【问题标题】:How do I implement a shutdown and restart commands in "on message"?如何在“on message”中实现关机和重启命令?
【发布时间】:2019-06-29 15:39:49
【问题描述】:

我的 Discord 机器人通过 discord.py 运行,使用 on_message 函数。如何创建关闭命令和重启 Bot 的命令?

我的机器人在 repl.it 上托管的服务器上运行。

代码:

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 SHUT DOWN HERE

理想情况下,命令应该响应"!shutdown""!restart",并且只能由我使用。

【问题讨论】:

    标签: python discord discord.py repl.it


    【解决方案1】:

    您可以将代码放在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')
    

    【讨论】:

    • 我不明白restartshutdown 有何不同。你在谈论一些循环,但我没有看到。
    • @Neuron while True 是一个无限循环,将在break 处停止,它只存在于shutdown 命令中
    • 谢谢,我错过了while True.. ;)
    【解决方案2】:

    要退出脚本,您可以调用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)
    

    【讨论】:

    • 如何将它添加到我的代码中? @FlyingSixtySix
    • 我添加了一个示例。我不完全确定这些是否适用于 repl.it,但值得一试。
    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 2020-04-02
    • 2011-12-14
    • 2021-05-06
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多