Discord bot listen to commands on specific channel(Discord bot 侦听特定频道上的命令)
问题描述
我的 discord 机器人中有一堆命令,我想要做的是让机器人仅在某些命令来自特定频道时才收听它们.
I have a bunch of commands in my discord bot and what I am trying to do is to make the bot listen to some commands ONLY if they come from a specific channel.
这是一个命令示例:
@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)
我可以在我想要的特定渠道中给出答案,但我希望机器人仅在特定渠道中触发命令时才回复,而不是在任何地方.
I can give the answer in a specific channel that I want, but I want the bot to only reply if the command is triggered in a specific channel, not everywhere.
我尝试了 if/else 与 if message.channel.id = 'id' 但它不起作用.
I tried a if/else with if message.channel.id = 'id' but it doesn't work.
推荐答案
你可以写一个 check 来装饰你的命令.下面我们使用我们的目标频道 ID 创建一个 check,然后用该检查装饰我们的命令.
You can write a check that you can use to decorate your command. Below we create a check using our target channel id, and then decorate our command with that check.
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)
这篇关于Discord bot 侦听特定频道上的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Discord bot 侦听特定频道上的命令
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
