How do you treat rapid heartbeat from cocaine or ecstasy?

Depends. That would depend on the exact heart rhythm. But the most important answer is to stop using dangerous drugs which can kill you.
Medications. Although the effect of Cocaine and ecstasy are different on the body when used the mainstay is sedatives and medications to slow the heart rate generally we avoid beta blockers as they can cause vasoconstriction so we may use a medication like diltiazem, for rate control and sedatives for the anxiety caused by both of these treatment is based on symptoms.