#discord-bots
1 messages ยท Page 611 of 1
.text_channels, someone recently made guild.channels mistake earlier and wondered why it wouldnt send in random channel
i dunno how to do list comprehension
woop, forgot about that
Well, they never said specifcally a text channel
[ object/objects.atrribute for object in list if <condition>]```
good point lol
Nah just want to check it.
if discord.utils.get(guild.channels, name="lol"):
print("This Channel exists!")
else:
print("This Channel does not exist!")```
What if the channel name is `lol-xd`. Then it would be false right? So do I have to do something with `lol in name`
Nope. You just need to set the name kwarg to the name of the channel
so channel.name for channel in guild.text_channels if channel.name == 'general_chat'
That would return a list of channel names
If it's a text channel though, change guild.channels to guild.text_channels. It'll give it less to sort through should you have other channels like voice channels
if they do channel for channel ..... , That would be the channel object
im confused
so if i want the channel id, can i do
id for channel in guild.text_channels if channel.name == 'general_chat'
channel.id for channel in
oh ok
oh yeah i see now
oh i have actually used this b4
i needed to convert the keys of a dictionary where the keys were numbers but strings into a list of integers and used it
keylist = feetable.keys()
keylist = [int(i) for i in keylist]```
how do I split the list for the id
You can't really split lists, or that's not the correct term for what you want. Do you mean indexing?
message.mentions is 1nin length
mention.id for mention in message.mentions
Then that means you have no mentions
[<Member id=693828694816587876 name='Twig' discriminator='2140' bot=False nick=None guild=<Guild id=886045666781036624 name='twig bot!' shard_id=None chunked=False member_count=4>>]
this
thanks!
<generator object on_message.<locals>.<genexpr> at 0x7efff02877b0>
comes up
wdym :
nothing it just prints out that weird text
What do you need to do with your channels?
If someone pings someone i want the bot to ping the mentioned person again
if message.mentions:
for member in message.mentions:
await message.channel.send(f'{member.mention}')
Dang, sorry, mentions, mixed up two problems there
You can also do
''.join([member.mention for member in message.mentions])
yeah that would be less spammy
thanks I appreciate it so much
I have 2 reactions \๐ and \๐ Is there a way I could make a check to check for either one
Yes
how would I go about this
discord.utils.get(message.reactions,"๐")
Dont need it
You can make a check
To check reactions
yeah thats more the answer I was looking for
how would you do that though
im not sure how checks work
lambda reaction, user: reaction.emoji == '๐'
that would work for one but how could I do 2
You can make the bot wait_for() a reaction and check if the reaction is the one you want
but how for 2
do it twice?
Check 2 reactions he ment
await client.wait_for('reaction_add', check = lambda reaction, user: reaction.emoji == '๐' or '๐')
would that work
oh , if you just want to check that there are 2 reactions , you can use reaction.count
no
^
so if its ๐ is does one thing
if its ๐ it does another
lambda reaction, user: reaction.emoji in ['๐' ,'๐']```
or , py lambda reaction, user: reaction.emoji == '๐' or reaction.emoji=='๐'
then how could I differentiate which is which
and do something different depending on which is reactex
you get the discord.Reaction object , you can use reaction.emoji again to check which reaction it was
so
if reaction.emoji == '๐':
code
else:
more code
sure
k thanks
no need for the else block, just return something in the if
so
if reaction.emoji == '๐':
return await ctx.send('you reacted with a thumbs down')
more code here
I have to check for another reaction as well
sure ig
How do i make a say cmd for my bot like >say Sus and the bot does that
Echoing what a user says?
yessirr
@client.command()
async def say(ctx, *, user_text):
await ctx.send(user_text)
Indentation is probably wrong but you could fix that yourself
Is there a way to make bots recognize reactions?
if reaction.emoji == ':thumbsup:':
await member.send(f'Congrats! Your suggestion: {suggestion} was accepted. And will be added soon')
await channel2.send(embed=embed)
await mes.delete()
elif reaction.emoji == ':thumbsdown:':
await member.send(f'Sorry! Your suggestion: {suggestion} was not accepted.')
await mes.delete()
I have this code and im getting a error of inconsistant tabs and spaces error on the await channel2.send
You cannot use tabs and spaces in the same line
im not
Reindent everything
Read
read what
@commands.command()
async def get_channel(ctx, *, given_name=None):
for channel in ctx.guild.channels:
if channel.name == given_name:
wanted_channel_id = channel.id
await ctx.send(wanted_channel_id) # this is just to check ```
Trying to make a command to search for a channel and it gives the results/closest results
I'm not sure if this is the right way but this isn't working
i am using bot.command i will just change cleint to bot
@client.event
async def on_guild_join(guild):
owner = guild.owner
await owner.send("Helllo!")
I'm getting AttributeError: 'NoneType' object has no attribute 'send'
How can I create a vc with only certain members seeing it?
I am a rook ask @slate swan @final iron @slate swan @slate swan
you miss member intents
I have intents enabled
in the code as well?
Yeah
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = ',',description="Hello there", intents=intents)
you can pass a permission object while creating the channel
@slate swan nice pfp
as overwrite parameter
ty!
well , guild.owner returns None somehow , which can only be due to lack of intents
Since Guild.owner can be None sometimes, you should check if guild.owner is None, and if it is use fetch_user(guild.owner_id)
This isn't an intents issue
ah, good idea thanks
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
oh i see , it returns None if bot lacks member intents so said that
Ignoring exception in command suggest:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/bot.py", line 57, in suggest
reaction.emoji = None
UnboundLocalError: local variable 'reaction' referenced before assignment
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/nextcord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'reaction' referenced before assignment
It shouldn't be an intents issue
Because they show that their bot identifies with guild member intents on
So this is probably just a cache issue
yea
?
reaction.emoji = None
its not even in your code
maybe you didnt save the code and rerun it
its there
how do i link channels using channel ids in DMs?
<#CHANNELID>
ye doesnt work
It won't work in DMs
exactly
<#${channel.id}>
is there a workaround?
At least I don't think so? I'm not sure
And I don't know of any workaround
doesnt work in dms
oh ok
Huh, I just tested it
It does work
wot
Are you sure you're in the same server as the channel?
no lol
Show's up as deleted channel on my client
Cz u can't see my DM with Sand
Either way, yea I just tested you can mention channels in DMs
same
Cz u can't see your DM. You can only see my DM
The difference is of the PoV
I got it for him
@pliant gulch check the dm I just sent you

swear it said can't
!d discord.TextChannel.mention
property mention: str```
The string that allows you to mention the channel.
uh wrong reply
yes, its not
dont call it
....
if "Hello" in message.content:??
also where is line 19?
@bot.command
Low-key sherlocks discord bot will eventually be the ai that destroys earth
fixed now
DESTRUCTION
Comrade aint dead
ew replit

import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
from keep_alive import keep_alive
bot = commands.Bot(command_prefix = '>')
@bot.event
async def on_ready():
await bot.change_presence(status= discord.Status.idle, activity=discord.Game('Nuke Nuke'))
print("Comrade Ain't Dead")
@bot.command
async def on_message(message):
if message.author == bot.user:
return
elif message.content('Hello'):
await message.channel.send('Hello Comrade')
elif message.content('Hi'):
await message.channel.send('Hi. Did ya nuke USA?')
elif message.content('comrade', 'Comrade'):
await message.channel.send('Fuck You')
elif message.content('LMAO'):
await message.channel.send('You Dont Laugh In Russia')
elif message.content('Anime'):
await message.channel.send('Anime Sucks You Crazy MF')
if 'i solemnly swear that i am upto no good' in message.content.lower():
role = discord.utils.get(message.guild.roles, id=904021392998146118)
await message.author.add_roles(role)
elif 'mischief managed' in message.content.lower():
role = discord.utils.get(message.guild.roles, id=904021392998146118)
await message.author.remove_roles(role)
await bot.process_commands(message)
keep_alive()
bot.run("TOKEN")
something wrong
it doesnt reply on Hi or Hello or anything
@slate swan
@sullen shoal@slate swan
send the console
ikr like
step 1 get off replit
if 'hello' in message.content.lower():
await message.author.channel.send(message)
let me know when your done with that
?
i just host it on replit
yea no
use heroku
it is on stop for now
should i do this?
how do slash commands work
@slate swan
discord.Message.content is an attribute and can't be called. what you have to do is, #discord-bots message
uh ok
something wrong
cuz when i do >say Test
it doesnt work
@sullen shoal
You're missing an @
lol
Did you save and rerun your code?
if you have an errorhandler cog, how would you invoke custom error messages for commands?
everytime an error hits it runs both messages
yes
I reckon its likely due to on_message not hitting process comands line
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Put ur on_message into @bot.event
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
from keep_alive import keep_alive
bot = commands.Bot(command_prefix = '>')
@bot.event
async def on_ready():
await bot.change_presence(status= discord.Status.idle, activity=discord.Game('Nuke Nuke'))
print("Comrade Ain't Dead")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
elif message.content.startswith('Hello'):
await message.channel.send('Hello Comrade')
elif message.content.startswith('Hi'):
await message.channel.send('Hi. Did ya nuke USA?')
elif message.content.startswith('Comrade'):
await message.channel.send('Shut Up Fool')
elif message.content.startswith('hello'):
await message.channel.send('Hello Comrade')
elif message.content.startswith('hi'):
await message.channel.send('Hi. Did ya nuke USA?')
elif message.content.startswith('comrade'):
await message.channel.send('Fuck You')
elif message.content.startswith('LMAO'):
await message.channel.send('You Dont Laugh In Russia')
if 'i solemnly swear that i am upto no good' in message.content.lower():
role = discord.utils.get(message.guild.roles, id=904021392998146118)
await message.author.add_roles(role)
elif 'mischief managed' in message.content.lower():
role = discord.utils.get(message.guild.roles, id=904021392998146118)
await message.author.remove_roles(role)
await bot.process_commands(message)
@bot.command
async def say(ctx, *, user_text):
await ctx.send(user_text)
keep_alive()
bot.run("TOKEN")
Should work tbh
ye
Add () at the end of @bot.command?
bot.command()?
say "text" right
You're missing the brackets
^
btw can i configure it as like after using that command it deletes the message
await ctx.message.delete()
To delete the command
@bot.command()
async def say(ctx, *, user_text):
await ctx.send(user_text)
add after that?
B4 ctx.send
Do u wanna delete the command
Or the output?
@bot.command()
async def say(ctx, *, user_text):
await ctx.mssage.delete()
await ctx.send(user_text)
Yh
Message
Not mssage
if i do >say sus and the bot says sus Then the >say sus should be deleted
Yh
?
This will work
Does the bot message twice if we have 2 listeners in the code
how do we get the server avatar?
if you have multiple listeners of same event, yes
I have created 2 functions with 2 different listeners
unless, you have named the function same, it should work
using premium_since how can i find out how long a members been boosting for
would i have to do something like member.premium_since(UTCnow - 30%d)
or whatever the syntax is
Purge Command help @slate swan@quick gust
await ctx.channel.purge(amount=amount)
Enjoy
!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
A quick reference for Python's strftime formatting directives.
just this
async def purge(ctx, *, user_text):
await ctx.channel.purge(amount=amount)
async def purge(ctx, *):
await ctx.channel.purge(amount=amount)
- โฌ๏ธ
they just told you how to purge a specific amount of messages in a channel
now YOU make the command using the information.
and no what you did looks about wrong 
@thorny sequoia
@bot.command()
async def purge(ctx, amount=5):
await ctx.channel.purge(amount=amount)
?
amount: int = 5 so discord.py converts it / attempts to convert it to an integer.
if not then it will raise an error saying amount must be int, got str inetead.
but for the rest, seems about rigt
where? in the async def line or the ctx.channel one?
understood
@bot.command()
async def purge(ctx, amount: int = 5):
await ctx.channel.purge(amount=amount)
@pale zenithcorrect?
yes seems correct
where is the decorator?
:tias:
huh
I cant import ipc from nextcord.ext
@grand lagoon this isn't the correct channel for all this...
?
Please stop else I will have to ping the mods
ok
Please delete those GIFs
limit=amount
yea
@tall dust @crimson pulsar @arctic python
change to limit=amount
done already
worked?
it worked
cool
!warn 880878204863254600 don't drop out of context gifs in an on-topic channel
:x: The user doesn't appear to be on the server.
alright then
thnx
ping the @Moderators role in the future
kk
can someone help me with his 
whats rong
i want to make a snipe command that doesnt snipe blacklisted words
stored it in db
wanna check my code ?
yes
a json file is more than enough
class snipe(commands.Cog):
def __init__(self, bot,message=None,author=None,blacklisted_stuff=None):
self.bot = bot
self.message = message
self.blacklisted_stuff = [] if blacklisted_stuff is None else blacklisted_stuff
self.author = author
async def cog_command_error(self, ctx, error):
await ctx.send(embed=discord.Embed(title='hey, dont error me ๐',description=error))
@commands.Cog.listener()
async def on_message_delete(self,message):
if message.author.id == 218438244289740800:
self.message = '**cants snipe boot**'
self.author = message.author
if message.author.bot:
return
if not any([term in message.content.split() for term in self.blacklisted_stuff]):
self.message = message.content
self.author = message.author
@commands.command()
async def snipe(self,ctx):
if self.message is None: return await ctx.send('there are no deleted messages')
embed = discord.Embed()
embed = discord.Embed(title=" ",description=f"{self.message}")
embed.set_author(name=self.author.name,icon_url=self.author.avatar_url)
embed.set_thumbnail(url=self.author.avatar_url)
embed.set_footer(text=f'requested by {ctx.author.name}',icon_url=self.author.avatar_url)
await ctx.send(embed=embed)
@commands.command()
@commands.has_permissions(administrator=True)
async def blacklist(self,ctx,stuff=None):
if stuff is None: return await ctx.send('pass some shit to blacklist dude')
with open('blw.json') as fhand:
x = json.load(fhand)
with open('blw.json','w') as fhand:
x.append(stuff)
z = x
json.dump(z,fhand)
self.blacklisted_stuff = z
await ctx.send('added that word in the blacklist file')```
Dont use json as db
so whots not wroking
@commands.Cog.listener()
async def on_message_delete(self,message):
if message.author.id == 218438244289740800:
self.message = '**cants snipe boot**'
self.author = message.author
if message.author.bot:
return
if not any([term in message.content.split() for term in self.blacklisted_stuff]):
self.message = message.content
self.author = message.author``` Why you use on_message_delete not on_message
its a snipe command ?
How do I get user id from a mention?
command = kwargs.get("args")
if await author_is_mod(message.author, self.storage):
if len(command) >= 1:
if command[0]:
guild_id = str(message.guild.id)
user_id = command[0]
muted_role_id = int(self.storage.settings["guilds"][0][guild_id]["muted_role_id"])
print(user_id)
try:
print(user_id)
user = await message.guild.fetch_member(user_id)
This is what i have rn
not working
you need to get user
AttributeError: 'str' object has no attribute 'id'
Is there any way to track these invites? And like delete them or track how many users have joined?
how if i cant even fetch it
use ctx.guild.get_member(id_here)
using a database, yes
but the guy is mentioning the user
wdym
just like !mute @slate swan
I can use a json file to store data
so split <@ >
you save the invite codes and the uses in the database, when someone joins the server you check the server's invites with the ones you have in your db, and when one of them has more uses than what you have in your database, that's the invite the person joined used
sin
it can be used to store data tho ๐
thats how I store stuff lmao, cbf learning a db
and I can remove an invite?
alright thanks command[0].split("<@!")[1].rstrip(">")
still, not a database
it works tho xd
you just need an invite object and then .delete on it
np ;)
!d discord.Invite.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Revokes the instant invite.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to do this.
its very worth it though
alr ty bossman
How do you make a command tag for example when a user joins they do a !verify and then they follow the instructions? Because i want my bot to be like this
Does that make sense?
returned <coroutine object Guild.invites at 0x7ff402d17ec0>
Ok i have another problem I have an unban command but I cant unban the user AttributeError: 'str' object has no attribute 'id'
guild = bot.guilds[0]
channel = bot.get_channel(91079377950838401)
await channel.send(guild.invites())
You await it wtf dude
await guild.invites
ty
hi, i am trying to make a random discord tag generator, code so far doesn't work, nothing happens when i do command
@client.command()
async def tag(ctx):
randomtag = random.randint(1,9999)
if len(randomtag) == '1':
await ctx.send(f'#000{randomtag}')
if len(randomtag) == '2':
await ctx.send(f'#00{randomtag}')
if len(randomtag) == '3':
await ctx.send(f'#0{randomtag}')
else:
await ctx.send(f'#{randomtag}')
int doesnt work with len, how else do i do it
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
sure
??
uhhh nice
you could just do random.randint(1000, 9999)
starting from 1 does not make sense
@slate swan
Oh so you want it to include tags starting with 0 too , use >=< instead of len
how about 0001 tags
what does that do
you would need a list of roast and use random.choice
Or just use some api
Bruh ain't you aware about mathematical comparisons? I meant > , = and < by that
oh ok
i thought >=< was 1
Nah
wdym use some api lol
i will use random choice
Assuming you're aware what api is , it will return roasts without hardcoding anything , whereas the string method would require you to add strings by yourself
I c
output: ```
[<Invite code='AB5XmpEj' guild=<Guild id=910126069003190292 name='BotTesting' shard_id=None chunked=False member_count=8> online=None members=None>,
<Invite code='CvR8K2U7' guild=<Guild id=910126069003190292 name='BotTesting' shard_id=None chunked=False member_count=8> online=None members=None>,
<Invite code='xp7pUTRq' guild=<Guild id=910126069003190292 name='BotTesting' shard_id=None chunked=False member_count=8> online=None members=None>]
code: ```py
guild = bot.guilds[0]
channel = bot.get_channel(910793779508838401)
print(await guild.invites())
How am I able to create a for loop that can sort through EACH invite, and look for things inside of the guild, such as member_count?
The most basic for-loop...
for invite in invites_list:
print(invite.guild.member_count)
And of course, replace invites_list with your actual list of invites
ty
didn't know how to iterate through the guild
You don't
through the list
Basic for loop
One of the first things you learn when learning Python
If you ever did it
damn no need to roast me ๐
Just saying, an advanced knowledge of Python is kind of required for making bots
Help anyone know why i can't improt discord?
import discord
Have you installed it?
Yes
In the correct version?
Pip show discord
Name: discord
Version: 1.7.3
Summary: A mirror package for discord.py. Please install that instead.
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: UNKNOWN
Location: c:\users\yunish\appdata\local\programs\python\python39\lib\site-packages
Requires: discord.py
Required-by:
How can I have data stored in json file show in per field in one embed?
Does any one know how to make this?
pip3 install discord
Requirement already satisfied: discord in c:\users\yunish\appdata\local\programs\python\python39\lib\site-packages (1.7.3)
Requirement already satisfied: discord.py>=1.7.3 in c:\users\yunish\appdata\local\programs\python\python39\lib\site-packages (from discord) (1.7.3)
Umm so what do i do
Is my python broken
And what happens when you try to import and run the bot?
I can't import it
Just go in the cmd
And type python3 I guess
And i download it?
Download?
And what if you type python
3.9.7
But no Microsoft store?
Then type import discord after you've typed python
Nope still error
What error?
What kind of error
Traceback (most recent call last):
File "C:\Users\Yunish\PycharmProjects\discord\main.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
Ok i closed it
Import the module from the REPL
You created a virtual environment which doesn't contain discord.py in it.
Oh ok so how do make it work
When you create a project on PyCharm don't create a new virtual environment
If you notice , the folder you use for your bot is named discord
Well ig no body wants to answer me maybe ill just talk to someone in private
What
Your question?
Don't select the option at the top, select the one at the bottom
can someone help?
I wanna do this for my bot i need help doing it can i dm you?
Does that have anything to do with my discord not importing?
No
Well , do you have multiple versions of python installed?
Since it's the folder where your project is, not a folder in that project folder
That's not related to your error , but would be problematic later
I dont have a verison of python installed
Asking the user to verify them when they join a guild?
Basically yes
You would be using on_member_join event
also , it needs member intents enabled
Yes i hve all of that would i be able to dm you?
sure
wut
Idk
code:
for invites in await guild.invites():
print(invites)
print(invites.guild.member_count)
Output:
dsc.gg/abc
8
dsc.gg/bb4
8
dsc.gg/123
8```
The discord . gg part works, but the invites are stuck on 8. Anyone know why this is?
they should output 8, 0, 16
Why should the output be different
The guild member count doesn't change
There are 8 members in your guild
And not 8, then 0 and then 16 members
Oh yea winrar so what you said to do did not work any other sugestions?
Can someone help me too? I want to make a field per data stored in json but its just sending multiple embeds instead of adding fields
oh right, i'm trying to find the amount of members who have joined per link. Do you know if this is possible? I'm looking to find the 8 on there
invites.uses
!d discord.Invite.uses
How many times the invite has been used.
ty lemme read
Hi! Can anyone help me find a good reference for comparing emojis here in Discord? I'm trying to do something whenever a specific emoji is used as reaction.
You need to track it yourself if you wish to get the members
str(reaction.emoji) in the on reaction event is generally what you use
is there any way to check when a new invite has been created. Like on_member_join, but like on_create_invite. If not, I can always loop through to find new invites.
!d discord.on_invite_create
discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") is created. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.
New in version 1.3.
Note
There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/master/api.html#discord.Object "discord.Object") rather than the respective models.
This requires [`Intents.invites`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.invites "discord.Intents.invites") to be enabled.
ty
I would suggest to anyone, if you have free time just explore the docs a bit more. Not only will you learn new things but even find inspiration for additions to your bot.
^^
Discord will be releasing a new text input component soon, im pretty sure it has to do with the image I sent yesterday. Essentially a component that will allow developers to create in platform forms
Hey guys
So,
description=f"{moderator.mention}" This is my code
moderator=discord.utils.get(ctx.guild.roles, id=911791547786342461)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'moderator' is not defined
Can someone help?
Is it below or above your description?
pin this
above
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
There we go
Sure
how do you identify each emoji? Can you see my code and tell what should I do my emoji name: if str(reaction.emoji) == "flag_us":
Give me a minute
import discord
from discord.ext import commands, tasks
bot = commands.Bot(command_prefix='+')
@bot.event
async def on_ready():
print('bot in active')
await bot.change_presence(activity=discord.Streaming(name='xxx', url='xxx'))
@bot.event
async def on_member_join(member):
await member.send('Private message')
any reason why this isn't working?
error?
Paste your code and someone will help. But you would use an if Elif else statement to check
nothing happens
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
give that a good read
\:emopji:, then you can copy that into your code
Oh
Oh good catch that completely evaded me ๐คฃ
Lol
I got an error
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'mention'
hii,
how do we wait for message like on message inside a cog?
@commands.Cog.listener
Same but uses the decorator ^^
Moros, could you help?
oh thanks
?
Could u send the updated code so I can check for myself?
Ofc
@bot.command()
async def hanamiteam(ctx):
moderator = discord.utils.get(ctx.guild.roles, id=911791547786342461)
embed = discord.Embed\
(
title="***โ ๐๐๐๐๐๐ ๐๐๐๐ โ***",
description=f"{moderator.mention}\n\nโฅ x \n\n<@&{911791651926728744}>\n\nโฅ x\n\n<@&{911791801143296031}> \n\nโฅ x\n\n<@&{911791957158821888}>\n\nโฅ x \n\n<@&{911792064956596225}>\n\nโฅ x\n\n<@&{911792168161640559}> \n\nโฅ x\n\n<@&{911792284465504277}>\n\nโฅ x \n\n<@&{911792501264887838}>\n\nโฅ x\n\n <@&{911792601546502255}>\n\nโฅ x\n\n<@&{911792601546502255}>\n\nโฅ x\n\n<@&{911792737643274273}>\n\nโฅ x ",
colour=discord.Colour.purple(),
timestamp=datetime.datetime.utcnow()
alright
Hey I need help with a command in my bot. It's supposed to get the top 50 results of a leaderboard here's my current code idk how to make it send the top 50 results. ```py
@bot.command()
async def lb(ctx, *, lbname):
lb = requests.get("https://api.hyperlandsmc.net/leaderboards")
lb = lb.json()
name = lb[f'{lbname}']
await ctx.send(f'yoo this works')
could you remove id=911791547786342461
Alr
and interchange it with,
name="RoleNameHereCaseSensitive"
Alr
Should look something like this
moderator = discord.utils.get(ctx.guild.roles, name="RoleNameHereCaseSensitive")```
moderator = discord.utils.get(ctx.guild.roles, name="911791547786342461")
no the name
ye
not the role id
Oh ye ye I pasted the wrong
okay change it with name and lmk if it works
Omg, it did
cool!
I'll try, thank you really much
and making a new variable for each role would be inefficient
hey this gave an error like ths TypeError: Cog.listener expected str but received 'function' instead.
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i mean i wanted it to listen to messages only after a command is called
oh
U did @listener(on_message) instead of @listener("on_message")
could u elaborate
oh, no the listener wont work there i think
thats basically a bot.event but in a cog
yeah ๐
But I still dont understand what you want the command to do
imagine i wanted to leave u a message(not dms) so i will use this command to set a message to send to another user.
once that user send a message in chate , bot will send my message
oh
yeah then you can do what Skelmis said
oh ok i will try it
can we make watch together links from old library?
Nope
Oh wait, yes
My bad ^^^
!d discord.VoiceChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
thanks for it
so that client ? self.bot.wait for?
self,bot.wait for worked, thank you guys
hi guys, what are webhooks? are those like webview in Android?
we are humans and our preferred way to debug code is by looking at the traceback.
I think the problem is that I'm comparing list with integer
you have to show the error if you want help
webhooks can be used only in pc
or desktop site discord web
i disagree with that
webhooks can be sent using the discord api, it doesnt need bot user tokens to be sent
it can only be sent in a specific channel
well sure you could make webhooks with bot
does anyone know how to pin a message using the bot?
anyone having the webhook URL can use it, it has rate limits and you can normal messages, embeds, images, that look like a message sent by a bot, the difference is that, it doesnt have a profile because its not a bot
i tried doing pin_message but it doesn't work
!d discord.Message.pin
await pin(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Pins the message.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
Do you guys know how to delete message after let's say 5 seconds
oh ๐
await asyncio.sleep(5)
thats basic python, asyncio.sleep time.sleep or sleep
No, only asyncio
time.sleep will block the code
oh lmao
how do i make it pin a specific message
Set a delete_after=(seconds) in your .send() method
Or do message.delete(delay=(seconds))
i dont think it has that keyword, delay
!d discord.abc.Messageable.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
!d discord.Message.delete
๐
oh it does
Itโs a method. That means you use it on an instance of a class. In this case an instance of message which is how you specify the message
Trust me. Iโve done dpy long enough to know all those small things

You could also add delete_after=5
No
Doesn't have the same utility
Wanted to use purge after x seconds
At least that's what I understand
Nah, I see what you mean now
I have this code saving in my json file but whenever it saves it puts curly brackets with no information in it and under it is where it saves all the data, is there a way to remove that here is the code
with open('quotes.json','r') as f:
quotes=json.load(f)
try:
for current_user in quotes["users"]:
current_user['time'] == time
current_user['quote'].append(message)
if username != current_user['name']:
current_user['name'] = username
break
except:
quotes["users"].append({
'name':username,
'time': time,
'quote': message,
})```
I mean, I can also be wrong 
With purge, if you mean put a delay between each message, you will need to do a for loop of history and an asyncio.sleep inside
Not sure if your solution is the best because I have to wait 5 seconds to get a response
If you just wait to wait before executing the purge, put the asyncio.sleep before the purge
@broken dirge read my solutions above
Depending on what you want
i dont see any advantage of doing that
thats the data it stores and I want to remove those curly brackets on top under users
So await ctx.channel.purge(limit=2, delete_after=5) or how?
What do you exactly want to do
Discord bot sends message, waits for my response and gets input, does stuff with input and sends response. After getting input I want to delete it
Do you use wait_for to get the input of the user?
Yeah
And the message you want to delete is which one?
Mine
So just one
Well
When you use wait_for and wait for a message you get a message object in return
Then you can simply use await asyncio.sleep(x) and then await message.delete()
Yeah works just fine. But the thing is that I have to wait 5 seconds to get my response. I'd like to do it in a way that I get a response immediately and my response is deleted in 5 secs
Ofc if that's possible
I don't think it is with asyncio function
I mean
# command stuff
msg = wait_for....
# do stuff with the user response
await asyncio.sleep(x)
await msg.delete()
You will get the response instantly
Nope. It will wait until the time runs out. Then it will delete the message and send the response.
Well I don't understand what you already have and what you want. Sorry
No problem. Thanks for your help anyways.
It will still work so no worries ๐
Why am I getting this error? Messageable.send() takes from 1 to 2 positional arguments but 3 were given
send will have a positional argument defaultly
u could say it only takes one and you gave 2
Gotcha
so you could use an f-string
Oh yeah
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
cool
thanks
Oh wait. It's not going to work because I need "" In order to eliminate the gaps
then do it
Yeah, thanks
:incoming_envelope: :ok_hand: applied mute to @rotund nova until <t:1637500172:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 13 consecutive newlines in 10s).
!unmute 796343238839238677
:incoming_envelope: :ok_hand: pardoned infraction mute for @rotund nova.
Sorry long blocks of code with lots of newlines tend to trip the spam filter.
Try this:
uh, okay thanks
someone know why bot dont waiting and dont give unban?
https://paste.pythondiscord.com/joseyetomu.py
# !r command button -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def randteamchoice(ctx, message, userid):
if ctx.channel.id in allowed_channels: # and ctx.author.id in games.values():
ggid = settings.find_one({"guild_id": ctx.guild.id})
qsize = ggid["qsize"]
game_id = ggid["game_id"]
guild = ctx.guild
set_aid.add(userid)
print(len(set_aid))
if len(set_aid) == qsize / 2:
set_aid.clear()
await message.delete()
print('hell')
player_ids = games[game_id][:] -> my code just stops here
print(player_ids)
random.shuffle(player_ids)
print(player_ids)
team1 = player_ids[:qsize / 2]
print(team1)
team1_ids[game_id] = team1
team2 = player_ids[qsize / 2:]
print(team1)
team2_ids[game_id] = team2
print('hello')
Anyone know why its stopping at that line?
Its not giving any errors
if you need to use both ' and " in the string, you may use the escape characters, \", \'
where was that
sry for disturbing, just wanna ask how to delete a specific data in json file?
using a command
kevinlie do you know how to make the bot pin a message
!e
print("\"hello\" was texted by myxi.")```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
"hello" was texted by myxi.
use the del statement
await pin(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Pins the message.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
pin_message(message)```i
oh so it was tha
i guess
no
can you show me an example
message = await ctx.send('hi')
await message.pin()
oof
!e
d = dict(hi=1)
print(d)
del d["hi"]
print(d)```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
001 | {'hi': 1}
002 | {}
in your command
it doenst need the await right?
no
no
no, del does not, but message.pin does
also dont use json as a db
why
its not meant for that
there are plenty of easy databases to choose from
which are even easier than json to use
for example?
deta
Can someone help me? Whenever I try to add data in my json file it puts curly brackets automatically here is the code
with open('quote.json','r') as f:
quote =json.load(f)
try:
for current_user in quote["users"]:
if current_user['id'] == user:
current_user['quote'].append(message)
if username != current_user['name']:
current_user['name'] = username
break
except:
quote['users'].append({
'id':user,
'name':username,
'quote': message
})
saveJson(quote, "quote.json")โ
an easy solution to this would be to use a database. faster, better, easier to use
So there is no way to fix it in json?
why would you do that when you dont even need to waste time on it
Wdym
you already wasted more than 2 hours on it. which you could have spent to know the syntax of a database
or you two are different people
doing the same thing
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def join(self, ctx):
voice_channel = ctx.author.voice.channel
if ctx.author.voice is None:
await ctx.send("shemoajvi vc-shi๐ ")
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
@commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url,download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpeg0pusAudio.from_probe(url2,**FFMPEG_OPTIONS)
vc.play(source)
@commands.command()
async def pause(self,ctx):
await ctx.voice_client.pause()
await ctx.send("Paused โธ๏ธ")
@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Resumed โถ๏ธ")
def setup(client):
client.add_cog(music(client))
why am i getting invalid syntax error at the end of the code, and yes this is a cog for a music bot
Wdym
if you're really that kind of person who would forever stick with bad stuff like using json as a db, atleast use pickledb
Hey @sullen shoal how do i add a command upon which saying it teells a quote from a website
You need an API
def get_quote():
response = requests.get("SITE")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
if msg.startswith('INSPIREUSSR'):
quote = get_quote()
await message.channel.send(quote)
yea like
And don't use requests
just search it online
over 700ms latency
and this is something which you should be proud of yourself by doing it without asking for help
Tru
except there is an error
why is the above like vibrant and below not vibrant? @sullen shoal
basic intendation error, which is taught in the first lesson of every python tutorial
resolve the underlines under response and requests (and json)
๐
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
well u imported them
?? what
i imported it
so it should work now
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
from keep_alive import keep_alive
bot = commands.Bot(command_prefix = '>')
@bot.event
async def on_ready():
await bot.change_presence(status= discord.Status.idle, activity=discord.Game('Nuke Nuke'))
print("Comrade Ain't Dead")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if 'i solemnly swear that i am upto no good' in message.content.lower():
role = discord.utils.get(message.guild.roles, id=904021392998146118)
await message.author.add_roles(role)
elif 'mischief managed' in message.content.lower():
role = discord.utils.get(message.guild.roles, id=904021392998146118)
await message.author.remove_roles(role)
await bot.process_commands(message)
def get_quote():
response = requests.get("https://english.api.rakuten.net/juanroldan1989/api/moviequotes?")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
if msg.startswith('Welp'):
quote = get_quote()
await message.channel.send(quote)
@bot.command()
async def say(ctx, *, user_text):
await ctx.message.delete()
await ctx.send(user_text)
@bot.command()
async def purge(ctx, amount: int = 5):
await ctx.channel.purge(limit=amount)
correct? @vast gale
the indentation, it needs to be either not in the event, or further up, but the reason its a different color is because vscode is trying to tell you something
specifically the indentation of your code.
or the location of the definition
it would make the most sense to move get quote out of this function defintion
.
new bot.event
and anything i can do to import all of these things at once? @vast gale
no, its just a helper method
Can someone pls help im trying to use an API to get image urls. What do i use for asyncronous as module I dont want the bot to freeze by using requests. Also, how do i embed images using only urls?
API would be something like thishttps://burgers1.p.rapidapi.com/burgers
i prefer httpx.AsyncClient over aiohttp for some reasons but you can use aiohttp as well
what bout this @sullen shoal or @vast gale
like json and all of that stuff
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
what all do ya import?
for what
aiohttp is the name of the module?
like i need to import json and all that stuff now
yes
whats the * for tho?
ty
what is the stuff?
it hints, that it should only be passed as a keyword argument
@sullen shoal this is the "stuff"
i can ignore it then?
lmaoo you are also using keep_alive
its a small world
import json
json.load
json.dump
from discord.ext import commands
commands.Bot
we prefer this way
can you get this automatic command out of there? Because my bot is prefixed with "/" and if I leave it it's kind of hard to work
u can change keep alive to anything else
oo
it is not something to be ignored
ye
i meant not pass anythng other than *
def func(*, arg)...
func(arg=1)
#you cant do:
func(1)```
k ty for the help i figured it out
yees ty
Myxi would you be able to help for a second 
# !r command button -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def randteamchoice(ctx, message, userid):
if ctx.channel.id in allowed_channels: # and ctx.author.id in games.values():
ggid = settings.find_one({"guild_id": ctx.guild.id})
qsize = ggid["qsize"]
game_id = ggid["game_id"]
guild = ctx.guild
set_aid.add(userid)
print(len(set_aid))
if len(set_aid) == qsize / 2:
set_aid.clear()
await message.delete()
print('hell')
player_ids = games[game_id][:] -> my code just stops here
print(player_ids)
random.shuffle(player_ids)
print(player_ids)
team1 = player_ids[:qsize / 2]
print(team1)
team1_ids[game_id] = team1
team2 = player_ids[qsize / 2:]
print(team1)
team2_ids[game_id] = team2
print('hello')
My code is stopping in this line, but itโs not giving any errors, and I see nothing wrong with the code
i usually help when the problem is explained properly and i know to solve it
Hard to explain the problem when I donโt know what it is 
instead of print statements, you can use breakpoint it will basically stop and start a debugger session when it executes that line
it helps to debug, try to change value of certain variables and see if it works
It outputs (Pdb)
thats the debugging session
check the value of player_ids
i dont think it should stop there without any error
are you sure youre handling the errors right?
the only point it could stop working without any error would be the if statement
how do i get emojis from message.reference.resolved??
I only have per command error handlers set up
!d discord.MessageReference.resolved
The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.
Currently, this is mainly the replied to message when a user replies to a message.
New in version 1.6.
sorry thats my alt.. yeah only have per command errors set up.
And not for that command
.
It returns a Message object, so u gotta use regex
idk then, if i was you, instead of trying to debug that code i would have just coded it again
can u show a example?
Sorry, idk how to use regex, but u need to find the words which start and end with :
o wanted the bot to take the reactions the user sent and turn them into unicode. After that he would react with the same reactions in a set message... is it possible?
- using bot.wait_for
U can do \๐
ฐ๏ธ to turn an emoji to unicode
So like
i think clean_content could work
\๐ ฐ๏ธ
never tried on emojis tho
!d discord.Message.clean_content
A property that returns the content in a โcleaned upโ manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.
This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.
ye, but the bot do the samething?
Yea. Just get the name of the emojis and add backslash
hmmm, tried player_ids = [x for x in games[game_id]] and just a regular for loop
still not working
and no errors, very strange
are you trying to copy a list
and whats the value
so im transferring the values from the game_id key to a list
what is the type of value
Help this guy someone @sullen shoal @maiden fable
{72: [218993342707400704, 636493966971371530]}
so its another dict
Well no, thats the games dictionary, with the game id : player id's
How can I convert the author.name so it's all lower-case?
So
Bero would convert to bero in a Str
so the value is a list and youre trying to copy the values of the list to a new list
correct
str.lower
list has a method called copy
that will do it
right, but its in a dictionary
I was unaware you could do that from a list of values in a dict
@client.command()
async def role(ctx, role):
guild = ctx.author.guild
role1 = discord.utils.get(ctx.author.guild.roles, name= role)
if role1 not in ctx.author.roles:
await ctx.author.add_roles(role1)
await ctx.send(f'Gave Role : **{role}**.')
elif role1 in ctx.author.roles:
await ctx.author.remove_roles(role1)
await ctx.send(f'Took role : **{role}**')
elif role1 not in guild.roles:
await ctx.send('No such role exists.')``` The `elif role1 not in guild.roles` isn't working, can anyone tell me what I'm doing wrong
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'``` Error above
the value can be anything
an dict, can store any object or instance of something as a value of key
maybe even as a key
so how do I implement the copy method in that way
I get this output when I print it
<built-in method lower of str object at 0x000001F4A6F58AB0>
anyone?
!e
d = dict(k=[1,2,3])
print(d["k"].copy())```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3]
wot
don't do ctx.author.roles. Try author.roles
I see
how do i get the last message of a channel?
you can use the string method lower to turn chars of a string to lowercase
player_ids = games[game_id].copy()```
ignore what I said
the add/remove part works
i just need help with the last elif statement
should work if the value is a list or dict
still no output or errors
wtf is going on 
Why do you use elif? Just do else
same error shows up
put the entire code in a try except block like this,
try:
...
except Exception as e:
raise e```
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
Well ur checking the role by ID i don't think that works
i want to make it so that if a non existent role is entered, it would display an error message
But I'm not sure
hm
but is the guild.roles correct?
like how do i check if it even exists
still nothing
this should work for it right
guild = ctx.author.guild
if role not in guild.roles:
await ctx.send('This role does not exist.')```
then i would have coded it again
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
theres no reason it shouldnt be working though
theres more verbose bits of code there
and that is the bit that isnt working
this should work for checking if the role exists in the serrver right? @slate swan
instead of getting the role from cache, just typehint role to discord.Role. It will convert the mentioned role to a discord.Role object
but i don't want that


