如何使用 discord.py 获取所有文本频道?

How to get all text channels using discord.py?

我需要获取所有频道来制作一个 bunker 命令,这使得所有频道只读。

假设您正在使用异步分支,Client class 包含 guilds,其中 returns 是 guild class 的列表是机器人连接到的。此处的文档:https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.guilds

遍历此列表,每个 guild class 包含 channels,其中 returns 是 Channel class 的列表服务器有。此处的文档:https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.channels

最后,遍历此列表,您可以检查每个 Channel class 的不同属性。例如,如果您要检查频道是否为文本,您可以使用 channel.type。此处的文档:https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel

一个粗略的例子,说明如何列出类型为 'Text':

的所有 Channel 个对象
text_channel_list = []
for server in Client.guilds:
    for channel in server.channels:
        if str(channel.type) == 'text':
            text_channel_list.append(channel)

要与 'text' 进行比较,channel.type 必须是一个字符串。

对于 discord.py 的旧版本,通常称为 async 分支,请使用 server 而不是 guild

text_channel_list = []
for server in Client.servers:
    for channel in server.channels:
        if str(channel.type) == 'text':
            text_channel_list.append(channel)

他们在 discord.py (1.0) 的 newer version 中将 Client.servers 更改为 Client.guilds
您还可以使用 bot 而不是 Client ().
并且 guild.text_channels 获取所有文本频道。
对于所有频道,您可以使用 bot.get_all_channels()

text_channel_list = []
for guild in bot.guilds:
    for channel in guild.text_channels:
        text_channel_list.append(channel)