首页 > 解决方案 > 我一直未能在 discord.py“文本频道,语音频道”中使用“ctx.guild.channels”枚举(列出)服务器中的所有频道

问题描述

我想使用 discord.py 列出服务器中的所有频道(带有名称、id 等信息)。为了实现它,我编写了以下代码。

@bot.command()
async def enumurate_channels(ctx):

    channels = ctx.guild.channels

    print("The number of channels", len(channels))

    for channel in channels:
        print(channel.name)  

并且请假设我们要处理包含 2 个频道的服务器,其中一个是文本频道中的“通用”,另一个是语音频道中的“通用”

当我运行上面的命令时,我得到了以下内容。

The number of channels 4
Text Channels
Voice Channels
general
General

首先显示的这两个 Text Channels,Voice Channels很烦人,因为它们实际上不是频道。

如何正确枚举服务器中的任何通道?

标签: discord.py

解决方案


快速解决方案之一是使用属性.type

@bot.command()
async def enumurate_channels(ctx):

    channels = ctx.guild.channels

    print("The number of channels", len(channels))

    for channel in channels:
        print(channel.type) # CHANGED HERE.

可能的输出channel.type 是“类别”、“文本”、“语音”

处理这个属性.type来做你想做的事。


推荐阅读