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

Discord消息拉取报错:invalid literal for int() with base 10: 'guild id'求助

问题根因分析
  • 第一处核心错误:你直接硬编码了示例静态链接 'https://discordapp.com/channels/guild_id/channel_id/message_id',该字符串中的guild_id是纯文本占位符,不是用户实际发送的真实链接,拆分后取到的link[-3]就是字符串guild_id,无法转换为int类型,直接触发报错。
  • 第二处错误:ID取值索引逻辑混乱,Discord消息链接拆分后的结构为 ['https:', '', 'discordapp.com', 'channels', '服务器ID', '频道ID', '消息ID'],你原有代码中混淆了频道ID和消息ID的位置,还重复写了两次拉取消息的冗余逻辑。
修正后的实现方案

你需要先从用户发送的指令内容中提取真实的消息链接,再做解析拉取,参考代码如下:

if msg.content.lower().startswith('giveaway'):
    # 拆分指令内容,提取用户传入的消息链接,指令格式为 giveaway 消息链接
    parts = msg.content.split()
    if len(parts) < 2:
        await msg.channel.send("请附带要举报的Discord消息链接")
        return
    raw_link = parts[1]
    # 校验链接格式合法性
    if not (raw_link.startswith('https://discordapp.com/channels/') or raw_link.startswith('https://discord.com/channels/')):
        await msg.channel.send("请输入合法的Discord消息链接")
        return
    link_parts = raw_link.split('/')
    if len(link_parts) < 7:
        await msg.channel.send("链接格式不完整")
        return
    try:
        # 正确提取三个ID
        guild_id = int(link_parts[4])
        channel_id = int(link_parts[5])
        message_id = int(link_parts[6])
        # 拉取目标消息
        guild = client.get_guild(guild_id)
        if not guild:
            await msg.channel.send("无法找到对应服务器")
            return
        channel = guild.get_channel(channel_id)
        if not channel:
            await msg.channel.send("无法找到对应频道")
            return
        target_msg = await channel.fetch_message(message_id)
        # 发送到指定举报频道,替换下方星号为你的举报频道ID
        report_channel = client.get_channel(******************)
        await report_channel.send(f"{target_msg.author.mention} Report Spam {raw_link}")
        await msg.channel.send("举报已提交")
    except ValueError:
        await msg.channel.send("链接ID解析失败,请检查链接有效性")
    except Exception as e:
        await msg.channel.send(f"拉取消息失败:{str(e)}")
注意事项
  • 确保你的机器人拥有对应服务器、频道的查看消息、读取消息历史权限,否则无法拉取目标消息
  • 新增的校验和异常捕获逻辑,可以避免非法输入直接导致程序崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:09:04