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

Discord.py如何将全部guild id写入JSON文件以供slash commands使用

Discord.py 提取服务器ID存入JSON实现方案

前置依赖

确保你已经安装v2.0及以上版本的discord.py,同时在Discord开发者后台的Bot设置页开启Server Members Intent和Guilds Intent。

完整实现代码

import discord
from discord.ext import commands
import json

# 初始化bot,可根据自身需求调整intents配置
intents = discord.Intents.default()
intents.guilds = True # 必须开启服务器访问权限才能读取guild列表
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    # 遍历所有bot加入的服务器,提取ID存入列表
    guild_ids = [guild.id for guild in bot.guilds]
    # 将ID列表写入JSON文件
    with open("guild_ids.json", "w", encoding="utf-8") as f:
        json.dump(guild_ids, f, indent=4, ensure_ascii=False)
    print(f"已成功提取{len(guild_ids)}个服务器ID,已存入guild_ids.json")
    
    # 如需直接用该ID列表同步slash命令,可添加以下代码
    # await bot.tree.sync(guilds=[discord.Object(id=gid) for gid in guild_ids])

# 替换为你自己的Bot Token运行即可
bot.run("你的Bot Token")

输出说明

运行后生成的guild_ids.json文件为纯ID数组,格式如下:

[
    123456789012345678,
    876543210987654321
]

注意事项

  • 提取操作必须在on_ready事件触发后执行,此时bot已完成所有服务器数据的拉取,提前执行会得到空列表
  • 测试阶段同步slash命令时,直接读取JSON中的ID列表,转成discord.Object对象传入同步方法的guilds参数即可,无需手动逐个填写ID
  • 不要将生成的JSON文件、Bot Token提交到公开代码仓库,避免敏感信息泄露

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:00:03