How to Use Await Functions Within a Thread

Hi. I am so tired. I have been debugging this Discord bot for literally four hours straight. And I finally hit a roadblock.

Here’s my problem. I have a function in my bot that allows you to create and manage events. Luckily I got that part working, and then started work on the actual checking of events to see if any need execution or deletion.

Using Python’s threading library, I made a simple background task that does exactly that. But I have one problem. In the function it runs, it needs to send an announcement message to a specific channel. It fails to do that because it’s not awaited. But I can’t use await if the function isn’t async. And I can’t use async when the function’s running in a background thread. How do I do this? Here’s some simplified code:

def checkevents():
    channel = bot.get_channel(channel_id)
    channel.send(f'The event {event["name"]} is going on now, @everyone!')
    sleep(60)

thread = threading.Thread(target=checkevents, daemon=True)
thread.start()

This code is extremely simplified. Here’s a link to the entirety of the spaghetti-code abomination known as main.py.

I’m so close to getting this to work. Please help me.

I solved the issue. After a visit to the Discord.py docs, I realized that Discord.py literally has a function for this built in. It’s the task library. Simply write(in a cog):

from discord.ext import tasks

class Cog(commands.Cog):
    def __init__(self, bot):
      self.bot = bot
      self.backgroundFunctionToLoop.start()
  
    @tasks.loop(seconds=numOfSecondsBetweenExecution)
    def backgroundFunctionToLoop(self):
        print('Do stuff')