如何使用Discord.py让Discord机器人状态显示其当前所在的服务器数量
实现Discord机器人实时展示服务器数量状态的方法
核心实现逻辑非常简单:定时触发状态更新任务,每次更新时拉取当前机器人加入的服务器(公会)总数,调用官方API更新机器人活动状态即可。也可以额外绑定服务器加入/退出的事件监听,实现状态的实时触发更新。
以下是两种主流开发框架的实现示例:
1. 基于discord.py(Python版本)实现
- 首先确保你使用的是discord.py v2.0及以上版本,需要先开启机器人的
Guilds权限 - 基础定时更新示例代码:
import discord from discord.ext import tasks, commands intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) # 每5分钟更新一次状态,频率可自行调整,避免太高触发限流 @tasks.loop(minutes=5) async def update_guild_count_status(): guild_count = len(bot.guilds) # 状态可自定义为「观看」「收听」等其他类型,这里默认是游戏状态 await bot.change_presence(activity=discord.Game(name=f"在{guild_count}个服务器中")) # 机器人初始化完成后再启动定时任务,避免未加载完服务器列表导致计数错误 @bot.event async def on_ready(): update_guild_count_status.start() print(f"已登录为 {bot.user}") bot.run("你的机器人Token")
- 如果需要加入/退出服务器时立刻更新,不需要等定时周期,可额外添加两个事件监听:
@bot.event async def on_guild_join(guild): guild_count = len(bot.guilds) await bot.change_presence(activity=discord.Game(name=f"在{guild_count}个服务器中")) @bot.event async def on_guild_remove(guild): guild_count = len(bot.guilds) await bot.change_presence(activity=discord.Game(name=f"在{guild_count}个服务器中"))
2. 基于discord.js(JavaScript/TypeScript版本)实现
- 建议使用discord.js v14及以上版本,示例代码如下:
const { Client, GatewayIntentBits, ActivityType } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); function updateGuildCountStatus() { const guildCount = client.guilds.cache.size; client.user.setActivity({ name: `在${guildCount}个服务器中`, type: ActivityType.Playing // 可替换为Watching/Listening/Streaming等类型 }); } client.on('ready', () => { console.log(`已登录为 ${client.user.tag}`); updateGuildCountStatus(); // 设置每5分钟定时更新 setInterval(updateGuildCountStatus, 5 * 60 * 1000); }); // 加入/退出服务器时触发即时更新 client.on('guildCreate', updateGuildCountStatus); client.on('guildDelete', updateGuildCountStatus); client.login('你的机器人Token');
注意事项
- 不要将状态更新频率设置得高于1分钟,高频调用很容易触发Discord的API限流,导致机器人临时无法调用接口
- 如果你的机器人加入的服务器超过1000个,需要在Discord开发者后台申请服务器成员意图(Server Members Intent),才能正确获取完整的服务器列表
内容的提问来源于stack exchange,提问作者fargo
相关产品推荐
相关产品推荐

