如果我想要去“的消息,”使用discord.py创建一个关机和重新启动命令,我怎么会去这样做呢?

问题描述 投票:-1回答:2

我的不和谐博特逃跑discord.py,使用ON_MESSAGE功能。如果我想用这个,创造条件,关机,另一个重新启动我的不和谐博特,我将如何做到这一点的命令?

我跑机器人关上repl.it.服务器主机下面我会链接一些代码,所以你可以看到我所说的意思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,并应只能由我来使用。

在此先感谢,H

python discord discord.py repl.it
2个回答
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)

0
投票

你可以把你的代码在while回路,并使用client.logout()关闭不和谐的连接。然后!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')
© www.soinside.com 2019 - 2024. All rights reserved.