Python开发Discord机器人多on_message事件失效问题求助
Discord机器人多消息事件失效问题解决方法
问题根源
你遇到的核心问题有两个:
- 重复注册事件导致覆盖:Discord.py中,同一个事件(比如
on_message)多次用@client.event装饰定义时,只会保留最后一个注册的处理函数,前面的所有事件逻辑都会被覆盖,这就是前三个消息匹配完全失效的原因。 - 语法缩进错误:最后一个
on_message事件的url_pattern定义和if判断块没有缩进在函数内部,会触发语法错误,甚至导致机器人无法正常启动。
修复方案
把所有消息匹配逻辑合并到单个on_message事件处理函数中,同时修正缩进问题,确保所有逻辑都在函数范围内执行:
import discord from discord.ext import commands import re client = commands.Bot(command_prefix="?", intents=discord.Intents.all()) @client.event async def on_ready(): print("RickGrBot Is Connected With Discord") @client.command() async def ping(ctx): await ctx.send("Pong!") @client.command() async def hallo(ctx): await ctx.send("Hallo!") @client.event async def on_message(message): # 先处理命令,确保?ping、?hallo等命令正常生效 await client.process_commands(message) # 定义所有需要匹配的URL和对应回复 url_mappings = [ (r'https?://tenor.com/view/im-so-drunk-i-barely-can-see-gif-18529125', "Gijs."), (r'https?://cdn.discordapp.com/attachments/1042805105658953808/1089794665001263114/Screenshot_2023-01-01-23-12-25-177_com.android.chrome.png', "Brandon."), (r'https?://cdn.discordapp.com/attachments/1042805105658953808/1089802868946636831/Screenshot_2022-10-24-18-06-13-64_1c337646f29875672b5a61192b9010f9.jpg', "dylan."), (r'https?://tenor.com/view/angry-little-girl-annoyed-cute-gif-22673877', "Rick.") ] target_channel = client.get_channel(1089903003739361312) for pattern_str, reply in url_mappings: url_pattern = re.compile(pattern_str) if url_pattern.search(message.content): await target_channel.send(reply) # 如果希望匹配到一个URL后就停止检查,可添加break # break client.run("MY_TOKEN")
额外优化说明
- 使用列表存储URL和回复的映射,让代码更简洁易维护,后续新增匹配规则只需在列表中添加条目即可。
- 提前获取目标频道对象,避免重复调用
get_channel,提升执行效率。 - 若需要同一消息中匹配多个URL并发送多条回复,可移除注释中的
break;若只需匹配第一个符合条件的URL,保留break即可。
内容的提问来源于stack exchange,提问作者RickGrGamen
相关产品推荐
相关产品推荐

