Reputation: 27
I have a simple python bot within discord.
Lets say my code is as follows:
@client.command(pass_context=True)
async def test(ctx):
await asyncio.sleep(500)
await ctx.send("Hello!")
This code will have the bot wait 500 seconds before sending "Hello! in chat. If I shutdown my bot and restart it, this timer will obviously be lost and unsaved.
How can I carry this function out across restarts and such?
Upvotes: 0
Views: 42
Reputation: 661
The way I implement something like this is with a try-finally loop, the finally part executes even if you stop/restart your bot (not with every method of killing the process)
try:
client.run(TOKEN)
finally:
save('data.json', data)
To make this work you would expand your command that requires restart with a part that saves to a global dictionary/list. Something like (hellosave is the global list here):
hellosave.append((time.time() + 500, ctx.channel.id))
await asyncio.sleep(500)
await ctx.send("Hello!")
hellosave.pop(0)
As save() you would take that global dict/list and save it in some format (you can do it any way you'd like, from pickling to printing it in a .txt file [I chose json here cuz I needed it to be readable, that might not be the case in your case])
Next time you boot up your bot, in the on_ready() event you look for the contents of that file and restart the function based on the data saved in it, like for example your hello case you'd check if the time in the saved event has already passed, if it has you send it immediately (or not at all) if it hasnt you create a task with asyncio.create_task
that waits for the amount it needs (time.time() - hellotime) [to make this work you have to save the channel id, like I did in my example]
Upvotes: 1