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

如何在discord.py中获取并输出所有频道的ID?

在discord.py中同时获取文本频道名称与ID的实现方法

核心逻辑很简单,discord.py的TextChannel对象本身就带有id属性,你只需要在输出频道名称的同时,加上对channel.id的调用即可。

示例代码(登录后自动遍历所有服务器频道)

import discord
from discord.ext import commands

# 配置必要的权限意图
intents = discord.Intents.default()
intents.guilds = True  # 开启服务器相关权限

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

@bot.event
async def on_ready():
    print(f"已成功登录:{bot.user}")
    # 遍历机器人加入的所有服务器
    for guild in bot.guilds:
        print(f"\n=== 服务器:{guild.name} ===")
        # 遍历当前服务器的所有文本频道
        for channel in guild.text_channels:
            # 同时输出频道名称和ID
            print(f"频道:{channel.name} | ID:{channel.id}")

# 替换成你的机器人TOKEN
bot.run("YOUR_BOT_TOKEN")

如果你需要通过指令触发查询

可以写一个自定义命令,让用户发送指令后获取当前服务器的频道信息:

@bot.command(name="channels")
async def list_channels(ctx):
    guild = ctx.guild
    # 拼接频道列表字符串
    channel_info = "\n".join([f"- {ch.name} | ID: {ch.id}" for ch in guild.text_channels])
    # 发送到频道
    await ctx.send(f"**{guild.name} 的文本频道列表**\n{channel_info}")

关键说明

  • channel.id是TextChannel对象的内置属性,直接调用就能获取频道的唯一数字ID
  • 你可以根据需求调整输出格式,比如用不同的分隔符或者排版方式

内容的提问来源于stack exchange,提问作者Mr.DOT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:55:41