python - 添加到其他人服务器的 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 列表?
解决方案
假设您的 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
任何类型的,例如更改字体或没有开始的频道。
推荐阅读
- angular - Angular JS-一字段接受两种不同类型的数据(坐标字符串或地址字符串)
- vba - 循环遍历范围 - 联合
- python - Connecting to Neo4j database after importing CSV
- mysql - 连接多个sql表以找到共同值
- c++ - 将文本文件中的成绩读入数组 C++
- excel - Excel 将多个单元格组合成一个数组作为公式中的变量输入
- r - 带有 sf 地图和替代 crs 的背景图像
- command-line - 批量缩小 GB 大小的 TIF 图像
- arrays - 反应状态数组不更新
- statistics - MDX 逆正态分布