Discord.py find who reacted to a message - python

I'm coding a discord bot and creating a game. I need to get the user that reacted to the message with the specific emoji to add in a list. How can i do that?
(my code below)
#client.command(aliases=['rr'])
async def roletarussa(ctx):
embed = discord.Embed(title="ROLETA RUSSA", description="Reaja com ✅ para participar!")
embed.set_thumbnail(
url="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRa7rdwxpSOiReyDvnVd6MzqDg33rtQrxhoUw&usqp=CAU")
embed.add_field(name="Só os brabo consegue entrar nesse web desafio 🔫🤠",
value="Vai logo entra nesse bagaça medroso!", inline=False)
embed.set_image(url='https://media1.tenor.com/images/64e0334d77b0976b808147bd160b8534/tenor.gif?itemid=12379724')
message = await ctx.send(embed=embed)
await message.add_reaction("✅")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ['✅']
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "✅":
await ctx.send('{} vai participar'.format(user))
await message.remove_reaction(reaction, user)
else:
await message.remove_reaction(reaction, user)
except asyncio.TimeoutError:
await message.delete()
break
# ending the loop if user doesn't react after x seconds
#client.command()
async def startrr(ctx):
players = []
maxlenght = 6
while len(players) < maxlenght:
rrp = ctx.message.author.mention
players.append(rrp)
players = list(set(players))
else:
await ctx.send('Sem mais vagas para o jogo.')
await ctx.send(players)
I need to get who reacted to the msg and store in 'players' list.

Related

How to add role by reacting in DM to a bot message

Im trying to make a bot that send me a message with a reaction button, when I click it, give me a role in the server. Im trying to use on_raw_reaction_add event but I cant reach a solution to make it, Im always getting errors at getting guild roles and this stuff.
In this case, guild is none, I dont know what Im doing wrong.
My code:
#client.command()
async def test(ctx):
global member
global message__id
global channel_id
channel_id = (ctx.channel.id)
member = ctx.message.author
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
mesg = await member.send(embed=embed)
await mesg.add_reaction("✅")
message__id = mesg.id
print("EXECUTED")
#client.event
async def on_raw_reaction_add(payload):
print("reacted")
print("messageid accepted")
guild = client.get_guild(payload.guild_id)
if guild is not None:
print("messageid accepted")
reactor = payload.guild.get_member(payload.member.id)
role = discord.utils.get(guild.roles, name="Member")
if payload.emoji.name == '✅':
print("emoji accepted")
await reactor.add_roles(role)
EDIT:
I changed my on_raw_reaction_add event:
#client.event
async def on_raw_reaction_add(payload):
print("reacted")
print("messageid accepted")
guild = client.get_guild(payload.guild_id)
if guild is not None:
print("guild not none ")
reactor = payload.guild.get_member(payload.member.id)
role = discord.utils.get(guild.roles, name="Verified")
if payload.emoji.name == '✅':
print("emoji accepted")
await reactor.add_roles(role)
else:
print("guild none")
And this is what happen when I try the method:
First three words are the prints of the bot reacting his own message, the "EXECUTED" is the print of test method and the last three messages. are when I react the bot message
In this case, I suggest using a wait_for rather than on_raw_reaction_add.
Example, as seen in the docs:
#client.command(aliases=["t"])
async def test(ctx):
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
# sends message to command author
mesg = await ctx.author.send(embed=embed)
await mesg.add_reaction("✅")
#check if the reactor is the user and if that reaction is the check mark
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '✅'
try:
#wait for the user to react according to the checks
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
# 60 seconds without reaction
await ctx.send('Timed out')
else:
await ctx.send('✅')
docs- https://discordpy.readthedocs.io/en/stable/api.html?highlight=wait_for#discord.Client.wait_for
async def test(ctx):
global member
global message__id
global channel_id
channel_id = (ctx.channel.id)
member = ctx.message.author
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
mesg = await member.send(embed=embed)
await mesg.add_reaction("✅")
message__id = mesg.id
print("EXECUTED")
role = get(ctx.guild.roles, id=role id here)
done = False
while done == False:
reaction, user = await client.wait_for(“reaction_add”, check=check)
if user == client.user:
continue
await member.add_roles(role)
done = True
I am pretty sure something like this would work :D
When you do guild is not None, it will never fire because you are reacting in a DM channel context - where the guild is None. To access the guild information from the DM, you'll need to save it somewhere in the message (or save it yourself internally). Then, you have the guild object and you're able to add roles or do things to it.
#client.command()
async def testrole(ctx):
member = ctx.author
# ...
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
mesg = await member.send(str(ctx.guild.id), embed=embed) # we need the guild information somewhere
await mesg.add_reaction("✅")
#client.event
async def on_reaction_add(reaction, user): # there's really no need to use raw event here
if user.id == client.user.id:
return
if reaction.message.guild is None:
if reaction.emoji == '\u2705':
# we have to get the guild that we saved in the other function
# there is no other way to know the guild, since we're reacting in the DM
# that's why it was saved inside of the message that was sent to the user
guild_id = int(reaction.message.content)
guild = client.get_guild(guild_id)
member = guild.get_member(user.id)
await member.add_roles(...) # change this with your roles

Discord.py on_message event isn't processing any commands - Modmail Event

I'm creating a mod-mail feature which members can message the bot and it will respond with instructions. However the event works fine with the exception of bot commands. Here is my code. Strangely no errors were detected.
sent_users = []
modmail_channel = client.get_channel(910023874727542794)
#client.event
async def on_message(message):
if message.guild:
return
if message.author == client.user:
return
if message.author.id in sent_users:
return
embed = discord.Embed(color = color)
embed.set_author(name=f"Misaland Modmail System", icon_url=f'{message.author.avatar_url}')
embed.add_field(name='Report a Member: ', value=f"React with <:Wojak1:917122152078147615> if you would like to report a member.")
embed.add_field(name='Report a Staff Member:', value=f"React with <:grim1:925758467099222066> if you would like to report a staff.")
embed.add_field(name='Warn Appeal:', value=f"React with <:Lovecat:919055184125100102> if you would like to appeal a warning.")
embed.add_field(name='Question:', value=f"React with <:gasm:917112456776679575> if you have a question about the server")
embed.add_field(name='Leave a Review', value=f"React with <:surebuddy1:917122193287163924> to leave a review about the server")
embed.add_field(name='Server Invite', value=f'React with <:smirk:910565317363773511> to get the server invite.')
embed.set_footer(text='Any questions asked that isnt related to the list, you will be severely abused')
msg = await message.author.send(embed=embed)
await msg.add_reaction("<:Wojak1:917122152078147615>")
await msg.add_reaction("<:grim1:925758467099222066>")
await msg.add_reaction("<:Lovecat:919055184125100102>")
await msg.add_reaction("<:gasm:917112456776679575>")
await msg.add_reaction("<:surebuddy1:917122193287163924>")
await msg.add_reaction("<:smirk:910565317363773511>")
sent_users.append(message.author.id)
try:
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ['<:Wojak1:917122152078147615>', '<:grim1:925758467099222066>','<:Lovecat:919055184125100102>','<:gasm:917112456776679575>','<:surebuddy1:917122193287163924>','<:smirk:910565317363773511>']
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "<:Wojak1:917122152078147615>":
embed = discord.Embed(color=color)
embed.set_author(name=f"Misaland Member Report", icon_url=f'{message.author.avatar_url}')
embed.add_field(name="How to Report:", value="Send the ID of the person you are reporting and attach a screenshot breaking the rules")
embed.set_footer(text="Misaland | Member Report")
await message.author.send(embed = embed)
message = await client.wait_for("message", timeout=60, check=lambda m: m.channel == message.channel and m.author == message.author)
embed = discord.Embed(title=f"{message.content}", color=color)
await modmail_channel.send(embed=embed)
except asyncio.TimeoutError:
await message.delete()
Try putting
await bot.process_commands(message)
at the end of your code in
async def on_message(message):
If you're using commands outside of on_message, it's overridden

Get informations in a function to use it in another function DISCORD.PY

i have a little problem with my code and i don't find any solutions,...
I write a code for my discord bot :
#client.event
async def on_message(message):
if message.content.startswith("!init"):
if message.content.split()[1] == 'règles':
id_channel = 893442599019511829
embed = discord.Embed(title = 'Création bot', description = "par Archi's modo")
embed.add_field(name="Règlement de la LSPD", value="En cliquant sur l'icône ✅ vous reconnaissez avoir blablabla,...")
mess = await client.get_channel(id_channel).send(embed=embed)
await mess.add_reaction('✅')
#client.event
async def on_raw_reaction_add(payload):
id_channel = 893442599019511829
id_message = ?????
role_a_donner = "zabloublou"
message_id = payload.message_id
member = payload.member
if message_id == id_message:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == '✅':
role = discord.utils.get(guild.roles, name=str(role_a_donner))
else:
role = discord.utils.get(guild.role, name=payload.emoji.name)
if role is not None:
if member is not None:
await member.add_roles(role)
channel = client.get_channel(id_channel)
await channel.send(member.mention)
And i don't know how can i get id of the message sended by the bot to use it in my function on_raw_reaction_add
Can someone help me please ?
You should consider using wait_for instead for this kind of use.Your method is mostly used for reaction roles.
Here is an example of wait_for reaction grabbed from discord.py docs for 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('👍')

How to make a Discord.Py random reaction game

How can I make the bot choose a right random answer (as a reaction)
And if the user gets it right send a winner message
if its wrong send a loser message.
redcrew = '<:redcrewmates:776867415514153031>'
bluecrew = '<:bluecrewmates:776867439085617153>'
limecrew = '<:limecrewmates:776867489866711041>'
whitecrew = '<:whitecrewmates:776867529900425217>'
await msg1.add_reaction(redcrew)
await msg1.add_reaction(bluecrew)
await msg1.add_reaction(limecrew)
await msg1.add_reaction(whitecrew)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) ==
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.send('Sorry, you took too long to vote!')
else:
await ctx.send('hello')
def setup(bot):
bot.add_cog(games(bot))```
**DONT WORRY ABOUT THE INDENTS**
import random
#bot.command()
async def reaction_game(ctx):
reactions = [
'<:redcrewmates:776867415514153031>',
'<:bluecrewmates:776867439085617153>',
'<:limecrewmates:776867489866711041>',
'<:whitecrewmates:776867529900425217>'
]
winning_reaction = random.choice(reactions)
message = await ctx.send('some message')
for reaction in reactions:
await ctx.add_reaction(reaction)
def check(reaction, user):
return user == ctx.author and str(reaction) == winning_reaction
try:
reaction, user = await bot.wait_for('reaction_add', check=check, timeout=60.0)
await ctx.send('You reacted with the winning emoji')
except asyncio.TimeoutError:
await ctx.send('You took too long to react')
else:
await ctx.send('hello')

How to cancel a pending wait_for

Assuming a command similar to this:
#bot.command()
async def test(ctx):
def check(r, u):
return u == ctx.message.author and r.message.channel == ctx.message.channel and str(r.emoji) == '✅'
await ctx.send("React to this with ✅")
try:
reaction, user = await bot.wait_for('reaction_add', timeout=300.0, check=check)
except asyncio.TimeoutError:
await ctx.send('Timeout')
else:
await ctx.send('Cool, thanks!')
Is there any way to cancel that wait_for if the user sends the same command multiple times before actually reacting to the message? So the bot stop waiting for reactions on previously sent messages and only waits for the last one.
Would something like this work for you?
pending_tasks = dict()
async def test(ctx):
def check(r, u):
return u == ctx.message.author and r.message.channel == ctx.message.channel and str(r.emoji) == '✅'
await ctx.send("React to this with ✅")
try:
if ctx.message.author in pending_tasks:
pending_tasks[ctx.message.author].close()
pending_tasks[ctx.message.author] = bot.wait_for('reaction_add', timeout=300.0, check=check)
reaction, user = await pending_tasks[ctx.message.author]
except asyncio.TimeoutError:
await ctx.send('Timeout')
else:
await ctx.send('Cool, thanks!')
You store all of the pending requests in a dict, and before creating another request you check if you are already have an existing task for this user, if you do you cancel it and create a new one

Categories