【问题标题】:How to get all text channels using discord.py?如何使用 discord.py 获取所有文本频道?
【发布时间】:2018-09-01 23:11:46
【问题描述】:

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

【问题讨论】:

    标签: channel discord discord.py


    【解决方案1】:

    他们在 discord.py (1.0) 的 newer version 中将 Client.servers 更改为 Client.guilds
    您也可以使用 bot 代替 Client (info)。
    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)
    

    【讨论】:

    • 谢谢!但是是否可以只获取列表中的频道名称?
    • @Jonathan 只需使用channel.name 作为它的名称,或者您也可以将频道对象转换为字符串str(channel),它会返回它的名称
    【解决方案2】:

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

    遍历这个列表,每个guild 类都包含channels,它返回服务器拥有的Channel 类的列表。此处的文档:https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.channels

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

    一个粗略的例子,说明如何列出所有 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)
    

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2022-01-16
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2021-10-28
      • 2021-03-13
      • 2020-10-22
      相关资源
      最近更新 更多