How to get User object from id discord.py - python

I have a bot that sends dm pings to a user whos Id is given as a parameter in a command.
This is the command:.spam ID #_OF_PINGS
I run into the following error:
Ignoring exception in command spam:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 16, in spam
await ctx.send(f'Started pinging {user.name} {num} times.')
AttributeError: 'NoneType' object has no attribute 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'
Here is my code:
from discord.ext import commands
token = 'MyBotTokenHere'
prefix = '.'
client = commands.Bot(command_prefix=prefix)
client.remove_command("help")
#client.event
async def on_ready():
print('Ready')
#client.command()
async def spam(ctx, id1: int, num: int):
user = client.get_user(id1)
await ctx.send(f'Started pinging {user.name} {num} times.')
for i in range(num):
await user.send(f'<#{str(id1)}>')
await ctx.send(f'Finished {num} pings for {user.name}')
client.run(token)
It was working fine yesterday, but today, it broke down for some reason.
How do I fix it?
P.S. I hosted it on Heroku

You can use a converter for this:
#client.command()
async def spam(ctx, user: discord.User, num: int):
await ctx.send(f'Started pinging {user.name} {num} times.')
for i in range(num):
await user.send(f'<#{str(id1)}>')
await ctx.send(f'Finished {num} pings for {user.name}')
This way, Discord will automatically try to get the discord.User instance that corresponds to the id that you pass as an argument, and you can also #mention someone if you want to & it'll still work.
Also, starting from Discord 1.5.0, you now need to pass in intents when initializing a bot, which you clearly aren't doing yet. Update your Discord, and use the following to initialize your bot:
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=prefix, intents=intents)
More info on the how's and why's of intents in the relevant API documentation. You'll also want to enable members on your bot's Privileged Intents page, which is explained in the linked API docs as well.

Related

Add Role on Server

I intend, if you send the bot a certain DM that it then gives a role on a certain server.
This is my code what I tried:
#bot.event
async def on_message(message):
if message.author.bot:
return
elif message.content.startswith("++neunundvierzig++"):
role = message.author.guild.get_role(861543456908640298)
guild = bot.get_guild(816021180435529758)
await message.channel.send("Erfolgreich Zerifiziert!")
await member.add_roles(role)
It says in the log:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\aaa12\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "f:\HTML CSS JS Py Projekte\Python\bot_check\bot.py", line 36, in on_message
role = message.author.guild.get_role(861543456908640298)
AttributeError: 'User' object has no attribute 'guild'
I think you defined role wrong. Your code says that message.author.guild doesn't exist, so you should try message.guild.
Like this:
role = message.guild.get_role(861543456908640298)
Aside from that, you don't defined member. Just rename it to await message.author.add_roles(role) instead of await member.add_roles(role)
Sources
Discord Messages

discord.py: Sending invite through user DMs

So I wrote this command which I thought would send an invite to the member that was tagged but apparently I am missing something.
It returns this error:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Invite' object has no attribute 'ctx'
Thanks.
import discord
from discord.ext import commands
class Invite(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command(pass_context=True)
async def invite(self, ctx, member: discord.Member, *argument):
link = await ctx.channel.create_invite(max_uses=1, unique=True)
await member.send(link)
await ctx.send(f'{member.name} has received an invite.')
def setup(client):
client.add_cog(Invite(client))
I guess you have to request the invite in another way.
Try out the following:
#commands.command(pass_context=True)
async def invite(self, ctx, member: discord.Member, total: int = None):
guild = self.client.get_channel(ctx.channel.id)
link = await guild.create_invite(max_uses=1 if total is not None else total, unique=True)
await member.send(link)
await ctx.send(f'{member.name} has received an invite.')
What did we do?
Get the channel.id and define it as guild
Create an invite to guild with max. 1 use and the property of being unique
Send the link to the member and confirm it by bot

(discord.py) İ want to make a roll call bot for a discord server

I want to make a discord bot. Here is what i want: When i say '!yoklama 11.10.2020.txt'(or something) bot sends me a list of participants of which voice channel i am in.[not 1 channel(which i am in)] But i dont know how can i do.
Then i was some research and i find similar things about my request.
But they did not work properly.
Here is my found codes:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.command()
async def attendance(ctx, filename):
channel = client.get_channel(755129236397752441) # Replace with voice channel ID
with open(filename, 'w') as file:
for member in channel.members:
file.write(member.name + '\n')
client.run('mytoken')
This codes are working(when i run they dont give me error) but when i say !attendence test.txt bot
does not say anything and my python shell say to me:
Ignoring exception in command attendance:
Traceback (most recent call last):
File "C:\Users\Yunus Emre KISA\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(args, **kwargs)
File "C:\bot2\bot2.py", line 10, in attendance
for member in channel.members:
AttributeError: 'NoneType' object has no attribute 'members'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Yunus Emre KISA\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Yunus Emre KISA\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\discord\ext\commands\core.py", line 859, in invoke
await injected(ctx.args, **ctx.kwargs)
File "C:\Users\Yunus Emre KISA\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError:
'NoneType' object has no attribute 'members
You see guys i dont understand anything please help me.
I found these question but it does not work for me:
Discord Python bot creating a file of active member in a vocal channel
#client.command()
async def test(ctx):
guild = ctx.guild
channel = discord.utils.get(guild.voice_channels, name='General')
for member in channel.members:
print('test')
What I would do instead of having to pass in the file in the command, is just in the function writing:
with open("file.txt", "w") as f:

'int' object has no attribute 'id'

I’ve been tormented by this error for a week, I seriously don’t understand what’s the matter, help plz
'int' object has no attribute 'id'
there is my code:
import discord
import random
import asyncio
from discord import Member
from discord.utils import get
from discord.ext import commands
from discord.ext.commands import Bot
from discord.ext.commands import check
from discord.ext.commands import has_role
ROLE = 730459135170183170
bot = commands.Bot(command_prefix='$')
#bot.command(pass_context = True)
#commands.has_role(730459135170183170)
async def use_shovel(ctx,user: discord.Member):
x = random.randint(1,50)
role = get(user.guild.roles, name =ROLE)
if x == 1:
await ctx.send("You've found REQUIEM ARROW!")
await bot.author.add_roles(731166197030322216)
else:
await ctx.send("meh, nothing")
await user.remove_roles(731166197030322216)
bot.run(TOKEN)
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "use_shove" is not found
Ignoring exception in command use_shovel:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "meh.py", line 24, in use_shovel
await user.remove_roles(731166197030322216)
File "C:\Python\lib\site-packages\discord\member.py", line 685, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
I really cannot understand why this error happen. So,how can I fix this?I
There are multiple errors in your code :
First, you're looking for a role with 730459135170183170 as a name, so your role variable's value will be None.
ROLE = 730459135170183170
(...)
role = get(user.guild.roles, name =ROLE)
Then, both add_roles and remove_roles take a role object as argument, not an int.
await bot.author.add_roles(731166197030322216)
(...)
await user.remove_roles(731166197030322216)
Finally, never ever share your token on any website:
bot.run('TOKEN')
You should go to your discord bot app and create a new token, so you're the only one who can use your bot app.
To solve your problem, you can get rid of your ROLE variable and replaces these lines:
#commands.has_role("Exact role name")
(...)
role = get(user.guild.roles, name="Exact role name")
(...)
await bot.author.add_roles(role)
(...)
await user.remove_roles(role)

Discord.py Bot that doesn't act like it has permissions

So I am working on a Discord Bot and trying to work on role assignments. I made sure that I am using the new rewrite system, I made sure I gave the bot administrative privileges. I have taken just about every measure I could think of and it simply is not working. I looked at the updated API to handle it, used sample code as a framework, This is the code
import os
import discord
from discord.utils import get as dget
from discord.ext.commands import Bot
from dotenv import load_dotenv
load_dotenv('key.env')
TOKEN = os.getenv('DISCORD_TOKEN')
client = Bot(command_prefix = '!')
#client.event
async def on_ready():
print('Connected')
#client.command()
async def role(ctx):
user = ctx.message.author
role = discord.utils.get(ctx.guild.roles, name="Sample")
await user.add_roles(role)
client.run(TOKEN)
and this is the error that i get:
Ignoring exception in command role:
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "d:/Google Drive/Coding/Khasbot/main.py", line 22, in role
await user.add_roles(role)
File "C:\Users\chris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\chris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 221, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\chris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\chris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
I honestly have no idea what could be going wrong. I have tried endless things and even created a whole new bot altogether. Still the same issue. It worked last night and literally just won't do it.
Make sure that your bot must have Manage Roles permission on your server and the role for adding roles must be lower than your bot top role.
Make you did these 2 things.

Categories

Resources