How to create multiple roles through discord.py bot? - python

I have been trying to make my discord bot create multiple roles through a command. But it simply doesn't work. Here is what I have done so far:
#commands.command()
async def create_roles(self, ctx):
guild = self.client.get_guild(783547639944839178)
channel = self.client.get_channel(809683610058752010)
await guild.create_role(name="red", color=discord.Color.value('F51720'))
await guild.create_role(name="skyblue", color=discord.Colour.value('11A7BB'))
await guild.create_role(name="yellow", color=discord.Colour.value('F8D210'))
await channel.send("Done.")
When I run this code I get this error:
Ignoring exception in command create_roles:
Traceback (most recent call last):
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\wave computer\PycharmProjects\pythonProject\cogs\roles.py", line 14, in create_roles
await guild.create_role(name="red", colour=discord.Colour.value('F51720'))
TypeError: 'member_descriptor' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'member_descriptor' object is not callable
Any help would be appreciated!

I am a bit late, but here is the solution.
You used discord.Color.value a bit wrong. For the colors you can use either a HEX or RGB code.
For a RGB code Discord has this function: discord.Color.from_rgb() and for a hex code you can simply define the color, for example:
customred = FF0000.
For your code I took once the RGB variant:
#commands.command()
async def create_roles(self, ctx):
guild = self.client.get_guild(GuildID)
channel = self.client.get_channel(ChannelID)
await guild.create_role(name="red", color=discord.Color.from_rgb(245, 23, 32))
await guild.create_role(name="skyblue", color=discord.Color.from_rgb(17, 167, 187))
await guild.create_role(name="yellow", color=discord.Colour.from_rgb(248, 210, 16))
await ctx.send("Done.")
You can of course define the color beforehand - cred = discord.Colour.from_rgb(248, 210, 16)) - and then use only cred as color:
await guild.create_role(name="red", color=cred)

Related

Dictionary "Command' Object is not subscriptable

I am trying to make a bot that does a very simple task, it adds points to a member in the channel for the time the bot is live, in a temporary context. Trying to accomplish this without databases, because I don't need a permanent record of these points. I seem to have come very close to a solution combining a lot of references I've found over the internet. In essence, I create a dictionary based on the member ID and add 1 that key value pair whenever I use the give command, however, I keep getting the error listed below, I appreciate your time and please if someone can explain to me WHY this sub scriptable error happens with my code, Thank you and have a great day.
Adding my code below:
import discord
from discord.ext.commands import Bot
from collections import defaultdict
TOKEN = '#code would go here.'
bot = Bot('!')
points = defaultdict(int)
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
#bot.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.content == "hello":
# SENDS A MESSAGE TO THE CHANNEL.
await message.channel.send("FIX CONTEXT")
# INCLUDES THE COMMANDS FOR THE BOT. WITHOUT THIS LINE, YOU CANNOT TRIGGER YOUR COMMANDS.
await bot.process_commands(message)
#bot.command(pass_context=True)
async def give(ctx, member: discord.Member):
points[member.id] += 1
ctx.send("{} now has {} radiation".format(member.mention, points[member.id]))
#bot.command(pass_context=True)
async def points(ctx, member: discord.Member):
ctx.send("{} has {} radiation".format(member.mention, points[member.id]))
bot.run(TOKEN)
The main thing I don't understand about my code is the line Command raised an exception: TypeError: 'Command' object is not subscriptable
We have logged in as RadiationTracker#7562
AdamKostandy: !!give AdamKostandy#9900 (ffg-game-chat)
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "!give" is not found
AdamKostandy: !give AdamKostandy#9900 (ffg-game-chat)
Ignoring exception in command give:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Adam/Documents/GitHub/Discord-Bot/main.py", line 34, in give
points[member.id] += 1
TypeError: 'Command' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Command' object is not subscriptable
AdamKostandy: !points AdamKostandy#9900 (ffg-game-chat)
Ignoring exception in command points:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Adam/Documents/GitHub/Discord-Bot/main.py", line 39, in points
ctx.send("{} has {} radiation".format(member.mention, points[member.id]))
TypeError: 'Command' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Command' object is not subscriptable

Error in the reportar command. Object has no attribute send on discord.py

async def reportar(ctx, *, text=None):
owner = bot.get_user(773913180271280129)
x = discord.Embed(title='**Report Error!**')
x.add_field(name='Server:', value=ctx.guild.name, inline=False)
x.add_field(name='ID of the Server:', value=ctx.guild.id, inline=False)
x.add_field(name='Report:', value=text, inline=False)
x.set_thumbnail(url=ctx.guild.icon_url)
x.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
x.timestamp = datetime.datetime.utcnow()
await owner.send(embed=x)
#Developer
await ctx.message.add_reaction('✅')
#reaction
y = discord.Embed(title='#Team B0T')
y.add_field(name=f'**Hello {ctx.author.display_name}**', value='*YOUR MESSAGE*')
y.timestamp = datetime.datetime.utcnow()
await ctx.author.send(embed=y)
I am trying to make a reportar command. If any user face problem in my bot. It can report and a Dm would be sent to me by the bot.
But, i am getting an error. Please help me out
Error -
Ignoring exception in command reportar:
Traceback (most recent call last):
File "C:\Users\manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\manoj\OneDrive\Desktop\Coding and editing\Mezuhashi.py", line 50, in reportar
await owner.send(embed=x)
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'```
You should enable the User Intent. To do that, add these 2 lines of code to your main file under the imports:
intents = discord.Intents.default()
intents.members = True # Subscribe to the privileged members intent.
bot = commands.Bot(command_prefix="your prefix", intents=intents)

Make the bot discord send a message when someone type "!clear" has no permission

#client.command(pass_context=True)
#commands.has_permissions(administrator=True)
async def clear(ctx,amount=1000):
await ctx.channel.purge(limit=amount)
#clear.error
async def clear_error(ctx,error):
if isinstance(error, MissingPermissions):
text = "Sorry {}, you do not have permissions to do that!".format(ctx.message.author)
await client.send_message(ctx.message.channel, text)
output: ( I want it to send a message to that user, who have no permission administration, and delete his message I dont understand this error, it happeen when I try to send please fix it ty would you fix it for me guys thank you im new here. )
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 777, in prepare
if not await self.can_run(ctx):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1087, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\utils.py", line 348, in async_all
for elem in gen:
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1087, in <genexpr>
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1790, in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Administrator permission(s) to run this command.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 71, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\cyberx\Desktop\Paid projects\Discord bot\bot.py", line 25, in clear_error
await client.send_message(ctx.message.channel, text)
AttributeError: 'Bot' object has no attribute 'send_message'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\cyberx\Desktop\Paid projects\Discord bot\bot.py", line 14, in on_message
await client.process_commands(message)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 976, in process_commands
await self.invoke(ctx)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 943, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 424, in dispatch_error await injected(ctx, error)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 77, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'send_message'
You need to make an error handler, like this:
#<commandname>.error
async def <commandname>_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions): #could be other type of error
await ctx.send(f"Sorry {ctx.author.mention}, you do not have permissions to do that!")
If you are a newcomer, I recommend reading this: https://vcokltfre.dev/tutorial/12-errors/
Also, to delete the trigger just use await ctx.message.delete()
Firstly, the error handler should be commands.MissingPermissions not MissingPermissions.
Secondly, client.send_message() was deprecated in the rewrite.
Thirdly, I don't think you can use discord.py in python 2.7, maybe upgrade to python 3.

Command raised an exception: TypeError: index 'wallet' cannot be applied to Cursor instances. Discord.py?

I am making a search command for my discord bot with mongodb. This command was not showed anywhere so im testing it around.This is what i made so far but i get the error shown in the title. I dont know how to fix it so if you know please tell me. It would really help it all. Here is my code
async def search(self, ctx):
apple = [
'Shoe',
'Sink',
'Car'
]
await ctx.send(f'What would you like to search? \n``{apple}``')
await open_account(self, ctx.author)
document = collection.find({"userid":ctx.author.id})
wallet_amt = document['wallet']
def check(msg):
return msg.author== ctx.message.author and message.channel==ctx.message.channel and str(msg.content) in ['Shoe','Sink','Car']
msg = await self.bot.wait_for("message", check=check)
if str(msg.content) == 'Sink':
earnings = random.randint(50,200)
await ctx.send(f'You chose to search the ``Sink`` You found <:Coin:842441305242206228> **{earnings}**! Why did you even look there?')
collection.update_one({"userid":ctx.author.id}, {"inc":{"wallet":earnings}})
else:
await ctx.send('XD')
Ignoring exception in command search:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/cogs/economy.py", line 51, in search
wallet_amt = document['wallet']
File "/home/container/.local/lib/python3.8/site-packages/pymongo/cursor.py", line 650, in __getitem__
raise TypeError("index %r cannot be applied to Cursor "
TypeError: index 'wallet' cannot be applied to Cursor instances
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: index 'wallet' cannot be applied to Cursor instances
find() returns a cursor; you likely want find_one() which returns a dictionary.
document = collection.find_one({"userid":ctx.author.id})

how can I display in the #channel, members with a certain role? (with discord.py)

I'm trying to write a command in my (first) bot that prints in the discord channel all members
in a certain #role (in this it's called "Serf")
this is my command/function
#client.command()
async def snap(ctx):
target = discord.Role.members("Serf")
for person in target:
await ctx.send(person)
but nothing happens and I get this error in the terminal
Ignoring exception in command snap:
Traceback (most recent call last):
File "/home/thonkpad/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "Python/thanosBot/bot.py", line 28, in snap
target = discord.Role.members("Serf")
TypeError: 'property' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/thonkpad/.local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "/home/thonkpad/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/thonkpad/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'property' object is not callable
The problem is you're calling the actual discord.Role object itself and not finding the Role object of the specific role you want. You could do something like this:
#client.command()
async def snap(ctx):
role = discord.utils.get(ctx.message.guild.roles, name="Serf")
target = role.members
for person in target:
await ctx.send(person.name)
target will be a list of discord.Member objects

Categories