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

PyCord自定义状态无法定时更新问题求助

问题分析与修复方案

你的机器人状态仅在启动时更新一次,核心问题如下:

  • randomstatus函数仅修改了局部变量status,未调用bot.change_presence()实际更新机器人状态
  • randomstatus函数从未被启动,on_ready事件仅执行了一次状态设置,未触发循环更新逻辑
  • members变量仅在机器人启动时计算一次,后续服务器成员数变化时不会自动更新

修复步骤

  1. 在状态循环中触发更新:每次随机选择状态后,调用bot.change_presence()同步更新机器人在线状态
  2. 启动状态循环任务:在on_ready事件中,用asyncio.create_task()启动状态更新的循环任务
  3. 实时计算成员数:每次更新状态时重新计算成员总数,确保状态里的成员数是最新值
  4. 优化循环条件:用bot.is_ready()替代字符串变量o,逻辑更安全可靠

修复后的完整代码

import random
import asyncio
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

# 动态生成状态消息(实时计算成员数)
def get_status_messages():
    total_members = sum(guild.member_count for guild in bot.guilds)
    return [
        "Made with ❤️ by epdev",
        "Watching over the epdev server",
        f"Helping {total_members} members!",
    ]

async def randomstatus():
    await bot.wait_until_ready()  # 等待机器人完全就绪后再执行循环
    while bot.is_ready():
        await asyncio.sleep(10)
        status_list = get_status_messages()
        selected_status = random.choice(status_list)
        await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game(name=selected_status))

@bot.event
async def on_ready():
    print('Main Bot Status: Running')
    # 启动状态更新的异步任务
    asyncio.create_task(randomstatus())

bot.run("你的机器人令牌")

额外注意

  • 需确保机器人在Discord开发者后台开启了Server Members Intent权限,否则guild.member_count可能无法正确获取成员数
  • wait_until_ready()用于避免机器人未完全连接Discord时执行状态更新导致的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:25:16