如果我想使用discord.py“在消息上”创建关闭并重新启动命令,我该怎么做?

时间:2019-02-05 18:30:14

标签: python discord discord.py repl.it

我的Discord Bot使用on_message函数运行discord.py。如果要使用此命令,创建一个将关闭的命令,另一个命令以重新启动我的Discord Bot,我该怎么做?

我在repl.it的服务器主机上运行了bot。 我将在下面链接一些代码,以便您可以了解on_message的意思:

  if message.content.upper().startswith("!SHUTDOWN"):
    if "534116283487223809" in [role.id for role in message.author.roles]:
      await client.send_message(message.channel, "*Shutting Down...*")
      time.sleep(0.5)
      #SCRIPT TO SHUTDOWN HERE

理想情况下,这些命令应分别用作!shutdown!restart,并且只能由我使用。

预先感谢, 高

2 个答案:

答案 0 :(得分:0)

要退出脚本,请致电sys.exit([arg])。要重新启动脚本,请查看os.exec*()

例如:

if message.content.upper().startswith("!SHUTDOWN"):
  if "534116283487223809" in [role.id for role in message.author.roles]:
    await client.send_message(message.channel, "*Shutting Down...*")
    time.sleep(0.5)
    os.exit(0) # the exit code, 0, means it exited successfully
if message.content.upper().startswith("!RESTART"):
  if "534116283487223809" in [role.id for role in message.author.roles]:
    await client.send_message(message.channel, "*Restarting...*")
    time.sleep(0.5)
    python = sys.executable
    os.execl(python, python, *sys.argv)

答案 1 :(得分:0)

您可以将代码置于while循环中,并使用client.logout()关闭Discord连接。 !restart命令将仅使用client.logout()而不会中断while循环,并且!shutdown也将使用client.logout(),但将调用break来取消while循环。

您可以创建命令来处理此问题,而不必将on_message事件中的所有内容弄乱。

from discord.ext import commands

while True:
    client = commands.Bot(command_prefix='!')

    @client.command(pass_context=True)
    async def restart(ctx):
        if "534116283487223809" in [role.id for role in ctx.message.author.roles]:
            await client.logout()

    @client.command(pass_context=True)
    async def shutdown(ctx):
        if "534116283487223809" in [role.id for role in ctx.message.author.roles]:
            await client.logout()
            break

    @client.event
    async def on_message(message)
        # do previous on_message stuff here
        await client.process_commands(message) # add at bottom to allow commands to work

    client.run('token')