此代码:
await Bot.close()
用于注销Bot。
问题是我想写一个重新启动命令,如下所示:
@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)
问题是,当Bot关闭时,必须重新启动shell,否则程序将无法继续运行{seconds}sec.
如何创建一个重新启动Bot的命令
提前感谢
因此,您应该能够在不关闭终端的情况下断开连接,然后重新连接。
请注意,我使用的是.connect()
而不是.login()
,因为当你关闭连接时,你实际上并没有退出。
编辑:我没有注意到,但Dominik提到睡眠不是异步的,所以你可以通过导入asyncio并使用await asyncio.sleep(seconds)
使其异步(尽管这是不必要的(,也可以像以前一样使用time.sleep函数,但不需要等待。
@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)
您可以使用os.execv()
函数完全重新启动bot。
"[…]执行一个新程序,替换当前进程;[它不]返回";
实现将是
os.execv("path-to-python-bin", ["python"] + ["absolute-path-to-bot-main-file"])
例如
os.execv("/usr/local/bin/python3.8", ["python"] + ["/home/user/test/bot.py"])
您的命令可以像这个一样执行
@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将为您处理所有注销和重新登录。无需单独调用函数。
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()
这将是完美的工作。你的代码不起作用,因为一旦机器人通过使用bot.close停止,它就不能自动打开