Add Role on Server - python

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

Related

Discord.PY, reaction role error occuring?

Alright I am trying to create a command where the user does (prefix)requestrole discordid roleid. It then sends a request embed to a channel where certain roles can view that channel and they can click on either the checkmark reaction or the 'x' reaction to accept or deny the role request.
#commands.command()
async def requestrole(self, ctx, discordid, roleid):
discordid = int(discordid)
roleid = int(roleid)
userid = ctx.author.id
channel = self.bot.get_channel(FILLWITHCHANNELID)
guild = ctx.guild
user = ctx.author
role = get(guild.roles, id=roleid)
embed = discord.Embed(title="Role Request", description=f"{user} requested {role} for {userid}", color=0x00ff00)
await channel.send(embed=embed)
message = await embed.send(embed=embed)
await message.add_reaction("✅")
await message.add_reaction("❌")
#self.bot.event
async def on_reaction_add(reaction, user):
if reaction.emoji == "✅":
user = reaction.message.author
guild = reaction.message.guild
role = get(guild.roles, id=roleid)
await user.add_roles(role)
await channel.send(f"{user} has been given {role}")
elif reaction.emoji == "❌":
await reaction.message.send("Role request denied")
This is the error I am now receiving
Ignoring exception in command requestrole:
Traceback (most recent call last):
File "C:\Users\name\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\name\Documents\GitHub\PRP-Bot\cogs\role_cog.py", line 31, in requestrole
message = await embed.send(embed=embed)
AttributeError: 'Embed' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\name\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\name\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\name\AppData\Roaming\Python\Python310\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: 'Embed' object has no attribute 'send'
My question particularly is what is causing the error, and how do I properly code it so a person can basically click on the reaction checkmark to add the role, or click the x to remove the role.
you are trying to send a message to an Embed. That's not how Embeds work. you can send a message to a channel but not to a Embed. Just remove the line message = await embed.send(embed=embed) and you should be fine

Python 3.9.x - Attribute error using discord.py library

Creating a simple admissions system - want it to give a role when the person runs a command
Full error feed
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 18, in on_message
await client.add_roles(message.author, role)
AttributeError: 'Client' object has no attribute 'add_roles'
Full code
import discord
from discord.utils import get
import os
client = discord.Client()
#client.event
async def on_ready():
print('we are logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'give me admin':
role = get(message.guild.roles, name='Hoplite')
await client.add_roles(message.author, role)
client.run(os.getenv('Token'))
There isn't anything like client.add_roles you have to user member.add_roles instead.
await message.author.add_roles(role)
Remember that the bot has to have permissions and the role you want to give has to be lower than the highest role the bot has!

How to get User object from id discord.py

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.

discord.py Fetching messages by content

I'm trying to build a discord bot for reaction roles. To do this, I'm trying to use the on_reaction_add combined with fetch_message to check if the reaction added was to the message that the bot sent but I keep getting various error with fetch_message. Here is the code:
#bot.command()
async def createteams(ctx):
msg = await ctx.send("React to get into your teams")
await msg.add_reaction("1️⃣")
await msg.add_reaction("2️⃣")
await msg.add_reaction("3️⃣")
await msg.add_reaction("4️⃣")
await msg.add_reaction("5️⃣")
await msg.add_reaction("6️⃣")
await msg.add_reaction("7️⃣")
await msg.add_reaction("8️⃣")
#bot.event
async def on_reaction_add(reaction, user):
id = reaction.message.id
if await reaction.message.author.fetch_message(reaction.message.id) == "React to get into your teams":
print("Success")
This gives me the error
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "hypixel.py", line 60, in on_reaction_add
fetch = await reaction.message.author.fetch_message(id)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/abc.py", line 955, in fetch_message
channel = await self._get_channel()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/member.py", line 243, in _get_channel
ch = await self.create_dm()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/member.py", line 109, in general
return getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'
But when I go and copy the ID of the message I reacted to, its the same as the printed variable id but it still says Message Not Found
Thanks
I figured out the issue, you can't use fetch_message with user it needs to be channel so I changed my code to
await reaction.message.channel.fetch_message(id)
and it worked :)

on_raw_reaction_add(payload) troubleshooting

Hey i am developing a Discord Bot with Python.
Here is the documentation: https://discordpy.readthedocs.io/en/latest/index.html
This program should give a user a role if he or she reacts to a message
I tried to define the ctx in the function itself
#client.event
async def on_raw_reaction_add(payload):
member = discord.utils.get(client.get_all_members())
role = discord.utils.find(lambda r: r.name == "check-in", ctx.guild.roles)
check_in = ["612637944544624690"]
if str(payload.channel_id) in check_in:
await client.add_roles(member, role, reason="check-in")
That is the error without ctx in the function itself:
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\kaitr\Anaconda3\envs\tutorial\lib\site-packages\discord\client.py", line 270, in _run_event
await coro(*args, **kwargs)
File "C:/Users/kaitr/PycharmProjects/Discord Tutorial/bot.py", line 39, in on_raw_reaction_add
role = discord.utils.find(lambda r: r.name == "check-in", ctx.guild.roles)
NameError: name 'ctx' is not defined
That is the error with ctx in the function itself:
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\kaitr\Anaconda3\envs\tutorial\lib\site-packages\discord\client.py", line 270, in _run_event
await coro(*args, **kwargs)
TypeError: on_raw_reaction_add() missing 1 required positional argument: 'ctx'
You don't have access to an invocation context because this isn't a command. You can only use the attributes of the payload, a RawReactionActionEvent object. This includes a guild_id attribute that you can use to get the guild:
#client.event
async def on_raw_reaction_add(payload):
if payload.guild_id is None:
return # Reaction is on a private message
guild = client.get_guild(payload.guild_id)
role = discord.utils.get(guild.roles, name="check-in")
member = guild.get_member(payload.user_id)
if str(payload.channel_id) in check_in:
await member.add_roles(role, reason="check-in")

Categories

Resources