Python开发Discord大写消息删除机器人误判特殊字符如何解决
问题根源
你的判断逻辑存在根本性错误:数字、标点、符号类字符的.upper()返回值与原值完全一致,因此message.content.startswith(message.content.upper())对任何只含符号/数字的内容都会返回True,哪怕没有大写字母也会触发删除逻辑。
修复方案
调整判断逻辑:仅提取消息中的英文字母做全大写校验,还可以增加字母长度阈值,避免单字符、无字母的消息被误删。
修正后的代码如下:
import discord from discord.ext import commands # 合并冗余导入,新版discord.py需要显式声明意图 bot = commands.Bot(command_prefix='', intents=discord.Intents.all()) print("Starting...") @bot.event async def on_ready(): print("Logged on as {0.user}".format(bot)) @bot.event async def on_message(message): # 忽略机器人自身消息,避免循环触发 if message.author == bot.user: return # 提取消息中所有英文字母 letters = [c for c in message.content if c.isalpha()] # 校验规则:存在至少2个字母,且所有字母均为大写时才触发 if len(letters) >= 2 and all(c.isupper() for c in letters): await message.delete() args = message.content.split(" ")[1:] await message.channel.send(" ".join(args)) bot.run("你的机器人Token")
额外注意事项
- 目前Discord API要求显式开启消息内容权限,你需要登录Discord开发者后台,在对应机器人的设置页面打开
Message Content Intent开关,否则机器人无法读取消息内容 - 代码中已经移除了冗余的asyncio、重复Bot导入,减少不必要的依赖加载
- 如果不需要保留你原有的取第一个词之后内容重发的逻辑,也可以改成重发原消息的全小写版本,把重发逻辑替换为
await message.channel.send(message.content.lower())即可
内容的提问来源于stack exchange,提问作者Juan
相关产品推荐
相关产品推荐

