You need to enable JavaScript to run this app. 如何使用discord.py实现每秒自动更新VPS PPS的Discord Embed?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用discord.py实现每秒自动更新VPS PPS的Discord Embed?

discord.py 实现Embed定时自动刷新的落地思路

结合你已经能独立获取PPS数据、生成对应Embed的基础,只需要依托discord.py原生的任务调度能力就能实现需求,不需要额外引入第三方定时框架,具体实现逻辑如下:

核心实现逻辑

discord.py 内置的discord.ext.tasks模块是专门做常驻定时任务的官方组件,相比手写while True + asyncio.sleep的裸循环,它自带异常兜底、生命周期绑定的能力,不会因为单次接口调用失败导致整个监控流程崩溃。

  • 用全局/类级别的变量存储第一次发送Embed时拿到的消息对象引用,避免每次更新都重新发新消息刷频道
  • 用@tasks.loop(seconds=1)装饰器定义每秒触发的监控循环
  • 循环内部拿到最新PPS数据后,直接调用原有消息的edit()方法更新Embed内容,不产生新的频道消息
  • 给循环加前置等待逻辑,等bot完全连上Discord网关后再启动任务,避免未认证报错

关键实现细节

  • 一定要加前置等待:通过@任务函数.before_loop装饰器绑定等待逻辑,内部调用await bot.wait_until_ready(),防止bot还没完成登录鉴权就开始发请求触发接口报错
  • 做好异常兜底:在循环内部捕获discord.HTTPException类的异常,遇到API限流、网络波动时不要让任务直接终止,等下一个1秒周期自动重试即可
  • 尽量减少无效请求:如果获取PPS的接口返回数据没有变化,可以直接跳过编辑操作,减少不必要的API调用,降低被限流的概率
  • 支持持久化:如果需要在bot重启后不重新发新的监控Embed,可以把第一次生成的监控消息对应的频道ID、消息ID存在本地配置文件里,bot启动时通过channel.fetch_message()重新拿到消息引用,赋值给存储变量即可无缝接续之前的监控流程

最小可运行示例代码

from discord.ext import commands, tasks
import discord

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
# 全局存储需要持续更新的监控消息对象
monitor_message: discord.Message = None

def get_current_vps_pps():
    # 替换成你已经实现的PPS获取逻辑
    return 12345

@tasks.loop(seconds=1)
async def update_pps_embed():
    global monitor_message
    if monitor_message is None:
        return
    try:
        pps_value = get_current_vps_pps()
        updated_embed = discord.Embed(
            title="VPS 网络状态监控",
            description=f"当前实时每秒包数:**{pps_value} PPS**",
            color=discord.Color.brand_green()
        )
        await monitor_message.edit(embed=updated_embed)
    except discord.HTTPException as err:
        print(f"Embed更新失败,等待下一轮重试:{err}")

@update_pps_embed.before_loop
async def wait_for_bot_ready():
    # 等bot完成全部初始化流程再启动定时循环
    await bot.wait_until_ready()

@bot.command(name="启动监控")
async def start_pps_monitor(ctx: commands.Context):
    global monitor_message
    # 首次发送初始Embed,留存消息引用
    init_embed = discord.Embed(title="VPS 网络状态监控", description="监控初始化中...")
    monitor_message = await ctx.send(embed=init_embed)
    # 避免重复启动定时任务
    if not update_pps_embed.is_running():
        update_pps_embed.start()

bot.run("你的bot令牌")

常见踩坑提醒

  • 别用send()代替edit()更新内容,1秒一条新消息会快速刷爆频道,既影响用户体验也极易触发Discord的垃圾消息限流
  • 别用同步的网络请求库(比如普通requests)去获取PPS数据,这类阻塞操作会卡死整个bot的事件循环,换成aiohttp这类异步请求库即可
  • 1秒的刷新间隔刚好符合API调用频率要求,不建议设置更短的间隔,否则会触发单接口调用频率限制

内容的提问来源于stack exchange,提问作者Jake.34

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 19:36:03