Puk3l_YT
Puk3l_YT

Reputation: 17

Why error - AttributeError: 'NoneType' object has no attribute

I just coding discord bot, and need help with adding roles to users.

I used script :

import discord #first script line

bot = discord.Client()


@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=" //help"))
guild_count = 0

for guild in bot.guilds:
    print(f"- {guild.id} (name: {guild.name})")

    guild_count = guild_count + 1
print("Verify bot is in " + str(guild_count) + " guilds.")

@bot.event
async def on_message(message):
if message.content == "//verify": #first command
    member = message.author
    wait_until_ready()
    var = discord.utils.get(message.guild.roles, name="verifyed")
    await member.add_roles(var)
    await message.author.send("You are verifyed on server! Thanks for using!")
    await message.author.send("Vote for our bot : **we are not in bot list already**")
    embed = discord.Embed(title='Verify',description='User verifyed! Use **//verify to verify your self!')
    await message.add_reaction('✅')
    embed.set_footer(text="Coded by Puk3l YT#2657")
    await message.channel.send(message.channel, embed=embed)

Then I just tested the code, and get error message :

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\mykem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
  File "C:\Users\mykem\Desktop\bot\online_bot.py", line 23, in on_message
    await member.add_roles(var)
  File "C:\Users\mykem\AppData\Local\Programs\Python\Python38-32\lib\site- packages\discord\member.py", line 676, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

What can I do? Can someone help me? Thank you for all answers

Upvotes: 0

Views: 2262

Answers (1)

Tin Nguyen
Tin Nguyen

Reputation: 5330

Code:

var = discord.utils.get(message.guild.roles, name="verifyed")
await member.add_roles(var)

Traceback:

    await member.add_roles(var)
  File "C:\Users\mykem\AppData\Local\Programs\Python\Python38-32\lib\site- packages\discord\member.py", line 676, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

The mistake is that it is trying to get a role but cannot find any. The var is None instead of being an object of type discord.Role. Thus your subsequent call await member.add_roles(var) fails. You need to add a condition that ensures var is valid.

E.g.

if var:
  await member.add_roles(var)
else:
  print("role could not be found")

Upvotes: 1

Related Questions