首页 > 解决方案 > Discord.py 按名称中的单词编辑频道

问题描述

我正在制作统计机器人,但我遇到了一个问题,语音频道包含会员数。我想让机器人更新该频道的名称,on_member_joinon_member_remove用户使用命令refresh但我以不同的方式尝试了很多次时,它仍然不起作用,我想让他编辑名称中包含“成员:”的频道但是我最多可以get使用常量名称进行通道。有没有办法get通过包含“成员:”来引导?

好的,我尝试了 Łukasz 的代码,但它仍然没有更改频道名称。我的代码:

@bot.event
async def on_member_join(member):
    await asyncio.sleep(random.randint(600, 1200))
    guild = member.guild
    channels = [c for c in guild.channels if "Members:" in c.name.lower()]
    for channel in channels:
        await channel.edit(f"Members: {member.guild.member_count}")

@bot.event
async def on_member_remove(member):
    await asyncio.sleep(random.randint(600, 1200))
    guild = member.guild
    channels = [c for c in guild.channels if "Members:" in c.name.lower()]
    for channel in channels:
        await channel.edit(name=f"Members: {member.guild.member_count}")

@bot.command()
async def refresh(ctx):
    await ctx.send('Starting refreshing members count voice channel.')
    guild = ctx.guild
    channels = [c for c in guild.channels if "Members:" in c.name.lower()]
    for channel in channels:
        await channel.edit(f"Members: {ctx.guild.member_count}")
        await ctx.send(':thumbsup:')

还有我的频道截图(也许这很重要):
在此处输入图像描述

在此处输入图像描述

你能告诉我为什么它不起作用吗?

标签: pythondiscorddiscord.py

解决方案


您应该使用in关键字,例如

>>> "members:" in "whatever members: something"
True

获取包含该单词的所有频道members:

guild = # Any `discord.Guild` instance
channels = []

for c in guild.channels: # You can also use the `Guild.text_channels` or `Guild.voice_channels` attributes
    if if "members:" in c.name.lower():
        channels.append(c)

如果你想要一个单行:

guild = # Any `discord.Guild` instance
channels = [c for c in guild.channels if "members:" in c.name.lower()]

然后你可以遍历每个通道并对其进行编辑:

for channel in channels:
    await channel.edit(**kwargs)

注意:编辑频道有很高的速率限制(每个频道 iirc 每 10 分钟 2 个请求)你应该明智地使用它

参考:


推荐阅读