問題描述
我的 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 偵聽特定頻道上的命令的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!