Having trouble with check = True using on_raw_reaction_add - discord.py

I'm having trouble with my check = True. I can't seem to get identify the member making the reaction. Here is the code:
#bot.command()
async def buy(ctx):
reaction = await ctx.reply('Pick \U0001f44d')
#bot.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
def check(pl):
return pl == payload.member and str(payload.emoji) == '\U0001f44d'
try:
pl = await bot.wait_for('raw_reaction_add', timeout=3.0, check=check)
except asyncio.TimeoutError:
await channel.send("no one picked")
await payload.member.send("you")
else:
if payload.emoji == '\U0001f44d':
await channel.send("you picked 1")```
My I idea is to have someone call the command and then allowing more than one member to be able to react thus the bot.event. What am I doing wrong for my check to not = True?

Maybe you have an issue with the check
I suggest to replace your check with this:
check = lambda payload: payload.message_id == msg.id and payload.channel_id == ctx.channel.id and str(payload.emoji) == '\U0001f44d'
payload = await client.wait_for('raw_reaction_add', check=check, timeout=30)

Related

discord.py how takes 1 values per user

problem: i want a command that is capable to takes more than one user
like
1 place congrats juan
2 place congrast dolores
3...
obviously if they answered it correctly
i have a command but it only takes the first correct value it would be nice if you can help me
#bot.command()
async def rev(ctx):
a = "liechtenstein" #this is just an example
b = a[::-1]
await ctx.send(a)
def check(msg: discord.Message) -> True:
return msg.content == b and msg.channel == ctx.message.channel
try:
guess = await bot.wait_for('message', timeout=7, check=check)
await ctx.send(f"congrats {guess.author}")
except asyncio.TimeoutError:
await ctx.send("ups time over")```
the problem is when the answer is correct it break, but i want others users continue sendings messages
how can i change it to
guess = await bot.wait_for('message', timeout=7, check=check)
await ctx.send("Now Next One")
guess2 = await bot.wait_for('message', timeout=7, check=check)
await ctx.send("Now Next One")
....
await ctx.send(f"congrats {guess.author}")
Something Like This !

Discord.py Check doesnt seem to apply. Doesnt do anything

I wanted to create a bot with a spam feature, but with the condition that it checks for a stop message every cycle. I have tried looking at other posts but neither of them really helped or worked. The check doesn't seem to do aynthing as if the code doesn't reach it. I tried to spot any of the "checked" messages I put into the code to be displayed in the console, but they are not printed, thus my suspicion.
I get no errors in the console, and typing ' $stop ' does nothing. Any Idea why?
Thank you.
async def bot_spam(message):
try:
msg = message.content.split(' ')
if msg[2] == '1':
await message.channel.send(f"You will ping {msg[1]}, once.")
elif msg[2] == '0':
await message.channel.send("You cant ping 0 times.")
return
else:
await message.channel.send(f"You will ping {msg[1]}, {msg[2]} times.")
time.sleep(1)
msgr = int(msg[2])
global spam
spam = True
while spam is True and msgr > 0:
def check1(msg1: discord.Message):
print("checked")
if msg1.content == "$stop":
return False
return True
try:
if await bot.wait_for('message', check=check1, timeout=1.5):
print("checked 2")
await message.channel.send("Stopping.")
spam = False
except asyncio.TimeoutError:
await message.channel.send(f"{msg[1]}")
msgr -= 1
await message.channel.send("Done.")
except IndexError:
await message.channel.send("Your arguments don't make sense \n It's '$spam #someguy timesyouwantpinged'")
This is a logic issue
def check1(msg1: discord.Message):
print("checked")
if msg1.content == "$stop":
return False
return True
You are returning False when "$stop" is typed, thus the bot keeps waiting for a message until check returns True
Created a variable that checks for $stop using on_message outside the cycle instead of within it.
async def on_message(message):
if message.author == client.user:
return
else:
if message.content == "$stop":
stop = True
return
...
while stop is False and msgr > 0:
await message.channel.send(f"{msg[1]}")
time.sleep(0.5)
msgr -= 1
if stop is True:
await message.channel.send("Stopped.")
else:
await message.channel.send("Done.")

Discord.py | How to write multiple events with the same name?

Iv'e been trying to create 3 on_raw_reaction_add commands, but only the one positioned last works(doesn't matter which one I put last).
Here's my code:
#client.event
async def on_raw_reaction_add(payload4: discord.RawReactionActionEvent):
message_id = payload4.message_id
if message_id == 921150661456986122:
if payload4.emoji.name == '**':
guild_id = payload4.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
channel = guild.get_channel(921114527075020841)
message = await channel.fetch_message(message_id)
server = message.guild.owner
await server.send(f'''{payload4.member.mention} asked for the ** role.''')
user = client.get_user(payload4.user_id)
emoji = client.get_emoji(767057115306655775)
await message.remove_reaction(emoji, user)
#client.event
async def on_raw_reaction_add(payload3: discord.RawReactionActionEvent):
message_id = payload3.message_id
if payload3.emoji.name == '*':
guild_id = payload3.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
channel = guild.get_channel(921114527075020841)
message = await channel.fetch_message(message_id)
server = message.guild.owner
await server.send(f'''{payload3.member.mention} asked for the * role.''')
user = client.get_user(payload3.user_id)
emoji = client.get_emoji(767057122054635540)
await message.remove_reaction(emoji, user)
#client.event
async def on_raw_reaction_add(payload2: discord.RawReactionActionEvent):
message_id = payload2.message_id
if message_id == 921114830356762666:
guild_id = payload2.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload2.emoji.name == 'vip':
channel = guild.get_channel(921114527075020841)
message = await channel.fetch_message(message_id)
server = message.guild.owner
await server.send(f'''{payload2.member.mention} asked for the vip role.''')
user = client.get_user(payload2.user_id)
emoji = client.get_emoji(767064946919735298)
await message.remove_reaction(emoji, user)
I thought of maybe changing the first 2 events to "bot" and "cord" but it didn't work.
You can't make multiple events, you can though make multiple listeners!
#client.listen('on_raw_reaction_add')
async def my_cool_function(payload: discord.RawReactionActionEvent):
# ... do something
#client.listen('on_raw_reaction_add')
async def my_second_cool_function(payload: discord.RawReactionActionEvent):
# ... do something else
# or
#client.listen()
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
# ... do something
#client.listen()
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
# ... do something else
You can only have a total of 25 listeners.
In python, you can't have multiple functions with the same name, so you can't have multiple events with the same name. As Rose mentioned, if you really want to have the code in different functions, for example because they are in different files, you can use listeners. But if you have these functions in one file, or you hit the limit of 25 listeners, you should add all the code in one function:
#client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
message_id = payload.message_id
if message_id == 921150661456986122:
#add the code that is inside the if in the first function here, but rename payload4 to payload
if payload.emoji.name == '*':
#add the code that is inside the if in the second function here, but rename payload3 to payload
if message_id == 921114830356762666:
#add the code that is inside the if in the third function here, but rename payload2 to payload

Discord.py create an embed message command

I was trying to make a embed command with time limit, só i started doing it, and at my first try to make it timed it didn't work.
So i searched here, found one sample and tried to do like it (as you can see at my code below), but it didn't work too.
Then i tried to copy that code and pasted at my bot.
Guess...it didn't work -_-, now i'm here, asking gods to help.
client.command(aliases=["createEmbed", "embedCreate"])
async def embed(ctx,):
Questions = ["Titulo?", "Cor? (Hex sem #)", "Descrição?"]
Responses = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
#try:
await ctx.send(Questions[0])
title = await client.wait_for('message',timeout=2.0,check=check)
#except asyncio.TimeoutError(*title):
#await ctx.send("Demorou muito")
#return
#else:
Responses.append(title.content)
await ctx.send(Questions[1])
cor = await client.wait_for('message',timeout=25.0,check=check)
Responses.append(cor.content)
await ctx.send(Questions[2])
descrição = await client.wait_for('message',timeout=25.0,check=check)
Responses.append(descrição.content)
cor2 = Responses[1]
corHex = int(cor2, 16)
embedVar = discord.Embed(title=Responses[0], description=Responses[2], color=corHex)
await ctx.send(embed=embedVar)
At my code you can see the piece with #, that is the piece that i tried to test the time command.
If i remove the time command, it works.
It is better to loop through questions and get the date after that make the embed. Below is an example of how to get the Title and Description. You can modify it how you like
#client.command(aliases=["createEmbed", "embedCreate"])
async def embed(ctx):
questions = ["Title?", "Description?"]
responses = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for question in questions:
try:
await ctx.send(question)
message = await client.wait_for('message', timeout=15, check=check)
except asyncio.TimeoutError:
await ctx.send("Timeout")
return
else:
responses.append(message.content)
embedVar = discord.Embed(title=responses[0], description=responses[1])
await ctx.send(embed=embedVar)

how do i resolve this [ discord.py ]

how are you doing today i sure hope your doing great im sorry for the spam on other account i apologize. ok so my problem is that i switched from client to bot basically bot = commands.Bot i tried renaming all the commmands to bot.event or bot.command can someone pls help me pls i would appreciate it thank you here is the code :)
#bot.command()
async def ping(ctx):
await ctx.send(f'Pong!\n`{round(client.latency*1000)}ms`')
#bot.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = [ "It is certain.",
"As I see it, yes",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count it",
"It is certain.",
"It is decidedly so.",
"Most likely.",
"My reply is no."
"My sources say no.",
"Outlook not so good.",
"Outlook good.",
"Reply hazy, try again.",
"Signs point to yes.",
"Very doubtful.",
"Without a doubt.",
"Yes.",
"Yes – definitely.",
"You may rely on it." ]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
#commands.has_permissions(ban_members=True)
#bot.command()
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
await user.ban(reason=reason)
kick = discord.Embed(title=f":boom: Kicked {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=kick)
await user.send(embed=kick)
#commands.has_permissions(ban_members=True)
#bot.command()
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
await user.ban(reason=reason)
ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=ban)
await user.send(embed=ban)
#bot.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
#bot.command(pass_context = True)
async def mute(ctx, user_id, userName: discord.User):
if ctx.message.author.server_permissions.administrator:
user = ctx.message.author
role = discord.utils.get(user.server.roles, name="Muted")
#bot.command()
async def serverinfo(ctx):
name = str(ctx.guild.name)
description = str(ctx.guild.description)
owner = str(ctx.guild.owner)
id = str(ctx.guild.id)
region = str(ctx.guild.region)
memberCount = str(ctx.guild.member_count)
icon = str(ctx.guild.icon_url)
embed = discord.Embed(
title=name + " Server Information",
description=description,
color=discord.Color.blue()
)
embed.set_thumbnail(url=icon)
embed.add_field(name="Owner", value=owner, inline=True)
embed.add_field(name="Server ID", value=id, inline=True)
embed.add_field(name="Region", value=region, inline=True)
embed.add_field(name="Member Count", value=memberCount, inline=True)
await ctx.send(embed=embed)
await client.add_roles(user, role)
#bot.command()
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
#bot.command()
async def afk(ctx, mins):
current_nick = ctx.author.nick
await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.")
await ctx.author.edit(nick=f"{ctx.author.name} [AFK]")
counter = 0
while counter <= int(mins):
counter += 1
await asyncio.sleep(60)
if counter == int(mins):
await ctx.author.edit(nick=current_nick)
await ctx.send(f"{ctx.author.mention} is no longer AFK")
break
def setup(bot):
bot.add_cog(Afk(bot))
def user_is_me(ctx):
return ctx.message.author.id == "Your ID"
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
#bot.command()
#commands.has_permissions(kick_members=True)
async def giveaway(ctx):
await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")
questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await bot.wait_for('messsage', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
return
channel = bot.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send(f"You didn't answer with a proper unit. Use (s|m|h|d) next time!")
return
elif time == -2:
await ctx.send(f"The time just be an integer. Please enter an integer next time.")
return
prize = answers[2]
await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
embed = discord.embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
embed.add_field(name = "Hosted by:", value = ctx.author.mention)
embed.set_footer(text = f"Ends {answers[1]} from now!")
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
#bot.command()
#commands.has_permissions(kick_members=True)
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
try:
new_msg = await channel.fetch_message(id_)
except:
await ctx.send("The ID that was entered was incorrect, make sure you have entered the correct giveaway message ID.")
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations the new winner is: {winner.mention} for the giveaway rerolled!")
if you want me to answer anything to help you solve it feel free to comment thank you so much have a great day!
It seems like you copied most of the code from the internet and bashed it together to create a bot or a cog (based on your question I would guess a bot).
Assuming this is a snippet of your main bot file and not a cog there are a couple of things that could be different:
Put your utility functions in one place (peferably after your import statatements). It's good practise overall and makes more readeable code.
Unless you have a cog class in the same file as your bot instance (which is bad practise) you shouldn't need this:
def setup(bot):
bot.add_cog(Afk(bot))
If there is a cog class named Afk you should move it into a separate file (putting the cog class into the main bot file defeats the purpose of the cog)
In your mute command you have pass_context = True. This is from the old version of discord.py and is no longer needed.
I can't tell you much more since there's no point in trying to debug your code since you didn't give us any errors or stacktrace to work with.
It is very exhausting, so you can just leave client in every command, just write this client = commands.Bot(command_prefix = 'your prefix') it is the same bot, but it just has a different name.
If you meant that, because i didn't really understand what you need

Resources