Discord.py 使机器人在特定渠道做出回应

Discord.py making bot respond in certain channels

我希望使用我的 bot 的用户能够将 bot 配置为仅 运行 在某些频道中。当我使用 on_message 函数时,我能够通过检查消息来自哪个频道来实现这一点。现在我正在使用 Cogs,我不确定如何解决这个问题。

我的旧代码是这样的:

val_channels = ['a', 'b', 'c']
if message.channel in val_channels:
  # Do Something
else:
  print('The bot was configured to: ' + ', '.join(val_channels))

您可以验证 ctx.message.channel.id 是否与您的列表匹配。

class Greetings(commands.Cog):

    @commands.command()
    async def hello(self, ctx):
        """Says hello"""
        if ctx.message.channel.id in val_channels:
            await ctx.send('Hello!')
        else:
            await ctx.send('You can not use this command here.')

但是如果您仍想在 cog 中使用 on_message 事件,则需要修改装饰器。 Link to doc

class Greetings(commands.Cog):

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id in val_channels:
            # Do something
        else:
            print('The bot was configured to: ' + ', '.join(val_channels))