I have gone through periods of very bad sleeplessness in my life. Often, at these times, I have found myself using my time in bed to think of all the things, often long in the past, that I have done that were bad mistakes, big embarrassments, big failures. I would punish myself by reliving the pain and loss and embarrassment over and over.
What did I do to fix my problem? Partly, I just survived. Getting older helps. Mostly, I learned to forgive myself for my past failures. I try to concentrate on life now, hour-by-hour, one day at a time, one foot in front of the other, step by step. To some extent, medications have helped.
I have learned to improve the place and way I sleep. I make sure it's dark and safe. I play comforting sounds very softly all night long to mask out the sounds that otherwise would distract and disturb me. I wrap myself tightly and warmly. I try to avoid having potential sleep interruptions around. I don't go bed before I'm sleepy, and I don't read in bed. I exercise for the pleasure and stress relief it brings me. Exercise has been a great help to me in starting a "virtuous cycle" in my life.
Mostly, I just have learned to become kinder to myself, and more self-forgiving. I have at the same time become more forgiving and kinder to others. I see pieces of myself in everybody else, and it brings me closer to understanding and empathizing with them. I understand now that these things I feel inside myself, I have in common with the rest of humanity, are part of being human.
Are there any magic answers to sleeplessness or insomnia? I don't think so. When I work out something is making me feel bad, I try to fix it, or leave it behind. If something makes me feel good, I do more of it. I try to become sensitive to what is keeping me awake. I talk with it. I have a conversation with it. I try to find out what it wants. Then I try to accept it, forgive it, change it or else leave it behind me.