discord.py部分命令无法执行,新增命令后代码失效求助
问题分析与修复方案
核心问题:重复定义on_message事件
你在代码里多次用@client.event装饰on_message函数,Discord.py只会保留最后一个定义的on_message事件,前面的都会被覆盖。这就是为什么只有random_meme!相关逻辑可能触发,而last!、🤓后缀消息的处理完全失效,连client.process_commands也没机会执行。
其他代码错误
on_message_delete里的错误:await message.channel.send(channel, embed=embed):send方法无需传入channel参数,改成await message.channel.send(embed=embed)await channel.message.send("test"):正确写法是await channel.send("test"),不存在channel.message.send这种调用方式
on_member_unban事件的错误:- 事件函数不需要
self参数,改为async def on_member_unban(guild: discord.Guild, user: discord.User) response = ("The Following User Has Been Unbanned" + user):不能直接将User对象与字符串拼接,改为response = f"The Following User Has Been Unbanned: {user.name} ({user.id})"await client.process_commands(response):process_commands需要传入Message对象,这里直接发送消息到指定频道即可,比如channel = client.get_channel(channelid); await channel.send(response)
- 事件函数不需要
last!命令的错误:await client.process_commands(deleted_messages[0]):process_commands需传入Message对象,此处应直接发送记录的删除消息,比如await message.channel.send(deleted_messages[-1])(取最后一条删除的消息用索引-1而非0)
修复后的完整代码示例
import time import discord import redditeasy import requests import os # 请自行定义以下变量 # client = discord.Client(intents=...) # channelid = 你的目标频道ID # deleted_messages = [] @client.event async def on_message_delete(message): if message.author == client.user: return t = time.localtime() current_time = time.strftime("%c", t) embed = discord.Embed(title=f"{message.author.name} deleted a message", description="", color=0xFF0000) embed.add_field(name="Deleted Message", value=message.content, inline=True) embed.set_footer(text=f"Sent at {current_time}") channel = client.get_channel(channelid) if len(deleted_messages) == 6: del deleted_messages[0] final_deleted = f"{message.author.name}: |{message.content}| Sent at |{current_time}|" deleted_messages.append(final_deleted) await message.channel.send(embed=embed) await channel.send("test") @client.event async def on_member_unban(guild: discord.Guild, user: discord.User): response = f"The Following User Has Been Unbanned: {user.name} ({user.id})" channel = client.get_channel(channelid) await channel.send(response) @client.event async def on_message(message): # 优先处理命令(若使用commands.Bot框架) await client.process_commands(message) if message.author == client.user: return # 处理带🤓后缀的消息 if message.content.endswith("🤓"): await message.channel.send(f"Please shut the fuck up {message.author.name}.") # 处理last!命令 elif message.content == "last!": if deleted_messages: await message.channel.send(deleted_messages[-1]) else: await message.channel.send("No deleted messages recorded yet.") # 处理random_meme!命令 elif message.content == "random_meme!": post = redditeasy.Subreddit( client_id="你的client_id", client_secret="你的client_secret", user_agent="你的user_agent" ) try: postoutput = post.get_post(subreddit="dankmemes") with open('meme.jpg','wb') as f: response = requests.get(postoutput.content) f.write(response.content) channel = client.get_channel(channelid) await channel.send(file=discord.File('meme.jpg')) os.remove("meme.jpg") except Exception as e: await message.channel.send(f"Failed to get meme: {str(e)}") # 启动机器人 client.run("你的机器人令牌")
额外注意事项
- 确保机器人已开启对应Intents(如消息内容意图、成员意图),否则无法接收消息、删除事件等
- 若使用
commands.Bot框架,建议用@commands.command()装饰器定义命令,而非在on_message里判断内容,更规范且不易冲突 - 处理文件时优先用
with open语句,避免文件未正常关闭的问题 - 网络请求(如获取Reddit帖子)需添加异常处理,防止机器人崩溃
内容的提问来源于stack exchange,提问作者PugsHello
相关产品推荐
相关产品推荐

