Cannot Check Reaction In Discord.py - python

So basically i was making a modmail system and the problem was we wanted the person who dmed the bot has to react to ✅ if he reacts then the bot has to reply him "OK"
but the code was not working so what is the problem how to fix it?
import discord
import asyncio
client = discord.Client()
#client.event
async def on_message(message):
# empty_array = []
# modmail_channel = discord.utils.get(client.get_all_channels(), name="mod-mail")
if message.author == client.user:
return
if str(message.channel.type) == "private":
embed = discord.Embed(title='Confirmation',
color=0x03d692)
embed.add_field(name="You're sending this message to **The Dynamic Legends**", value="React with :white_check_mark: to confirm." + "\nTo cancel this request, react with :x:.", inline=False)
confirmation_msg = await message.author.send(embed=embed)
await confirmation_msg.add_reaction('✅')
await confirmation_msg.add_reaction('❌')
sent_users = []
sent_users.append(message.author.name)
try:
print('Working')
def check1(reaction, user):
return user == client.user and user!='Mod Mail Humara#5439' and str(reaction.emoji) == '✅'
reaction, user = await client.wait_for("reaction_add", timeout=30.0, check=check1)
# print(reaction, user)
if str(reaction.emoji) == '✅':
message.author.send('yes)
client.run('TOKEN')

There's a logic problem in the check func
return user == client.user
It simply doesn't make sense, instead of == use != and don't put the user!='Mod Mail Humara#5439' part
Your check func fixed:
def check1(reaction, user):
return user != client.user and str(reaction.emoji) == '✅'
Also message.author.send is a coroutine, so you need to await it
await message.author.send("whatever")
Your code:
#client.event
async def on_message(message):
if message.author == client.user:
return
if isinstance(message.channel, discord.DMChannel):
embed = discord.Embed(title='Confirmation', color=0x03d692)
embed.add_field(name="You're sending this message to **The Dynamic Legends**", value="React with :white_check_mark: to confirm." + "\nTo cancel this request, react with :x:.", inline=False)
confirmation_msg = await message.author.send(embed=embed)
await confirmation_msg.add_reaction('✅')
await confirmation_msg.add_reaction('❌')
sent_users = []
sent_users.append(message.author.name)
try:
def check1(reaction, user):
return user != client.user and str(reaction.emoji) == '✅'
reaction, user = await client.wait_for("reaction_add", timeout=30.0, check=check1)
if str(reaction.emoji) == '✅':
await message.author.send('yes')
except Exception as e:
pass

Related

unknown discord.py glitch

Hello I was following a discord bot tutorial video step by step yet when i publish my code and try to respond to it, it would completly ignore me and I have no idea why it does this here is the whole code.
import discord
import random
TOKEN = 'is here'
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'bot':
if user_message.lower() == 'hello':
await message.channel.send(f'hello {username}!')
elif user_message.lower() == 'bye':
await message.channel.send(f'see you later {username}!')
return
elif user_message.lower() == '!random':
response = f'this is your random number: {random.randrange(50000)}'
await message.channel.send(response)
return
if user_message.lower() == '!anywhere':
await message.channel.send('this can be used anywhere!')
return
client.run(TOKEN)
Fixed it for you. Your client.run(token) was inside the last if statement so your bot would not have even started also you need to enable intents in your developer account otherwise the bot might not be able to read messages.
username = str(message.author).split('#')[0] is unnecessary when you can just use username = message.author.name
import discord
import random
import asyncio
intents = discord.Intents.default()
intents.messages = True
intents.guild_messages = True
intents.message_content = True
client = discord.Bot(intents=intents, messages = True, guild_messages = True, message_content = True)
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
username = message.author.name
channel = str(message.channel.name)
if message.author == client.user:
return
if message.channel.name == 'bot':
if message.content.startswith('hello'):
await message.channel.send(f'hello {username}!')
if message.content.startswith('!anywhere'):
await message.channel.send('this can be used anywhere!')
return
client.run('token_here')

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

The bot does not give out a role when you click on the reaction, there are no errors, how to fix it?

Good time of day, a message is created and a reaction is added, but when you click on it, the role is not issued.
Code:
#commands.command(aliases = ["меропртиятие"])
#commands.has_permissions(administrator=True)
async def mp(self, ctx):
emb = discord.Embed(title=f'Праздник ', description='Нажми на реакцию что бы получить роль',
colour=discord.Color.purple())
message = await ctx.send(embed=emb)
await message.add_reaction('✅')
roles = discord.utils.get(message.guild.roles, id=839599224000610344)
check = lambda reaction, user: client.user != user
while True:
reaction, user = await client.wait_for('reaction_add', check=check)
if str(reaction.emoji) == "✅":
await user.add_roles(roles)
print('[SUCCESS] Пользователь {0.display_name} получил новую роль {1.name}'.format(user, roles))
await user.send('TEST')
You should use the on_reaction_add event for this. Store the message id of the embed either in a database or file then check if the reaction_add's message id is that of the stored message_id. An example would be:
async def on_reaction_add(self, reaction, user):
message_id = reaction.message.id
if str(reaction.emoji) == "✅" and message_id == STOREDMESSAGEID:
# the rest of the code

How can i make my help command "reset" Without making a million wait_fors? discord.py

This is my help command:
#client.command(pass_context=True, aliases=['cmd', 'commands'])
async def help(ctx):
embed = discord.Embed(colour=discord.Colour.blurple())
embed=discord.Embed(title="", description="This is a list of everything Otay! can do! If you need additional help with Otay! join the [**support server**](https://discord.gg/Wa9DpJGEKv)", color=0x7289da)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/776181059757932615/784819540496351233/otay2.png")
embed.add_field(name='`🎉` ***Fun***', value='`8ball`, `coinflip`, `dice`, `joke`, `say`, `fact`, `ss`', inline=False)
embed.add_field(name='`⚒️` ***Moderation***', value='`kick`, `ban`, `unban`, `nick`, `purge`, `slowmode`, `mute`, `unmute`, `lock`, `unlock`', inline=False)
embed.add_field(name='`⚠️` ***Setup***', value='`prefix`, `welcome`', inline=False)
embed.add_field(name='`🕹️` ***Games***', value='`rps`, `tictactoe`', inline=False)
embed.add_field(name='`🎁` ***Giveaway***', value='`gstart`', inline=False)
embed.add_field(name='`📷` ***Images***', value='`cat`, `dog`, `fox`, `koala`, `panda`, `meme`, `blursed`', inline=False)
embed.add_field(name='`🔧` ***Utilities***', value='`avatar`, `ping`, `poll`, `serverinfo`, `botinfo`, `userinfo`, `bitcoin`, `snipe`, `createinvite`, `password`', inline=False)
embed.add_field(name="`🎫` ***Ticket***", value="`configureticket`", inline=False)
embed.set_footer(icon_url=f"https://cdn.discordapp.com/attachments/776181059757932615/784819540496351233/otay2.png", text=ctx.author)
embed.timestamp = datetime.datetime.now()
msg = await ctx.send(embed=embed)
def checkifnotbot(reaction, user):
return user != client.user
await msg.add_reaction('🎉')
await msg.add_reaction('⚒️')
await msg.add_reaction('⚠️')
await msg.add_reaction('🕹️')
await msg.add_reaction('🎁')
await msg.add_reaction('📷')
await msg.add_reaction('🔧')
await msg.add_reaction('🎫')
await msg.add_reaction('🔗')
reaction, user = await client.wait_for("reaction_add", check=checkifnotbot)
if str(reaction.emoji) == "🎉":
embedfun=discord.Embed(title="`🎉`Help Fun", color=0x7298da)
await msg.edit(embed=embedfun)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "⚒️":
embedmod=discord.Embed(title="`⚒️`Help Moderation", color=0x7298da)
await msg.edit(embed=embedmod)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "⚠️":
embedsetup=discord.Embed(title="`⚠️`Setup", color=0x7289da)
embedsetup.timestamp = datetime.datetime.now()
await msg.edit(embed=embedsetup)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "🕹️":
embedgames=discord.Embed(title="`🕹️Help Games`", color=0x7289da)
await msg.edit(embed=embedgames)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "🎁":
embedgiveaway=discord.Embed(title="`🎁`Help Giveaway", color=0x7298da)
await msg.edit(embed=embedgiveaway)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "📷":
embedimages=discord.Embed(title="`📷`Help Images", color=0x7298da)
embedimages.timestamp = datetime.datetime.now()
await msg.edit(embed=embedimages)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "🔗":
embedlinks=discord.Embed(title="`🔗`Links", color=0x7289da)
await msg.edit(embed=embedlinks)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "🔧":
embedutils=discord.Embed(title="`🔧`Help Utilities", color=0x7298da)
embedutils.timestamp = datetime.datetime.now()
await msg.edit(embed=embedutils)
await msg.clear_reactions()
await msg.add_reaction('↩️')
elif str(reaction.emoji) == "🎫":
embedticket=discord.Embed(title="`🎫`Help Ticket", color=0x7289da)
await msg.edit(embed=embedticket)
await msg.clear_reactions()
await msg.add_reaction('↩️')
def checkifbot(reaction, user):
return user != client.user
reaction, user = await client.wait_for("reaction_add", check=checkifbot)
if str(reaction.emoji) == "↩️":
await msg.edit(embed=embed)
await msg.clear_reactions()
What i want to happen The embed "resets" it adds all the reactions again and just worked like if you typed -help.
My problem I don't know how to make it edit to the normal help command, because if it edits back and you need to add the reactions again you need to make like a million wait_fors
What i've tried
def checkifbot(reaction, user):
return user != client.user
reaction, user = await client.wait_for("reaction_add", check=checkifbot)
if str(reaction.emoji) == "↩️":
await msg.edit(embed=embed)
await msg.clear_reactions()
Problem with this is that i need to make so many wait_fors because if people want to see another category they have to click the reaction again.
And i tried doing this but this just sends it again and doesnt edit it
def checkifbot(reaction, user):
return user != client.user
reaction, user = await client.wait_for("reaction_add", check=checkifbot)
if str(reaction.emoji) == "↩️":
await help(ctx)
So is there a way to do something like: await msg.edit(help)(ctx)? Or how can i solve this problem?
You can solve this by creating a simple get_help function, that is
async def get_help(ctx):
return embed
# whatever u are currently doing in help(ctx), but return embed instead of sending
async def add_reactions(msg, ctx):
#add reactions
#add wait_for
async def help(ctx):
msg = await ctx.send(embed=get_help(ctx))
await add_reactions(msg, ctx)
def checkifbot(reaction, user):
return msg.id == reaction.message.id and user != client.user #improved check
reaction, user = await client.wait_for("reaction_add", check=checkifbot)
if str(reaction.emoji) == "↩️":
await msg.edit(embed = get_help(ctx))
However, you need not go through this much hassle and use discord.py's HelpCommand. which might be easier to implement and modify as per need.

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