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

discord.py cog中on_message调用jump_url触发无差别spam问题求助

问题根因

你现在的代码存在2个核心逻辑缺失,导致无差别触发记录:

  • 没有添加「过滤机器人自身/其他机器人消息」的判断逻辑
  • 完全没有实现「检测消息是否包含链接」的校验,只要接收到消息就直接生成记录,和你的需求不符

修复方案

1. 先添加消息过滤逻辑

在on_message函数最开头添加判断,过滤掉机器人自身发送的消息,也可以顺便过滤所有机器人发的消息避免其他机器人的内容被误记录:

# 过滤自身发送的消息
if message.author == self.bot.user:
    return
# 可选:过滤所有机器人发送的消息
if message.author.bot:
    return

2. 添加链接检测逻辑

用正则匹配消息内容中是否包含HTTP/HTTPS协议的链接,没有匹配到就直接终止处理:

import re
# 匹配URL的正则规则
URL_PATTERN = re.compile(r'https?://\S+')
if not URL_PATTERN.search(message.content):
    return

3. (可选)保留命令处理能力

如果你的机器人同时支持前缀指令,需要在on_message函数末尾添加以下代码,避免事件拦截正常指令的执行:

await self.bot.process_commands(message)

完整修正后代码参考

import re
import discord
from discord.ext import commands

URL_PATTERN = re.compile(r'https?://\S+')

class YourCogName(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message): 
        # 过滤所有机器人消息
        if message.author.bot:
            return
        # 检测是否包含链接
        if not URL_PATTERN.search(message.content):
            return
        
        # 只有符合条件的消息才会执行后续记录逻辑
        embed=discord.Embed(title="Message from {} contains a link ".format(message.author.name), description="", color=0x607d8b)
        embed.set_thumbnail(url="https://cdn.discordapp.com/avatars/9005083965732483134/14fcc0c2d369d9f4d742d9e8471d8536.webp?size=1024")
        embed.add_field(name="Message:" ,value=message.jump_url, inline=True)
        
        # 你自己的存储/发送逻辑
        # ...
        
        # 保留命令处理能力
        await self.bot.process_commands(message)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:05