First, with the power off, open the computer case and disconnect the 4-pin power plug from the drive. Then at least the drive won't open and close while you try to figure out what's wrong.
One possibility is that the front panel open/close button on the drive is sticking. Then the drive thinks you're always pressing the button. In that case, replace the drive. New DVD/CD burner drives are only $30 or so, so it isn't worth repairing one. I think you'll probably find the drive is just faulty.
Another possibility is that your computer has a virus. Random drive opening and closing was caused by a virus going around a while ago. I don't remember the virus name, but it was quite a while ago. Still, it's worth checking unless you're absolutely sure you have up-to-date antivirus software and you've been scanning your computer regularly. I would suggest downloading the free version of MalwareBytes' Anti-Malware
and doing a complete scan to see if it finds anything. If it does, let it correct the problem.
If it turns out to be a virus problem, don't forget to plug the power connector back into the CD drive when you've cleared the trouble.
Hope this helps, and thanks for using Fixya!