7
votes

I started using discord.py (not discord.ext commands, only import discord) recently, I made a channel, the name of which shows the member count in the guild, and updates everytime someone joins or leaves. This is my code:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready")

@client.event
async def on_member_join(member):
    channel = client.get_channel('channel id here')
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count()))

@client.event
async def on_member_leave(member):
    channel = client.get_channel('channel id here')
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count()))

client.run('my token here')

I also added "client.on_message" command so the bot would edit that name to whatever I typed in.

@client.event
async def on_message(message)
     if message.content == 'rename channel':
            channel = client.get_channel('channel id here')
            await channel.edit(name = 'TEST')

Now, after adding some print's for debugging, I found out that on_member_join and on_member_leave never get called, but the bot edits the channel's name when I type the command. That's a voice channel, which shows member count. There aren't any errors. Did I read the API wrong? Please help

3

3 Answers

5
votes

IDs of any kind in discord should be passed as an integer, not a string. Additionally, discord.Guild.member_count is an attribute, not a method, so use it without the parentheses. You should also be using on_member_remove() instead of on_member_leave().

import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready")

@client.event
async def on_member_join(member):
    channel = client.get_channel(ID)
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count))

@client.event
async def on_member_remove(member):
    channel = client.get_channel(ID)
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count))

client.run('my token here')
0
votes

I am not entirely sure, but the reason behind your on_member_join and on_member_leave not working maybe because of intents not being passed.

import discord
intents = discord.Intents.all()

client = discord.Client(intents = intents)

and then you want to enable server intents in the bot application. I faced this issue when I made my bot as well

0
votes

You need to set up intents in the discord developer portal then the code would be like such

import discord
from discord.ext import commands
intents = discord.Intents.all()

bot = commands.Bot(command_prefix=".", intents=intents)

etc