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
Related
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
I get this error on my bot when mentioning a role,here is the error,
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unhashable type: 'set'
my code:
import os
import discord
from discord.ext import commands
from discord import Intents
from apikeys import *
intents = Intents.all()
client = commands.Bot(intents = intents, command_prefix="-", case_insensitive=True)
#client.event
async def on_ready():
for emoji in client.emojis:
print("Name:", emoji.name + ",", "ID:", emoji.id)
print('Bot is Online {0.user}'.format(client))
print("--------------------------------------------------------------------------------------------------------------------------------------------------------")
client.remove_command('help')
emojigood = '\N{THUMBS UP SIGN}'
emojibad="\N{THUMBS DOWN SIGN}"
#client.command()
async def war(ctx):
await client.wait_until_ready()
embed = discord.Embed(title='War', description='You are starting a war, do you want to continue?', color=0x00000)
msg = await ctx.send(embed=embed)
await msg.add_reaction(emojigood)
await msg.add_reaction(emojibad)
def check(r, user):
return (r.emoji == emojigood or r.emoji == emojibad) and r.message == msg and user != client.user
r, user = await client.wait_for('reaction_add',check=check)
if r.emoji == emojigood:
embed = discord.Embed(title='War', description='Please now choose a country', color=0x00000)
await ctx.send(embed=embed)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await client.wait_for('message', check=check)
if len(msg.role_mentions) > 0:
role = msg.role_mentions[0]
channel = client.get_channel({849549009038344262})
await channel.send(f"{role.mention} {ctx.author} has declared war on you.")
else:
await ctx.send("Invalid role mentioned")
else:
await ctx.send("Cancelled")
client.run(token)
What's meant to happen:
Me:-war
Bot:Are you sure
Me:reacts
Bot:Type in role
Me:(role name)
Bot:....
{849549009038344262}
is a set literal for a set containing a number. discord.py is using hashing under the hood to look up channels, which is failing because it is not possible to hash sets. You should be passing a regular int instead of a set:
channel = client.get_channel(849549009038344262)
(Sorry for my english)My bot must give role by reaction on emoji, but it doesn't do it. But it doesn't send error-message. Please help.
My code:
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix = ".",intents = discord.Intents.all())
#client.event
async def on_ready():
print(discord.__version__)
Channel = client.get_channel(815949348948934716)
Text= "Выбери свою роль😇"
Moji = await Channel.send(Text)
await Moji.add_reaction('🏃')
#client.event
async def on_reaction_add(reaction, user):
Channel = client.get_channel(815949348948934716)
if reaction.message.channel.id != Channel:
return
if reaction.emoji == "🏃":
Role = discord.utils.get(user.server.roles, name="PUBG")
await user.add_roles(Role)
client.run("My token")
You must use an event called on_raw_reaction_add. You might want to read the Docs.
Now to the further procedure:
Define the event:
#client.event
async def on_raw_reaction_add(payload): # We use payload
Define the role(s):
guild = client.get_guild(payload.guild_id) # Define the guild
member = get(guild.members, id=payload.user_id) # Get the member from the guild
# channel and message IDs should be integer:
if payload.channel_id == Channel_ID and payload.message_id == Message_ID: # Inser your ID's
if str(payload.emoji) == "YourEmoji":
role = get(payload.member.guild.roles, name='RoleName') # ID also possible.
Add the role:
if role is not None:
await payload.member.add_roles(role)
So your entire code would be:
#client.event
async def on_raw_reaction_add(self, payload):
guild = client.get_guild(payload.guild_id)
member = get(guild.members, id=payload.user_id)
if payload.channel_id == Channel_ID and payload.message_id == Message_ID:
if str(payload.emoji) == "YourEmoji":
role = get(payload.member.guild.roles, name='RoleName') # Or id='RoleID'
else:
role = get(guild.roles, name=payload.emoji)
if role is not None:
await payload.member.add_roles(role) # Add the role
To add more roles just use elif statements.
What are we doing?
Send a message into the defined channel (Channel_ID)
Add a role when someone reacts with the defined emoji to the message
I need to remove all member roles and return them back later, I had started working on it but when I had executed this function (just writing command to Discord chat), I got following message: discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
And here's the code I executed:
import asyncio
import discord
from discord.ext import commands
from discord.utils import get
TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
bot = commands.Bot(command_prefix='e!')
bot.remove_command("help")
#bot.command()
async def hardmute(ctx, time : str, member : discord.Member = None):
if time[-1]=='s':
tme = int(time[:-1])
elif time[-1]=='m':
tme = int(time[:-1])*60
elif time[-1]=='h':
tme = int(time[:-1])*60*60
elif time[-1]=='d':
tme = int(time[:-1])*60*60*60*24
else:
tme = False
permissionrole = get(ctx.guild.roles, id=544069068777324579)
hardmutedrole = get(ctx.guild.roles, id=717877658259554396)
if member is None and tme and not ctx.author.roles[-1] >= ctx.guild.me.roles[-1]:
await ctx.channel.send('{}, you're going to be hardmuted for {}'.format(ctx.author.mention, time))
roles = ctx.author.roles
await asyncio.sleep(3)
await ctx.author.remove_roles(*ctx.author.roles)
await ctx.author.add_roles(hardmutedrole)
await asyncio.sleep(tme)
await ctx.author.remove_roles(hardmutedrole)
await ctx.author.add_roles(*roles)
await ctx.channel.send('{} came back from hardmute!'.format(ctx.author.mention))
elif member is not None and tme and not member.roles[-1] >= member.guild.me.roles[-1]:
if permissionrole in ctx.author.roles:
await ctx.channel.send('{}, you're going to be hardmuted for {}'.format(member.mention, time))
roles = member.roles
await asyncio.sleep(3)
await member.remove_roles(*ctx.author.roles)
await member.add_roles(hardmutedrole)
await asyncio.sleep(tme)
await member.remove_roles(hardmutedrole)
await member.add_roles(*roles)
await ctx.channel.send('{} came back from hardmute!'.format(member.mention))
else:
await ctx.channel.send('You dont have permission role')
elif ctx.author.roles[-1] >= ctx.guild.me.roles[-1] and member is None:
await ctx.channel.send('{}, you have a role "{}", that is high or equal in role hierarchy than "{}"'.format(ctx.author.mention, ctx.author.roles[-1].name, ctx.guild.me.roles[-1].name))
elif ctx.author.roles[-1] >= member.guild.me.roles[-1]:
await ctx.channel.send('User {} have role "{}", that is high or equal in role hierarchy than "{}"'.format(member.name, member.roles[-1].name, ctx.guild.me.roles[-1].name))
bot.run(TOKEN)
I'm not pretty sure but ctx.author.roles returns a list, and you tried to remove role from list, you can try this instead:
roles = member.roles
await asyncio.sleep(3)
for role in ctx.author.roles:
await member.remove_roles(role)
await member.add_roles(hardmutedrole)
await asyncio.sleep(tme)
await member.remove_roles(hardmutedrole)
for role in roles:
await member.add_roles(role)
I've looked everywhere and people just tell me to use the documentation and that doesn't help, I've already got on_message(message) defined so I can't use a member parameter and I want people to be set to a certain role when they say a keyword
here's what I got but it doesn't work:
if message.content.lower() == "!changeadmin"
role = discord.utils.get(server.roles, name="Administrator")
await client.add_roles(member, role)
I always get returned with
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\josep\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\josep\OneDrive\Documents\New folder\New folder\mybot1.py",
line 58, in on_message
role = discord.utils.get(server.roles, name="admin")
AttributeError: 'str' object has no attribute 'roles'
EDIT:
This is my full code (excluding the token at the bottom):
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
import ctx
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
chat_filter = ["CUNT", "NIGGER", "NIGGA", "FUCK", "BITCH", "DICK", "WANKER"]
bypass_list = ["227007454775476224"]
possible_responses = [
'That is a resounding no',
'It is not looking likely',
'Too hard to tell',
'It is quit possible',
'Definitely',
]
server = '242547220765868033'
roles = ['442351132615114772']
#client.event
async def on_ready():
print("Bot is online and connected to Discord")
bot = commands.Bot(command_prefix='!', description='A bot that greets the user back.')
#client.event
async def on_message(message):
contents = message.content.split(" ") #contents is a list type
for word in contents:
if word.upper() in chat_filter:
if not message.author.id in bypass_list:
try:
await client.delete_message(message)
await client.send_message(channel.message, "**Hey!** You're not allowed to use that word here!")
except discord.errors.NotFound:
return
if message.content.upper().startswith('!PING'):
userID = message.author.id
await client.send_message((discord.Object(id='442333293539622913')), "<#%s> Pong!" % (userID))
if message.content.upper().startswith('!SAY'):
if message.author.id == "227007454775476224" or message.author.id == "399959323591180288":
args = message.content.split(" ")
await client.send_message(message.channel, "%s" % (" ".join(args[1:])))
else:
await client.send_message(message.channel, "Sorry only the bot owner has permission to use this command")
if message.content.lower() == "cookie":
await client.send_message(message.channel, ":cookie:") #responds with Cookie emoji when someone says "cookie"
if message.content.lower() == "!website":
await client.send_message(message.channel, "habbo.com")
if message.content.upper().startswith('!EIGHTBALL'):
await client.send_message(message.channel, random.choice(possible_responses))
if message.content.lower() == '!changeadmin':
role = discord.utils.get(server.roles, name="admin")
await client.add_roles(member, role)
sorry if this a late reply :)
so if u wanna add roles to members try this code:
#client.command()
#commands.has_permissions(administrator=True)
async def giverole(ctx,member :discord.Member,role):
try:
add_role= discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(add_role)
await ctx.send('Updated')
except:
await ctx.send("role not found!")
so the code gonna work like this: let's say prefix= "?"
?giverole #member example
the bot gonna search a role name "example" from guild role and give it to #member