3

我试图弄清楚如何创建一个命令来“重新加载” Discord Bot 的命令,并允许我在添加新命令时保持机器人运行。

这只是让我的生活更轻松,所以我不必重新启动机器人。

我正在使用 discord.py 库与 discord API 进行交互。

我怎样才能做到这一点?

4

2 回答 2

6

这个问题可能迟到了,但无论如何我都会发布它

您应该查看 Discord.py 中所谓的“Cogs”是如何工作的。来自 Rapptz 的机器人(主要维护 Discord.py 的人)有一些很好的例子,如何将你的机器人组织成 Cogs 以及如何加载/卸载/重新加载它们(见cogs/admin.py)。

@commands.command(hidden=True)
@checks.is_owner()
async def load(self, *, module : str):
    """Loads a module."""
    try:
        self.bot.load_extension(module)
    except Exception as e:
        await self.bot.say('\N{PISTOL}')
        await self.bot.say('{}: {}'.format(type(e).__name__, e))
    else:
        await self.bot.say('\N{OK HAND SIGN}')

@commands.command(hidden=True)
@checks.is_owner()
async def unload(self, *, module : str):
    """Unloads a module."""
    try:
        self.bot.unload_extension(module)
    except Exception as e:
        await self.bot.say('\N{PISTOL}')
        await self.bot.say('{}: {}'.format(type(e).__name__, e))
    else:
        await self.bot.say('\N{OK HAND SIGN}')

@commands.command(name='reload', hidden=True)
@checks.is_owner()
async def _reload(self, *, module : str):
    """Reloads a module."""
    try:
        self.bot.unload_extension(module)
        self.bot.load_extension(module)
    except Exception as e:
        await self.bot.say('\N{PISTOL}')
        await self.bot.say('{}: {}'.format(type(e).__name__, e))
    else:
        await self.bot.say('\N{OK HAND SIGN}')

摘自cogs/admin.py

于 2017-01-07T00:41:05.460 回答
0

You can just use the basic reload built into discord.py

Here is an example of how my reload command is done.

@bot.command()
@commands.is_owner()
async def reload(ctx, extension):
    bot.reload_extension(f"cogs.{extension}")
    embed = discord.Embed(title='Reload', description=f'{extension} successfully reloaded', color=0xff00c8)
    await ctx.send(embed=embed)

Sends an embeded message when the cog is reload but you can always just do ctx.send(f'{extension} reloaded)

于 2021-09-11T15:51:31.060 回答