使用 discord.py 获取频道的名称

Pal*_*h35 6 python discord discord.py

如何获取频道的名称,以便该机器人可以在其放置的任何服务器上运行,而无需更改代码?(在我放置“我在这里放什么”的代码中,我希望名称在变量中)谢谢

from discord.ext.commands import Bot
import time, asyncio

TOKEN = 'Its a secret'
BOT_PREFIX = ["!"]
client = Bot(command_prefix=BOT_PREFIX)




@client.event
async def on_message(message):
    if message.author == client.user:
        return




@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await start()
    while True:
        currentTime = time.strftime("%M%S", time.gmtime(time.time()))
        if currentTime == "30:00":
            await start()
        await asyncio.sleep(1)


async def start():
    mainChannel = #What do i put here?
    print(mainChannel.name)
    await client.send_message(mainChannel, "Starting countdown", tts = True)



client.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)

Rul*_*rld 9

从 ID 获取频道(推荐)

首先,获取频道的ID(右键单击频道并选择“复制ID”)

其次,将ID放入以下代码:

client.get_channel("ID")
Run Code Online (Sandbox Code Playgroud)

例如:

client.get_channel("182583972662")
Run Code Online (Sandbox Code Playgroud)

注意: discord.py async 中的频道ID 是一个字符串,rewrite 中是一个整数

(感谢 Ari24 指出这一点)

从名称获取频道(不推荐)

首先,使用以下任一方法获取服务器:

server = client.get_server("ID")
Run Code Online (Sandbox Code Playgroud)

或者

for server in client.servers:
    if server.name == "Server name":
        break
Run Code Online (Sandbox Code Playgroud)

二、获取渠道:

for channel in server.channels:
    if channel.name == "Channel name":
        break
Run Code Online (Sandbox Code Playgroud)

什么不该做

尝试始终为每个服务器使用 ID,因为它更快、更高效。

尽量避免使用discord.utils.get,例如:

discord.utils.get(guild.text_channels, name="Channel name")
Run Code Online (Sandbox Code Playgroud)

尽管它确实有效,但这是不好的做法,因为它必须遍历整个频道列表。与使用 ID 相比,这可能会很慢并且花费更多的时间。

来自不和谐 API 文档:

discord.utils.get 是一个帮助器,它返回迭代中满足所有在 attrs 中传递的特征的第一个元素

  • 您还应该包括,仅在discord.py async 中,通道 ID 是一个字符串,而在 rewrite 中,它是一个整数 (2认同)

Ari*_*i24 8

现在重写有一个方法叫做discord.utils.get,您可以在其中实际获取具有特定参数的不和谐对象

在您使用频道名称的情况下:

import discord
channel = discord.utils.get(guild.text_channels, name="Name of channel")
Run Code Online (Sandbox Code Playgroud)

如果不和谐找不到具有该名称的文本频道,则应为无