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

Discord.py技术问题:从频道最近50条消息的Embed提取页脚内容

Discord.py 删除消息命令:提取消息Embed页脚内容

现有命令代码

#Delete Message Command
@bot.command()
async def deletemessage(ctx, *, messageid):
    await Webhooklogging(c['webhook'],f"{ctx.author} | {ctx.guild.id} -> {c['prefix']}deletemessage {messageid}")
    adminz = []
    for userid in users["users"]:
        if userid["isbotmod"] == "True":
            adminz.append(int(userid["userid"]))
    if ctx.message.author.id in adminz:
        for server in servers["servers"]:
            guild: Guild = bot.get_guild(int(server["guildid"]))
            if guild:
                channel: TextChannel = guild.get_channel(int(server["channelid"]))
                if channel:
                    perms: Permissions = channel.permissions_for(guild.get_member(bot.user.id))
                    if perms.manage_messages:
                            #get last 50 messages, if contains embed then get embed footer
    else:
        embed = discord.Embed(
            title = f'Error!',
            description = "You are not permitted to use this command!",
            color=0x662a85)
        await ctx.send(embed=embed)

需求说明

需要在命令权限验证通过后,实现以下逻辑:

  • 获取目标频道最近50条消息
  • 检查每条消息是否包含Embed
  • 若消息存在Embed,提取其页脚内容

尝试的代码(待完善)

for msg in ctx.channel.history(limit=50):
    embedFromMessage = msg.embeds[0]
    print(embedFromMessage.footer)

完善后的代码实现

将原代码中注释的部分替换为以下逻辑:

# 异步遍历目标频道最近50条消息
async for msg in channel.history(limit=50):
    # 检查消息是否包含Embed
    if msg.embeds:
        # 遍历消息中的所有Embed(单条消息可能存在多个)
        for embed in msg.embeds:
            # 提取并处理Embed页脚
            if embed.footer:
                footer_text = embed.footer.text
                footer_icon_url = embed.footer.icon_url
                # 可根据需求替换为日志记录、发送通知等操作
                print(f"消息ID {msg.id} 的Embed页脚:文本={footer_text},图标URL={footer_icon_url}")
            else:
                print(f"消息ID {msg.id} 的Embed无页脚内容")

关键注意点

  1. 异步遍历:channel.history()返回异步生成器,必须用async for遍历,否则会触发运行时错误
  2. 避免索引越界:直接取msg.embeds[0]会在消息无Embed时抛出IndexError,需先判断msg.embeds是否非空
  3. 多Embed处理:单条消息可能包含多个Embed,需遍历msg.embeds而非仅取第一个元素
  4. 页脚存在性判断:部分Embed可能没有页脚,需先检查embed.footer是否存在再提取内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:58:10