Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all text channels using discord.py?

I need to get all channels to make a bunker command, which makes all channels read only.

like image 839
Veestire Avatar asked Mar 23 '18 09:03

Veestire


People also ask

How do you fetch channels on discord PY?

How do I get channel ID channel Discord? Enable Discord Developer mode. Navigate to the server which contains the channel whose ID you want to copy. Right-click on the channel within the server's channel list, and the ID should be copied!

How do I retrieve old messages in discord PY?

You can use discord. TextChannel. last_message to get the last message of a channel.


2 Answers

They changed Client.servers to Client.guilds in newer version of discord.py (1.0).
You can also use bot instead of Client (info).
And guild.text_channels to get all text channels.
For all channels you can use bot.get_all_channels()

text_channel_list = []
for guild in bot.guilds:
    for channel in guild.text_channels:
        text_channel_list.append(channel)
like image 128
user4463876 Avatar answered Oct 20 '22 01:10

user4463876


Assuming you are using the async branch, the Client class contains guilds, which returns a list of guild classes that the bot is connected to. Documentation here: https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.guilds

Iterating over this list, each guild class contains channels, which returns a list of Channel classes that the server has. Documentation here: https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.channels

Finally, iterating over this list, you can check each Channel class for different properties. For example, if you want to check that the channel is text, you would use channel.type. Documentation here: https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel

A rough example of how you can make a list of all Channel objects with type 'Text':

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

To compare to 'text', channel.type must be a string.

For older versions of discord.py, commonly referred to as the async branch, use server instead of guild.

text_channel_list = []
for server in Client.servers:
    for channel in server.channels:
        if str(channel.type) == 'text':
            text_channel_list.append(channel)
like image 33
Benjin Avatar answered Oct 20 '22 01:10

Benjin