如何让discord.py的on_message事件仅读取指定频道消息?
问题解决:Discord机器人on_message仅监听指定频道+恢复命令功能
问题分析
- 全频道消息被读取:你的
print语句写在频道ID判断之前,导致所有频道的消息都会触发控制台打印。 - 常规!前缀命令失效:当消息不在目标频道时,代码提前
return,没有执行await bot.process_commands(message),导致机器人无法处理任何频道的前缀命令。
修复后的代码
@bot.event async def on_message(message): # 优先处理所有前缀命令,确保常规命令正常生效 await bot.process_commands(message) # 跳过机器人自身发送的消息 if message.author == bot.user: return # 仅处理指定频道的消息 target_channel_id = 1221858607000326186 if message.channel.id != target_channel_id: return # 现在只有指定频道的消息才会触发打印 print("This print shows in console only for the target channel's messages.") if 'vouch' in message.content.lower() and message.mentions: check_db_connection() mentioned_user = message.mentions[0] cursor.execute("SELECT * FROM midman_information WHERE midman_user LIKE %s", (f"%<@{mentioned_user.id}>%",)) result = cursor.fetchone() if result: vouch_count = result[2] + 1 cursor.execute("UPDATE midman_information SET vouch_count = %s WHERE midman_user = %s", (vouch_count, result[1])) db_config.commit() log_channel = bot.get_channel(1221858628173041674) embed = discord.Embed(title="Vouch Logged", description=f"{message.author.mention} has given a vouch to {mentioned_user.mention} | `{vouch_count}` vouches", color=0x2b2d31) embed.set_thumbnail(url=thumbnail) embed.set_footer(text="Lunar Services") await log_channel.send(embed=embed) else: await message.delete()
关键修改点
- 提前处理命令:把
await bot.process_commands(message)移到最开头,确保所有频道的前缀命令都能被机器人正常处理,不会因为频道判断提前return而失效。 - 调整打印位置:将
print语句移到频道ID判断之后,只有当消息来自目标频道时才会打印内容。 - 提取目标频道ID为变量:方便后续维护修改,代码可读性更高。
内容的提问来源于stack exchange,提问作者RealBytex
相关产品推荐
相关产品推荐

