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 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01