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

如何修复Discord.py automod cog中on_message事件的相关报错

问题修复方案

两个报错的直接解决方法

1. AttributeError: 'Mod' object has no attribute 'message'

触发该错误的原因有两处:

  • 你在on_message方法内错误尝试访问方法属性获取 guild id,原代码guild = await self.on_messgage.guild.id完全错误,直接替换为guild_id = message.guild.id即可,不需要await,也不需要访问self的相关属性。
  • 后续发送提醒消息时错误写了await client.message.channel.send,全局client对象没有message属性,直接替换为await message.channel.send。

2. TypeError: on_message() takes 1 positional argument but 2 were given

触发该错误的原因有两处:

  • on_message监听器方法缩进错误,被包含在了remove_profanity方法内部,导致方法注册时参数识别异常,需要把on_message方法的缩进调整到和Mod类其他方法同级。
  • 你当前所有的命令方法(kick_command、ban_command、unban_command等)缩进都在Mod类外部,没有作为Mod类的成员方法,调用时会缺失self参数,必须把所有命令方法缩进进Mod类内部。

其他必须修复的代码问题

  • MySQL语法适配:mysql.connector的参数占位符为%s不是?,所有涉及SQL参数传递的语句都要修改,示例:
# 修改前
cursor.execute("INSERT INTO mutes VALUES (?, ?, ?)", target.id, role_ids, getattr(end_time, "isoformat", lambda: None)())
# 修改后
cursor.execute("INSERT INTO mutes VALUES (%s, %s, %s)", (target.id, role_ids, getattr(end_time, "isoformat", lambda: None)()))
  • 机器人身份判断错误:if not message.author.client替换为if not message.author.bot,discord.py通过User.bot属性判断账号是否为机器人。
  • 黑名单词获取逻辑错误:执行SQL查询后需要主动拉取结果,execute方法本身没有返回值:
cursor.execute("SELECT word FROM blacklist;")
blacklist_words = [row[0] for row in cursor.fetchall()]

你可以基于这个结果列表自行添加违禁词检测逻辑。

  • 命令不触发修复:在on_message方法的最后一行添加await self.client.process_commands(message),否则你写的其他前缀命令不会被机器人响应。
  • 数据库连接参数错误:连接MySQL时database参数需要传入字符串,你直接传int类型的guild id会报错,修改为database=str(guild_id)。
  • 全局连接风险:不要使用全局的cnx和cursor变量,多服务器并发处理消息时会出现数据串扰,建议每次处理消息时创建的连接用完就关闭,或者使用连接池管理连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 23:45:03