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

在Discord.py中如何实现机器人对触发关键词的空格忽略匹配?

实现方法

核心思路是先对消息内容做预处理,移除所有空格后再进行关键词匹配,即可无视用户输入的任意空格间隔。

方案1:基础实现(仅忽略普通半角空格)

直接移除消息内容中的所有半角空格后匹配,修改后的代码如下:

@client.event
async def on_message(message):
    if message.author.bot:
        return
    # 预处理:转小写后移除所有空格
    processed_msg = message.content.lower().replace(" ", "")
    # 合并相同回复的触发词判断
    if 'didiask' in processed_msg or 'whoasked' in processed_msg:
        await message.channel.send(f"{message.author.mention} Shut up, the world doesnt revolve around you.")
    if 'stfu' in processed_msg:
        await message.channel.send('Was I summoned?')

注:这里把原来的format换成了f-string写法,更简洁易读,如果你需要兼容旧版本Python可以换回原来的format写法。

方案2:进阶实现(忽略所有空白字符)

如果需要同时忽略全角空格、制表符、换行符等各类空白字符,可以用正则表达式做预处理,代码如下:

import re # 导入正则模块,放在文件头部即可

@client.event
async def on_message(message):
    if message.author.bot:
        return
    # 预处理:转小写后移除所有类型的空白字符
    processed_msg = re.sub(r'\s', '', message.content.lower())
    if 'didiask' in processed_msg or 'whoasked' in processed_msg:
        await message.channel.send(f"{message.author.mention} Shut up, the world doesnt revolve around you.")
    if 'stfu' in processed_msg:
        await message.channel.send('Was I summoned?')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:48:03