I’m having trouble with my Discord bot. It’s supposed to automatically give a role to new users when they join the server, but it’s not working as expected.
The bot doesn’t show any errors, and it fails to assign the role. Here’s what my code looks like:
@bot.event
async def on_member_join(new_member):
bot_permissions = discord.Intents.default()
bot_permissions.members = True
bot = commands.Bot(command_prefix='!', intents=bot_permissions)
newcomer_role = discord.utils.get(new_member.guild.roles, name='Newcomer')
await new_member.add_roles(newcomer_role)
Can anyone point out what might be going wrong? I’m new to Discord bot development and could be missing something obvious. Any assistance would be greatly appreciated!
I’ve faced a similar issue before, and I think I see what’s going wrong here. The problem is likely with how you’re setting up the bot and intents.
You’re creating a new Bot instance inside the on_member_join event, which isn’t correct. The bot should be initialized once when your script starts, not every time a member joins.
Try moving the bot setup code outside of the event handler. Also, make sure you’ve enabled the proper intents when you first create the bot. Here’s a rough outline of how your code structure should look:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_member_join(new_member):
newcomer_role = discord.utils.get(new_member.guild.roles, name='Newcomer')
await new_member.add_roles(newcomer_role)
bot.run('YOUR_TOKEN_HERE')
This should resolve your issue. Remember to enable the ‘Server Members Intent’ in your Discord Developer Portal as well. Hope this helps!
hey there! looks like ur having some trouble with ur discord bot. the others already pointed out the main issue, but i wanted to add that u should also check if the ‘Newcomer’ role actually exists on ur server. sometimes we forget to create the role and wonder why it’s not being assigned
good luck with ur bot!
The issue you’re encountering is likely due to incorrect bot initialization. Your current setup creates a new bot instance every time a member joins, which isn’t the right approach. Instead, you should initialize the bot once at the start of your script.
Here’s a suggested modification:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_member_join(new_member):
newcomer_role = discord.utils.get(new_member.guild.roles, name='Newcomer')
await new_member.add_roles(newcomer_role)
bot.run('YOUR_BOT_TOKEN')
Also, ensure you’ve enabled the ‘Server Members Intent’ in the Discord Developer Portal. This should resolve your automatic role assignment issue.