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 侦听特定频道上的命令
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
