You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让discord.py机器人返回触发其响应的关键词?

Discord.py 机器人自动识别触发关键词并动态回复

要实现机器人自动识别触发消息的关键词,并根据匹配到的词生成回复,只需调整代码逻辑,从仅判断存在性改为定位具体匹配的关键词:

修改后的完整代码

@commands.Cog.listener()
async def on_message(self, message):
    if message.author == self.bot.user:
        return
    msg = message.content
    
    trigger = ["cat", "dog", "Snake", "Rabbit"]
    
    # 遍历触发词列表,寻找匹配项
    for animal in trigger:
        if animal in msg:
            embed = discord.Embed(description=f"{animal} is the best animal!")
            await message.channel.send(embed=embed)
            break  # 找到第一个匹配项后停止循环,避免重复发送

关键修改说明

  • 替换原有的any()判断逻辑,改为遍历触发词列表,逐个检查是否存在于消息内容中
  • 直接将匹配到的关键词赋值给animal变量,动态生成对应回复
  • 添加break语句,防止同一条消息包含多个触发词时重复发送回复

可选优化:不区分大小写匹配

如果需要忽略消息和触发词的大小写差异(比如用户发Cat也能触发cat的回复),可以修改匹配逻辑:

for animal in trigger:
    if animal.lower() in msg.lower():
        embed = discord.Embed(description=f"{animal} is the best animal!")
        await message.channel.send(embed=embed)
        break

内容的提问来源于stack exchange,提问作者Pandasie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:12:21