All perfect praise be to Allah, The Lord of the Worlds. I testify that there is none worthy of worship except Allah, and that Muhammad is His slave and Messenger.
There is generally no way for the Muslim to be certain that he is affected with magic and the like, especially that the symptoms of diseases are often similar as it is known.
We do not like to hasten and judge that one is affected with magic, for example, as this may lead the person to fall prey to illusions and obsessions the evil consequences of which can be very bad.
Therefore, it is better to look for the normal reasons that are apparent and to consult doctors who are specialized in physical or psychological diseases. If they the nature of the disease becomes clear to them and they prescribe to the patient the appropriate medication, then he may be cured with Allah’s Will.
Jaabir narrated that the Prophet said: "There is a cure for every disease, so if the cure coincides with the disease (it is suitable for it), the person will be cured by the will of Allah." [Muslim]
However, if the doctors do not see any obvious medical reason for the symptoms, then it might be magic and the like, and its treatment is with Ruqyah.
It is better for the Muslim to perform Ruqyah on himself, but if he needs a righteous person to perform Ruqyah on him, then this is acceptable; but one should be careful not to go to magicians.
For more benefit on Ruqyah, please refer to Fataawa 4310, 31469, 13277, 170973 and 117025.
Do not forget to supplicate Allah earnestly, because it is Allah Who cures and removes distress. Allah Says (what means): {Is He [not best] who responds to the desperate one when he calls upon Him and removes evil and makes you inheritors of the earth? Is there a deity with Allah? Little do you remember.} [Quran 27:62]
Also, being in the company of righteous women helps greatly, especially those who give you hope and urge you to think good of Allah.
Additionally, you may have to change your lifestyle and abandon repetitive habits that lead to boredom; you are more aware of yourself in this regard.
Allah knows best.