首页 > 解决方案 > 添加到其他人服务器的 Discord Bot 如何获取他们希望它发送消息的通道 ID?

问题描述

我目前有一个在我自己的私人服务器上运行良好的不和谐机器人。我希望机器人能够加入其他人的服务器,如果他们选择添加它们,但我的机器人的一部分是它会每隔一段时间自动向特定频道发送消息。为此,我使用了我在服务器上使用的频道的频道 ID:

async def esportsdiscussions():
    await client.wait_until_ready()
    channel = client.get_channel([Channel Id])
    await channel.send('Hi!')

如果我的机器人被添加到另一台服务器,我的服务器的频道 ID 显然无法正常工作,那么有没有办法从它所在的服务器自动获取通用频道 ID?还是有另一种方法可以为不同的服务器创建频道 ID 列表?

标签: pythondiscord.py

解决方案


假设您的 bot 加入的每台服务器都将拥有#general,最简单的方法是使用discord.utils'get 函数。它将遍历公会的频道,如果#general找到一个频道,则返回一个频道对象。

channel = discord.utils.get(ctx.guild.channels, name="general")

像这样的其他问题:


有时,服务器可能会将其一般标记为#╚general#general等,这将能够绕过上述代码。在这种情况下,您可以使用这种稍长的方法。

for channel in ctx.guild.channels: # for every channel in this guild,
    if "general" in channel.name.lower() # if the word 'general' is in this channel's name (lowercase)
        channel = channel # the channel variable is now this channel
        break # stop the loop

总体而言,唯一的主要问题是公会是否没有#general任何类型的,例如更改字体或没有开始的频道。


推荐阅读