How to give role to user for reaction - python

If user add reaction :HotS_Tank: in a special message, the bot will need to give this role to user, but I do not have any idea how to do it...
That's what I have tried:
async def role_background_task():
await client.wait_until_ready()
roleChannel = discord.Object(id='411270826374070293')
roleMSG1 = client.get_message(roleChannel, id='411657109860515840')
roleMSG2 = client.get_message(roleChannel, id='411657144488689674')
while not client.is_closed:
reac1 = await client.wait_for_reaction(emoji=':HotS_Tank:411445724287598592',message=roleMSG1)
if reac1.reaction.emoji == ':HotS_Tank:411445724287598592':
await client.add_roles(reac1.user, roleHOTS_Tank)
client.loop.create_task(role_background_task())

If you check the documentation, there's an event called on_reaction_add here. You can simply use that.
#client.event
async def on_reaction_add(reaction, user):
roleChannelId = '411270826374070293'
if reaction.message.channel.id != roleChannelId:
return #So it only happens in the specified channel
if str(reaction.emoji) == "<:HotS_Tank:411445724287598592>":
await client.add_roles(user, roleHOTS_Tank)

Related

MissingRequiredArgument: context is a required argument that is missing

Im Still New (Because I Took A Break And Forgot Almost Everything). I Was Coding An AFK Bot And This Happened...
Error: MissingRequiredArgument: context is a required argument that is missing.
Code:
#client.command()
async def start(ctx,context,user: discord.Member):
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
name = context.author.display_name
author = context.author
guild = context.guild
AFKrole = discord.utils.get(guild.roles, name="AFK")
if not AFKrole:
AFKrole = await guild.create_role(name="AFK")
await context.author.edit(nick=f"[AFK]{name}")
await author.add_roles(AFKrole)
await ctx.send(f"AFK Mode Started For **{author}**.")
gt = await client.wait_for('message', check=check, timeout=180)
if gt.content.lower() == "afk stop":
await context.author.edit(nick=f"{name}")
await author.remove_roles(AFKrole)
await ctx.send(f"AFK Mode Stopped For **{author}**.")
else:
pass
please help.
Remove context parameter and replace any context part in the code with just ctx. ctx is already context.
Ex.
name = ctx.author.display_name
author = ctx.author
guild = ctx.guild

role react bot discord python

I'm trying to create a react role on a message that my bot would have sent, how can I do it?
here is my code debut:
#bot.command(name = 'role_react_1')
async def role_react_1(ctx):
del = await ctx.channel.history(limit=1).flatten()
for each_messages in del:
await each_messages.delete()
message = await ctx.send("for have the role : evil : :smiling_imp: \nwhat role you want ?")
await message.add_reaction("????")
def checkEmoji(reaction):
return message.id == reaction.message.id and str(reaction.emoji) == ":evil:"
reaction = await bot.wait_for("reaction_add", check=checkEmoji)
if reaction.emoji == ":evil:":
role = discord.utils.get(ctx.guild.roles, name="evil")
await ctx.author.add_roles(role)
await ctx.send(f"the role {role} was assigned")
I've been told about 'on_raw_reaction_add' but I don't know how to use it. how to do it
if someone want a answer, it need a bot.event with reaction_add

Cogs Help In Discord Py

I am trying to create a command wherein if you react on the embed, the bot sends something back. If I add this code to a cog, it won't work. If possible, can you tell me why?
#bot.command(aliases=['test','t'])
async def Test(self, ctx):
TestEmbed = discord.Embed(title="Definition", description="This is just a test embed", color=11027200)
TestEmbed.add_field(name="\u200b", value="▹❁❁▹❁◃❁❁◃",inline=False)
emojis = ['⬅️','➡️']
TestEmbedAdd = await ctx.send(embed=TestEmbed)
for emoji in emojis:
await TestEmbedAdd.add_reaction(emoji)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await bot.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '➡️':
await ctx.send("Reaction 2!")
elif reaction.emoji == '⬅️':
await ctx.send("Reaction 1!")
except asyncio.TimeoutError:
await ctx.send("Time is out!")
With the help of the people in the comment section, I have found the problem with my code. I had to change bot.command into commands.command. (I've tried both bot and command, and it still works splendidly). The other crucial thing I had to add was "self" under bot.wait_for. Without the self, the command wouldn't work. Thank you so much for the help.
#commands.command(aliases=['test','t'])
async def Testing(self, ctx):
TestEmbed = discord.Embed(title="Definition", description="This is just a test embed", color=11027200)
TestEmbed.add_field(name="\u200b", value="▹❁❁▹❁◃❁❁◃",inline=False)
emojis = ['⬅️','➡️']
TestEmbedAdd = await ctx.send(embed=TestEmbed)
for emoji in emojis:
await TestEmbedAdd.add_reaction(emoji)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '➡️':
await ctx.send("Reaction 2!")
elif reaction.emoji == '⬅️':
await ctx.send("Reaction 1!")
except asyncio.TimeoutError:
await ctx.send("Time is out!")
you need #commands.command instead of #bot.command

My bot doesn't give role, but it doesn't send error

(Sorry for my english)My bot must give role by reaction on emoji, but it doesn't do it. But it doesn't send error-message. Please help.
My code:
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix = ".",intents = discord.Intents.all())
#client.event
async def on_ready():
print(discord.__version__)
Channel = client.get_channel(815949348948934716)
Text= "Выбери свою роль😇"
Moji = await Channel.send(Text)
await Moji.add_reaction('🏃')
#client.event
async def on_reaction_add(reaction, user):
Channel = client.get_channel(815949348948934716)
if reaction.message.channel.id != Channel:
return
if reaction.emoji == "🏃":
Role = discord.utils.get(user.server.roles, name="PUBG")
await user.add_roles(Role)
client.run("My token")
You must use an event called on_raw_reaction_add. You might want to read the Docs.
Now to the further procedure:
Define the event:
#client.event
async def on_raw_reaction_add(payload): # We use payload
Define the role(s):
guild = client.get_guild(payload.guild_id) # Define the guild
member = get(guild.members, id=payload.user_id) # Get the member from the guild
# channel and message IDs should be integer:
if payload.channel_id == Channel_ID and payload.message_id == Message_ID: # Inser your ID's
if str(payload.emoji) == "YourEmoji":
role = get(payload.member.guild.roles, name='RoleName') # ID also possible.
Add the role:
if role is not None:
await payload.member.add_roles(role)
So your entire code would be:
#client.event
async def on_raw_reaction_add(self, payload):
guild = client.get_guild(payload.guild_id)
member = get(guild.members, id=payload.user_id)
if payload.channel_id == Channel_ID and payload.message_id == Message_ID:
if str(payload.emoji) == "YourEmoji":
role = get(payload.member.guild.roles, name='RoleName') # Or id='RoleID'
else:
role = get(guild.roles, name=payload.emoji)
if role is not None:
await payload.member.add_roles(role) # Add the role
To add more roles just use elif statements.
What are we doing?
Send a message into the defined channel (Channel_ID)
Add a role when someone reacts with the defined emoji to the message

Discord py - if emoji in new created channel - delete the channel

Hey guys!
I am trying to make a litte ticket-bot for my server - the problem is that the emoji in the reaction deletes a channel!
So if a member uses the emoji outside the new created channel it will delete the channel :(
What does my code look like now:
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
guild_id = payload.guild_id
guild = self.client.get_guild(guild_id)
user_id = payload.user_id
user = self.client.get_user(payload.user_id)
message_id = payload.message_id
emoji = payload.emoji.name
if message_id == 768765161301213185 and emoji == "📩":
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
support_role = guild.get_role(760792953718308915)
category = guild.get_channel(768764177736400906)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True, send_messages=True),
support_role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
ticket_nr = random.randint(100,999)
channel = await category.create_text_channel(f'ticket-{ticket_nr}', overwrites=overwrites)
embed = discord.Embed(
title="How can I help you?",
description="Please wait for a supporter.")
embed.set_author(name="TiLiKas Ticket Bot")
for channel_all in guild.text_channels:
if str(channel_all) == str(channel):
if user_id != 739740219544305714 and emoji == "🔒":
await channel.delete(reason=None)
else:
print("ERROR")
What do I want?
I want the bot only to responde on the emoji if its used in the new created channel!
https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=check#discord.ext.commands.Bot.wait_for
#client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that 👍 reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('👎')
else:
await channel.send('👍')
Your check method should look something like:
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍' and reaction.message.channel == message.channel
This check here, checks:
the user who is reacting to the message is the same user who started the command.
the reaction is a thumbs up emoji.
the reaction is done in the same channel the command was started in.

Categories

Resources