首页 > 解决方案 > 使用 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)

标签: pythondiscorddiscord.py

解决方案


从 ID 获取频道(推荐)

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

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

client.get_channel("ID")

例如:

client.get_channel("182583972662")

注意:频道 ID 在 discord.py async 中为字符串,在 rewrite 中为整数

(感谢 Ari24 指出这一点)

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

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

server = client.get_server("ID")

或者

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

二、获取渠道:

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

什么不能做

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

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

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

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

来自不和谐 API 文档:

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


推荐阅读