Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.py on_member_join and on_member_leave not working

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 it 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

like image 308
musava_ribica Avatar asked May 31 '20 22:05

musava_ribica


2 Answers

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')
like image 132
Eric Jin Avatar answered Nov 19 '22 00:11

Eric Jin


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.

like image 21
Peble Jackson Avatar answered Nov 19 '22 00:11

Peble Jackson