How to run on_reaction_add commands - python

So I'm trying to create a discord.py bot, I'm using on_reaction_add to run the bot but it isn't working. When I run the script nothing happens, no error messages no nothing and I'm confused about what to do.
This is the whole code:
from discord.ext import commands
from discord import utils
bot = commands.Bot(command_prefix='!"')
#bot.command(name = '!"Help Ban', help = 'Bans a user')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching,
name='for !"help'))
print('We have logged in as {0.user}'.format(bot))
#bot.event
async def on_reaction_add(reaction, user):
message = reaction.message
if message.message_id == **CHANNEL NUMBER**:
member = utils.get(message.guild.members, id=message.user_id)
channel = bot.get_channel(**CHANNEL NUMBER**)
message.channel.send(f'#here, {member} wants to do parole')
#bot.event
async def on_message(message):
if '!"Ban' or '!"ban' in message.content:
run = True
if discord.utils.get(message.author.roles, name="Lord Jeebus") or discord.utils.get(message.author.roles, name="Supreme Lord Jeebus"):
messageTrue = message.content
messageTrue = messageTrue.split(' ')
Player = messageTrue[1]
Original = Player
Player = Player.replace('<', '')
Player = Player.replace('>', '')
Player = Player.replace(',', '')
userID = Player.replace('#', '')
userID = userID.replace('!', '')
member = await message.guild.fetch_member(userID)
banned_role = discord.utils.get(member.guild.roles, name="Death Row")
try:
reason = messageTrue[2]
await member.guild.ban(member, reason=reason)
await member.edit(roles=[])
await member.add_roles(banned_role)
await message.channel.send(f'{Original} now has 2 minutes before they are banned')
timer = 120
while timer != 0:
time.sleep(1)
timer -= 1
await message.channel.send(f'{Original} has been banned')
await member.ban(reason=reason)
except:
await message.channel.send(f'Could not ban user as no reason was given')
await bot.process_commands(message)
bot.run('TOKEN')
And this is the bit I'm stuck on:
#bot.event
async def on_reaction_add(reaction, user):
message = reaction.message
if message.message_id == **CHANNEL NUMBER**:
member = utils.get(message.guild.members, id=message.user_id)
channel = bot.get_channel(**CHANNEL NUMBER**)
message.channel.send(f'#here, {member} wants to do parole')
This code should be saying #here, Member wants to do parole it is supposed to do that in a private channel that is has access to but nothing is coming up, even in the command console.

Your code contains many errors and some wrong thinking. If you are new to Python/Reactions, then I would recommend tutorials or the Docs.
Many things in your code are also redundant.
First) message.message_id is wrong. You always query the ID of a channel, server etc. with .id and not with _id
Second) You don't need to query member at all. You have user as an argument and don't use it, that makes no sense. Accordingly, this line is also omitted.
Third) If you want to give the bot an instruction to send a message to the corresponding channel, you always have to do this with an await, this is completely missing in your code. You define channel but tell it to send the message in message.channel, so the bot has TWO specifications
The new code:
#bot.event
async def on_reaction_add(reaction, user):
if reaction.message.channel.id == PutYourChannelIDHere: # Check if the reaction is in the correct channel
channel = bot.get_channel(PutYourChannelIDHere) # Define your channel
await channel.send(f'#here, {user} wants to do parole') # Send it to the CHANNEL
The output:

Related

why, my mute role event stopps all commands from working

i'm trying to make a user mute command and event i’ve got the command working but now the event is preventing any and all commands from working only events respond now even if user is not muted, but when user does have muted role their messages are properly deleted, please help
#bot.event
async def on_message(message):
user = message.author
channel = bot.get_channel(1060922421491793981)
role = discord.utils.get(user.guild.roles, id=1060693595964842165)
if role in message.author.roles:
await message.delete()
await channel.send(f"#{user.display_name} **You are muted, You cant do this right now**")
command arguments are always strings, except the first argument ctx which is the context. What you can do in this case is derive the user from the mention in the ctx which you can get from ctx.message.mentions, so in this case you can make something like this.
#bot.command()
async def mute(ctx, user: str, duration_arg: str = "0", unit: str = "m"):
duration = int(duration_arg)
role = discord.utils.get(ctx.message.guild.roles, id=1060693595964842165)
await ctx.send(f":white_check_mark: Muted {user} for {duration}{unit}")
await ctx.message.mentions[0].add_roles(role)
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(role)
await ctx.send(f":white_check_mark: {user} was unmuted")
#bot.event
#commands.has_role("Muted")
async def on_message(message):
role = discord.utils.get(message.guild.roles, name="Muted")
if role in message.author.roles:
await message.delete()
await ctx.send("You cant do this")
await bot.process_commands(message)
Also two notes:
try not to write the type in the variable name. We know that the roleobject is an object, as everything in python is an object. Using role is sufficient enough.
You might not want to wait during an async function for something like this. Instead I suggest you look into tasks, and have some sort of mechanism that stores who is currently muted, in case the bot gets turned off
found the error was missing a process line
await bot.process_commands(message)
event now works

I want to get a list of members who reacted to a message and tag them

I'm trying to make a small matchmaking bot, and I want to get a list of people who reacted to a message the bot just sent so I can tag them in another message later. So far, I was able to get the message running and making something happen when it reaches 2 reactions:
import discord
import random
import os
from discord.utils import get
client = discord.Client(activity=discord.Game(name='Use !queue'))
#client.event
async def on_ready():
print('Logged in.'.format(client))
#client.event
async def on_message(message):
if message.content.startswith('!queue'):
await message.delete()
channel = client.get_channel(948024211736244255)
bot = await channel.send(
'<#&948034633373712445>\n\nA game is being set up for 8 players!\n\nTo join, react to this message with :white_check_mark:\n\nWhen 8 players have joined, maps will be voted upon and teams will be automatically balanced ingame.'
)
await bot.add_reaction(emoji='✅')
#client.event
async def on_raw_reaction_add(ctx):
ctx.channel_id == 948024211736244255
ctx.emoji.name == "✅"
channel = client.get_channel(948024211736244255)
message = await channel.fetch_message(ctx.message_id)
reaction = get(message.reactions, emoji=ctx.emoji.name)
count = reaction.count
if count == 2:
reactors = await message.reactions[0].users().flatten()
user = random.choice(reactors)
await channel.send("{} has reacted to the message.".format(user))
await message.delete()
client.run(os.getenv('TOKEN'))
But now I tried to get the bot to tag multiple people and I've been unsuccessful. Tried reading documentation and online help, but can't get anything to work.

Discord.py - sending user input to another channel via the bot (Rewrite)

I'm trying to make it so that you can get user input from a specific channel after a command, and then the bot sends the user input to a different channel. Can anyone tell me any errors that I've made and how to fix them because my code doesn't seem to work? I've only recently started using the discord.py rewrite.
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix=">")
#client.command()
async def resus(ctx):
await ctx.send("To reserve a username type - user (your discord tag) (the username you want) (if you want verification)")
def check(msg):
return msg.channel.id == 873501773971726346
msg = await client.wait_for("message", check=check)
if msg.content.lower() == msg.content.lower():
qwerty = bot.get_channel(873564203535958047)
await qwerty.send(f"{msg}")
else:
await ctx.send("There has been a problem, please try again.")
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(os.getenv('TOKEN'))
msg.channel is a discord.TextChannel instance, tou're comparing it to an integer, that's never True. You need to compare the channel ID instead:
def check(msg):
return msg.channel.id == 873501773971726346

Remove a message that the bot waited for using discord.py

Basically, im trying to make an autorole bot that takes a message from the user and then deletes the message and updates the role message after. The code I have so far is:
#commands.command()
#commands.has_any_role(786342585479593984, 787715167437324330)
async def rrtest(self, ctx, *, msg):
loop = True
j = "\n"
messagetext = [msg]
rolemessage = await ctx.send(f"```{j.join(messagetext)}```")
message = await ctx.send("Hold on!")
time.sleep(2)
while loop:
await message.edit(content="```Type the role you want to assign \n\nNo need to mention, just type the role name```")
msg = await self.client.wait_for('message', check=self.check(ctx.author), timeout=30)
# ^^^ this is the message i want to delete
what code would i use to delete msg?
Use the method .delete()
await msg.delete()
Also use await asyncio.sleep instead of time.sleep so it doesn't block you whole code.

Discord.py - Previous function affects the next function

I am trying to make a discord bot using Python and I want to make it so not everyone can mention #everyone or when they do the message will be deleted immediately, but then I have another code ($snipe) which doesn't work until I delete it, and after I do, it gives me the response! Any help would be appreciated!
#client.event
async def on_message(message):
xall = "#everyone"
role1 = discord.utils.get(message.guild.roles, name = "Owner")
role2 = discord.utils.get(message.guild.roles, name="Mod")
roles = role1 or role2
if xall in message.content:
if roles in message.author.roles:
pass
else:
await message.delete(message)
#Fun
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#client.command()
async def snipe(ctx):
await ctx.send("Aight, imma go snipe!")
#client.command()
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
slapped = ", ".join(x.mention for x in members)
await ctx.send('{} just got slapped for {}'.format(slapped, reason))
import discord
from discord.ext import commands
client = discord.Client()
#client.event
async def on_message(msg):
owner = discord.utils.get(msg.guild.roles, name="Owner")
mod = discord.utils.get(msg.guild.roles, name="Mod")
roles = (owner, mod)
if msg.mention_everyone:
if not any(r in msg.author.roles for r in roles):
await msg.delete()
client.run(TOKEN)
I have just ran this, and this works as expected. Removes the message if needed.

Categories