Discord机器人on_message事件下日志频道获取代码不执行如何修复
问题修复方案
核心错误原因
- 错误调用了不存在的
self.bot.guild属性:Discord.py的Bot实例本身就内置get_channel()方法,无需通过不存在的guild属性调用;你也可以从当前消息关联的服务器对象message.guild调用get_channel()方法,后者性能更高,你其他模块能正常运行大概率是没有使用self.bot.guild这个错误写法。 - 文件名不匹配:代码中读取的是
logchannel.json,但你提供的配置文件名为logchannels.json,多了一个s,会导致文件读取失败触发异常直接返回。 - 异常未打印日志:你当前捕获了异常但没有任何输出,无法定位具体错误点。
修复后的代码
@commands.Cog.listener() async def on_message(self, message): curseWord = ['bad words here'] msg_content = message.content.lower() if any(word in msg_content for word in curseWord): if message.channel.type == discord.ChannelType.private: return await message.delete() embed=discord.Embed(title="禁止违规词汇", description=f"{message.author.mention}, 你发送的内容包含违规词汇!", color=0x00FFFF) author = message.author pfp = author.avatar_url embed.set_author(name=f"{author}", icon_url=pfp) await message.channel.send(embed=embed) # 修正文件名和实际配置文件匹配 with open('logchannels.json', 'r', encoding='utf-8') as fp: log_channel_config = json.load(fp) try: if log_channel_config: print("1") # 修正get_channel调用方法,两种写法二选一即可 # 写法1:从当前服务器对象获取频道(性能更高) log_channel = message.guild.get_channel(log_channel_config[str(message.guild.id)]) # 写法2:从Bot全局实例获取频道 # log_channel = self.bot.get_channel(log_channel_config[str(message.guild.id)]) print("2") logembed=discord.Embed(title="机器人日志", description="检测到违规词汇", color=0x00FFFF) logembed.add_field(name="**消息内容:**", value=f"{msg_content}", inline=False) logembed.add_field(name="**发送用户:**", value=f"{message.author.name}", inline=False) logembed.set_author(name=f"{author}", icon_url=pfp) await log_channel.send(embed=logembed) else: print('3') return except (AttributeError, KeyError) as e: # 新增异常打印,方便排查其他问题 print(f"日志发送失败: {e}") return
额外优化建议
- 不要每次触发违规消息都读取一次配置文件,可以在Cog加载时就读取配置到内存,修改配置时再重载,减少IO开销。
- 可以增加配置不存在的判断,避免当前服务器没有配置日志频道时触发KeyError。
内容的提问来源于stack exchange,提问作者Coleman Ethington
相关产品推荐
相关产品推荐

