Skip to content
Advertisement

Discord.py editing channel by word that is in the name

I am making statistics bot, and i have a problem, with voice channel containing member count. I want to make bot update name of that channel, on_member_join, on_member_remove and when user use command refresh but i tried many times at different ways, and it stil don’t work, i want to make him edit channel that contains in name “Members:” but i can get channel at most with constant name. Is there any way to get channel by containing “Members:”?

Okay, i tried Łukasz’s code, but it still don’t changes the channel name. My code:

@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:')

And my channel screenshots (maybe it will be important):
enter image description here

enter image description here

Can you please tell me why it’s not working?

Advertisement

Answer

You should use the in keyword, e.g

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

To get all channels that contain the word 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)

If you want a one-liner:

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

Then you can loop through every channel and edit it:

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

Note: There’s a heavy ratelimit for editing channels (2 requests per 10 minutes per channel iirc) you should use this wisely

Reference:

Advertisement