python - 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' 但它不起作用。
解决方案
你可以写一个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)
推荐阅读
- reactjs - 如何在 Ant Design Pro 中禁用 Umi UI 气泡?
- node.js - 如何从 Sentinel 获取 Redis 主机的主机名
- mysql - 尝试在与 Pomelo.EntityFrameworkCore.MySql 相关的 dotnet core 3.1 中添加迁移时出错
- c - 我可以安全地调用未知来源的函数吗?
- chatbot - 如何在 Rasa<->Google 聊天集成后从发送到 Rasa 服务器的环聊消息中获取用户电子邮件 ID
- python - 如何访问一系列 MultiIndex 值?
- flutter - 当 Navigator.push 在颤动中移动到另一个屏幕时如何调用 AlertDialog
- java - Java的新手试图弄清楚如果给定某个输入,如何在do-while循环中跳回
- wso2 - WSO2 IS 如何使用用户证书获取 oauth2 令牌
- javascript - 如何将 const 变量传递给事件处理程序