首页 > 解决方案 > Discord bot 侦听特定频道上的命令

问题描述

我的不和谐机器人中有一堆命令,我想做的是让机器人只听一些来自特定频道的命令。

下面是一个命令示例:

@bot.command(name='bitcoin',
                brief="Shows bitcoin price for nerds.")
async def bitcoin(pass_context=True):
    url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json'
    response = requests.get(url)
    value = response.json()['bpi']['USD']['rate']
    await bot.send_message(discord.Object(id='<channel id is inserted here>'), "Bitcoin price is: " + value)
    # await bot.say("Bitcoin price is: " + value)

我可以在我想要的特定频道中给出答案,但我希望机器人仅在命令在特定频道中触发时才回复,而不是在任何地方。

我尝试了 if/else 与 if message.channel.id = 'id' 但它不起作用。

标签: pythondiscorddiscord.py

解决方案


你可以写一个check你可以用来装饰你的命令。下面我们check使用我们的目标通道 ID 创建一个,然后使用该检查来装饰我们的命令。

def in_channel(channel_id)
    def predicate(ctx):
        return ctx.message.channel.id == channel_id
    return commands.check(predicate)

@bot.command(name='bitcoin', brief="Shows bitcoin price for nerds.")
@is_channel('CHANNEL_ID')
async def bitcoin(pass_context=True):
    url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json'
    response = requests.get(url)
    value = response.json()['bpi']['USD']['rate']
    await bot.send_message(discord.Object(id='<channel id is inserted here>'), "Bitcoin price is: " + value)
    # await bot.say("Bitcoin price is: " + value)

推荐阅读