Reputation: 4098
This code:
await Bot.close()
is used to logout the Bot.
The problem is that i want write a restart command, like this:
@Bot.command()
async def OFF(ctx, seconds:float):
await ctx.message.delete()
embed = Embed(title = "OFF", description = f"{ctx.message.author.mention} turned off me for {round(seconds)} seconds", color = Color.red())
await ctx.send(embed = embed)
await Bot.close()
await sleep(seconds)
await Bot.login(token)
embed = Embed(title = "Turned on", description = f"I came back after {round(seconds)}", color = Color.green())
await ctx.send(embed = embed)
The problem is that when the Bot closes, the shell must be restarted, otherwise the program won't keep running after {seconds}sec.
How could i create a command which restarts the Bot?
Thanks in advance
Upvotes: 1
Views: 2399
Reputation: 91
import sys
def restart_bot():
os.execv(sys.executable, ['python'] + sys.argv)
@bot.command(name= 'restart')
async def restart(ctx):
await ctx.send("Restarting bot...")
restart_bot()
This will work perfect . Your code doesnt works because once bot is stops by using bot.close it cant be turned on automatically
Upvotes: 0
Reputation: 438
So you should be able to just disconnect and then reconnect without the terminal closing.
Notice I'm using .connect()
instead of .login()
as when you close the connection you're not actually logging out of discord.
Edit: I hadn't noticed but Dominik mentioned the thats sleep is not asynchronous and so you can either make it asynchronous (although its unnecessary), by importing asyncio and using await asyncio.sleep(seconds)
or just use the time.sleep function as you were but without the await.
@Bot.command()
async def OFF(ctx, seconds:float):
await ctx.message.delete()
embed = Embed(title = "OFF", description = f"{ctx.message.author.mention} turned off me for {round(seconds)} seconds", color = Color.red())
await ctx.send(embed = embed)
await Bot.close()
sleep(seconds)
await Bot.connect()
embed = Embed(title = "Turned on", description = f"I came back after {round(seconds)}", color = Color.green())
await ctx.send(embed = embed)
Upvotes: 2
Reputation: 2289
You can completely restart you bot by using the os.execv()
function.
"[...] execute[s] a new program, replacing the current process; [it does] not return"
The implementation would be
os.execv("path-to-python-bin", ["python"] + ["absolute-path-to-bot-main-file"])
for example
os.execv("/usr/local/bin/python3.8", ["python"] + ["/home/user/test/bot.py"])
Your command could be implemented like this
@Bot.command()
async def OFF(ctx, seconds:float):
await ctx.message.delete()
embed = Embed(title = "OFF", description = f"{ctx.message.author.mention} turned off me for {round(seconds)} seconds", color = Color.red())
await ctx.send(embed = embed)
os.execv("path-to-python-bin", ["python"] + ["absolute-path-to-bot-main-file"])
Discord.py will handle all logouts, and re-logins for you. No need to call the functions seperately.
Upvotes: 0