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
Related
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
I am trying to add roles in discord.py but I can't really make it work.
#bot.command(brief="Report member")
async def member(ctx):
if ctx.author.id != 783430063076147210:
await ctx.send("Mention the member you want to report")
message = await bot.wait_for('message', check=lambda message: ctx.author == ctx.author)
msg = message.content.replace("<","")
msg = msg.replace(">","")
msg = msg.replace("#","")
msg = msg.replace("!","")
#try:
msg = int(msg)
user = bot.get_user(msg)
await ctx.send('Are you sure you want to report ' + user.mention + "?")
message = await bot.wait_for('message', check=lambda message: ctx.author == ctx.author)
if message.content.lower() == "yes" or message.content.lower() == "y":
member = ctx.message.author
role = get(member.guild.roles, name="Reported")
user = ctx.guild.get_member(msg)
await bot.add_roles(user, role)
await ctx.send(user.mention + " was reported by " + member.mention + ".")
else:
await ctx.send("User was not reported!")
#except:
await ctx.send("Oops! That was not a user!")
I'm getting an AttributeError: 'Bot' object has no attribute 'add_roles', and the same with the other way
await user.add_roles(role)
returns AttributeError: 'NoneType' object has no attribute 'add_roles'
Is there something I'm missing?
Two ways of making this work:
1.
#bot.command()
async def role(ctx, member:commands.MemberConverter, role:commands.RoleConverter):
await member.add_roles(role)
^^ This method uses a role converter that accepts role ID, name, or mention.
I also use commands.MemberConverter because it accepts more methods of referencing a user than discord.Member, and the same thing for discord.Role.
2.
#bot.command()
async def role(ctx, member:commands.MemberConverter, role):
role = discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(role)
^^ This method uses discord.utils.get to get a guild role. From my knowledge, it only accepts role names and not role IDs or mentions.
bot.get_user() will return a User object, to which you cannot add roles, as no guild is specified. You could do ctx.guild.get_member(id) to get the Member object then add roles to that, but you'd be better of getting the member from the mentions attribute of a Message. Docs: https://discordpy.readthedocs.io/en/latest/api.html?highlight=mentions#discord.Message.mentions
Try something like this:
#bot.command()
async def role(ctx):
test = ctx.author
role = discord.utils.get(test.guild.roles, name="Name")
if role in test.roles:
await ctx.send("you already have a role")
else:
await test.add_roles(role)
Your line
await bot.add_roles(user, role)
needs to be replaced by
await user.add_roles(role)
these are my addrole and remouverole commands:
#bot.command()
#commands.has_permissions(administrator=True)
async def addrole(ctx, member : discord.Member, role : discord.Role):
await member.add_roles(role)
await ctx.send(f"{role} is added to {member}.")
#bot.command()
#commands.has_permissions(administrator=True)
async def removerole(ctx, member : discord.Member, role : discord.Role):
await member.remove_roles(role)
await ctx.send(f"{role} is removed from {member}.")
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.
I'm new to the discord API and I'm having trouble figuring out why my commands are not recognized. I've read through the documentation, but I'm not exactly sure where to look. Any help would be appreciated. Don't mind the hard-coded lists. I plan on changing that in the future. For now I just want to make sure that it works.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot online!")
#client.command(pass_context=True)
async def add_roles(member, *roles):
if message.content.startswith("!role"):
role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"]
entered_role = message.content[6:].upper()
role = discord.utils.get(message.server.roles, name=entered_role)
if role is None or role.name not in role_list:
# If the role wasn't found by discord.utils.get() or is a role that we don't want to add:
await client.send_message(message.channel, "Role doesn't exist.")
return
elif role in message.author.roles:
# If they already have the role
await client.send_message(message.channel, "You already have this role.")
else:
try:
await client.add_roles(message.author, role)
await client.send_message(message.channel, "Successfully added role {0}".format(role.name))
except discord.Forbidden:
await client.send_message(message.channel, "I don't have perms to add roles.")
#client.command(pass_context=True)
async def remove_roles(member, *roles):
if message.content.startswith("!unassign"):
role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"]
roles_cleared = True
for r in role_list:
# Check every role
role = discord.utils.get(message.server.roles, name=r)
if role in message.author.roles:
# If they have the role, get rid of it
try:
await client.remove_roles(message.author, role)
except discord.Forbbiden:
await client.send_message(message.channel, "I don't have perms to remove roles.")
roles_cleared = False
break
if roles_cleared:
await client.send_message(message.channel, "Roles successfully cleared.")
client.run("mytoken")
In function you need to have ctx variable
#client.comman(pass_context = True)
async def some_command(ctx, bla_bla, and_bla_bla):
pass
i think...
tell if it was helpful for u
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)