簡體   English   中英

使用 discord.py 獲取頻道名稱

[英]get the name of a channel using 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)

從 ID 獲取頻道(推薦)

首先,獲取頻道的ID(右鍵單擊頻道並選擇“復制ID”)

其次,將ID放入以下代碼:

client.get_channel("ID")

例如:

client.get_channel("182583972662")

注意: discord.py async 中的頻道ID 是一個字符串,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 中傳遞的特征的第一個元素

現在重寫有一個名為discord.utils.get的方法,您可以在其中實際獲取具有特定參數的不和諧對象

在您使用頻道名稱的情況下:

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

如果不和諧找不到具有該名稱的文本頻道,則應為無

其實很簡單:你可以簡單地做message.channel.name

例子:

print(message.channel.name)

print(message.channel.name) 僅在您收到消息時才有效,但我想發送一個而不需要先接收一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM