You need to enable JavaScript to run this app. discord.py如何实现将指定消息始终保持在最新消息位置?
优惠活动
大模型
产品
解决方案
定价
更多

discord.py如何实现将指定消息始终保持在最新消息位置?

这个需求完全可以在discord.py中实现,核心实现逻辑是记录上一条发送的sticky消息ID,每次推送新sticky前先删除旧消息。

修改后完整代码示例

import json
import discord
from discord.ext import commands

class StickyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        # 存储上一条sticky消息ID,如需持久化可写入sticky.json避免重启丢失
        self.last_sticky_id = None

    @commands.Cog.listener()
    async def on_message(self, message):
        # 过滤bot自己发的消息,避免循环触发事件
        if message.author.bot:
            return
        if not message.content or message.channel.id != 777073533687300106:
            return
        
        # 先删除已有的旧sticky消息
        if self.last_sticky_id is not None:
            try:
                old_sticky = await message.channel.fetch_message(self.last_sticky_id)
                await old_sticky.delete()
            except discord.NotFound:
                # 旧消息已被手动删除,重置ID记录即可
                self.last_sticky_id = None
        
        # 构造sticky内容Embed
        embed = discord.Embed(color=discord.Colour.gold())
        with open('sticky.json', 'r') as file:
            data = json.load(file)
        sorted_data = dict(sorted(data.items(), reverse=True, key=lambda item: item[1]))

        # 修复原代码循环仅保留最后一条内容的问题,支持多条sticky拼接展示
        embed_desc = []
        for pos, (id, text) in enumerate(sorted_data.items()):
            embed_desc.append(f"{pos+1}. {text}")
        embed.description = "\n".join(embed_desc)

        # 发送新sticky并记录消息ID
        new_sticky = await message.channel.send(embed=embed)
        self.last_sticky_id = new_sticky.id

核心改动说明

  • 新增bot自身消息过滤逻辑,避免bot发送sticky时再次触发事件导致循环推送
  • 新增旧sticky删除流程,捕获消息不存在的异常避免程序报错
  • 修复原代码遍历排序后数据仅保留最后一条内容的问题,支持多条sticky内容展示
  • 每次发送新sticky后记录消息ID,供下次触发事件时删除使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:15:03