discorddiscord.pybotsatexit

How can I fix a RuntimeWarning using the 'atexit' module?


Recently, I've been wanting to create an exit handler for my discord bot which sends an embed every time it goes offline. I found out through some quick research about the atexit module. I tried to incorporate it in my code like so:

import atexit
# Also other imports which make discord.py and interactions work...

def my_exit_handler():
    print("Exiting the program")
    time = get_current_timestamp() # this works
    embed = discord.Embed(
        title=" ",
        description=f"## 🔁 Bot is Restarting. Time now: <t:{time}> (<t:{time}:R>)",
        color=0x005300  # Green color
    )
    channel_id = 1149359551464882229
    final = bot.get_channel(channel_id)
    final.send(embed=embed)
    save_thread_data() # For other parts of my code
    save_leaderboard_data() # For other parts of my code

# ALL OF MY MAIN.PY CODE..

atexit.register(my_exit_handler)

bot.run('my token') 

however, any time I try to make it work, these errors pop up:

/home/container/main.py:186: RuntimeWarning: coroutine 'Messageable.send' was never awaited
  final.send(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

How can I fix them?

I'm expecting to see an embed pop up at that ID adress with the embed I asked.

I also tried making it into an async def but that brough up a whole other set of problems.


Solution

  • Messageable.send is an asynchronous functions; asynchronous functions need to be awaited with the await keyword.

    await final.send(embed=embed)
    

    For more: awaitables.

    This also means that the my_exit_handler function also has to be asynchronous.

    async def my_exit_handler():
        ...