get the name of a channel using discord.py

前端 未结 2 921
醉话见心
醉话见心 2021-01-13 07:00

how do I get the name of a channel so that this bot will work on any server its put on with no changes to code necessary? ( in the code where I put \"what do I put here\" is

相关标签:
2条回答
  • 2021-01-13 07:18

    Now in rewrite there's a method called discord.utils.get where you can actually getting discord objects with specific parameters

    In your case with a channel name:

    import discord
    channel = discord.utils.get(guild.text_channels, name="Name of channel")
    

    Should be None if discord couldn't find a textchannel with that name

    0 讨论(0)
  • 2021-01-13 07:33

    Getting channel from ID (Recommended)

    First, get the ID of the channel (Right click the channel and select "Copy ID")

    Second, put the ID in the following code:

    client.get_channel("ID")
    

    For example:

    client.get_channel("182583972662")
    

    Note: The channel ID is a string in discord.py async, and an integer in rewrite

    (Thanks to Ari24 for pointing this out)

    Getting channel from name (Not reccomended)

    First, get the server using either:

    server = client.get_server("ID")
    

    OR

    for server in client.servers:
        if server.name == "Server name":
            break
    

    Second, get the channel:

    for channel in server.channels:
        if channel.name == "Channel name":
            break
    

    What not to do

    Try to always use the ID for each server, as it is much faster and more efficient.

    Try to avoid using discord.utils.get, such as:

    discord.utils.get(guild.text_channels, name="Channel name")
    

    Although it does work, it is bad practise as it has to iterate through the entire list of channels. This can be slow and take much more time than using the ID.

    From the discord API docs:

    discord.utils.get is a helper that returns the first element in the iterable that meets all the traits passed in attrs

    0 讨论(0)
提交回复
热议问题