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

discord.py如何识别消息内容中的关键词触发机器人自动回复

discord.py 关键词触发回复实现方案

基础实现(单关键词匹配)

把原代码中的全等判断改为成员运算符判断即可,为了避免大小写差异导致匹配失败,建议统一将消息内容转为小写后再判断。

@client.event
async def on_message(message):
    # 避免机器人自己触发自己
    if message.author == client.user:
        return
    # 匹配关键词duck,忽略大小写
    if "duck" in message.content.lower():
        await message.channel.send("🦆")

进阶用法

  • 多关键词匹配:如果需要同时匹配多个关键词,可以用列表+any()函数实现
@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # 定义需要匹配的关键词列表
    trigger_keywords = ["duck", "quack", "鸭子"]
    # 任意关键词命中则触发
    if any(keyword in message.content.lower() for keyword in trigger_keywords):
        await message.channel.send("🦆")
  • 精确单词匹配(避免前缀/后缀误判):如果不希望类似duckling(小鸭子)这类包含关键词的衍生词触发匹配,可以用正则表达式匹配单词边界
import re

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # \b代表单词边界,re.IGNORECASE忽略大小写
    if re.search(r'\bduck\b', message.content, re.IGNORECASE):
        await message.channel.send("🦆")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:57:01