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

Python开发Discord Bot查询Minecraft服务器状态异常求助

问题分析与解决方案

核心问题

你的Bot触发heartbeat blocked for more than 10 seconds错误的根本原因是:在Discord.py的异步事件循环中使用了同步阻塞的time.sleep(60),这会彻底卡住事件循环,导致Bot无法响应Discord网关的心跳检测,最终触发超时警告甚至被断开连接。

此外,player_count函数内的while i < 1循环完全冗余,只会增加代码复杂度;同时未处理服务器离线场景,可能导致属性访问报错。

修正后的完整代码

import discord
from discord.ext import commands
import minestat
import asyncio

def player_count():
    # 填入你的Minecraft服务器IP和端口
    ms = minestat.MineStat('cakalistan.aternos.me', 29049)
    if ms.online:
        return f"Sunucu Aktif! version {ms.version}  {ms.current_players} out of {ms.max_players} players."
    else:
        return "Sunucu Kapalı!"  # 处理服务器离线的情况

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

@client.event
async def on_ready():
    print(f"{client.user.name} is logged in")
    # 启动独立的定时更新任务
    asyncio.create_task(update_presence())

async def update_presence():
    while True:
        server_status = player_count()
        await client.change_presence(activity=discord.Game(name=server_status), status=discord.Status.idle)
        # 用异步sleep替代同步sleep,不会阻塞事件循环
        await asyncio.sleep(60)

# 替换为你的Bot Token
client.run("your_bot_token_here")

关键改动说明

  • 替换同步sleep为异步sleep:asyncio.sleep()会释放事件循环,让Bot能正常处理心跳和其他事件,彻底解决阻塞问题。
  • 移除冗余循环:player_count内的while循环无实际作用,直接单次查询即可获取服务器状态。
  • 添加离线容错:当服务器离线时返回友好提示,避免访问ms.version等属性时触发异常。
  • 拆分异步任务:把定时更新逻辑放到独立的异步函数中,用asyncio.create_task启动,确保on_ready事件能正常完成,不会被无限循环阻塞。

额外注意事项

  • 确保minestat库为最新版本,避免查询逻辑出现兼容性问题。
  • 禁止在Discord.py的异步事件/命令中使用任何同步阻塞操作(如time.sleep、长时间运行的同步函数),若必须使用,需放到线程池中执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:22:02