#discord-bots
1 messages · Page 932 of 1
Then views make much more sense, create a class and design the game inside of the view!
Is there a way to do something like <t:129389128313> like the timestamp tht the bot can create?
Yeah, create a datetime object and format it. Have you worked with that before?
If you mean like datetime(seconds=seconds)?
Yeah, almost, but yeah.
well easier said than done 😭
is there an example you could show ?
😭 I know right 😅
and to format it does the datetime after I put it give like the 1293891823?
A quick reference for Python's strftime formatting directives.
If you have the timestamp you can do <t:TIMESTAMP:R> or something
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
print(f'<t:{dt.timestamp()}:R>')
👋 Hello!
okok
ok, how would I specify the date and minutes and seconds or the time?
!e We can run this and see btw! ```python
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
print(f'<t:{dt.timestamp()}:R>')
@minor totem :white_check_mark: Your eval job has completed with return code 0.
<t:1648246066.92453:R>
<t:1648246066>
Oops, that's a float which Discord isn't happy about!
There we go!
hm
<t:1648246066:R>
ah ok, different ways of doing it
Construct the datetime with that, dt = datetime(year=2022, month=3, hour=5) https://docs.python.org/3/library/datetime.html#datetime-objects
gotcha, tysm!
now wat is subclassing and callbacks
i assume callbacks = some kind of way to track the Button Interactions?
There's view examples here! Maybe they help? https://github.com/Rapptz/discord.py/tree/master/examples/views
The callback, gets called when you get an interaction. "callbacks" are a general programming term
!paste
i tried looking at the tic tac toe thingy but it seems a bit too complicated to me
https://paste.pythondiscord.com/ijequhewub Why when I do: .giveaway just nothing happens, getting no error. Cog is loaded so that should be fine.
you mean .Giveaway right?
just .giveaway
Okay! Look into classes a bit more and make another attempt at a later time?
welp .giveaway isnt in the aliases or the name
You can ask in a help channel or #python-discussion about classes
it's the async def
async def giveaway
Yet you pass name="Giveaway" which overwrites that!
yeah but the function name doesnt mean it gets called when you type it
Oh lol
or that actually
@junior verge you can just write it in aliases
why not have .giveaways and .Giveaways
uh no need for that I guess
why would one need a .Giveaways
whats your code again
No look: async def giveaway(self, ctx, client):. client is the missing argument
wait nvm
I defined client?
You have it in the parameters, so discord.py treates it as an argument.
Uh so what should I do then?
You need to use self.client and remove it from the function signature (this is the function signature: async def giveaway(self, ctx, client):)
oh no I just did client oops
Can I see your code now?
sure
!paste
https://paste.pythondiscord.com/upabebepiv, gonna go downstairs eat something brbn
You didn't remove client from the function signature
i call it function declaration 
Declaration would be the entire thing, the signature is the parameters part specifically
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
return
if reason is None:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
not working. Nothing output excepting 45 and 1, why?
postgresql
It's usually function signature or function head. The function declaration could also mean the entire body as well, as andy mentioned. It's not as widely used, so I wouldn't understand what you meant if you said "function declaration".
Which branch am I expected to follow? Can you tell me how you run the command, so that I know which if-statement to look at?
you do have a point

thx
At first, "Выберите участника" works if you do not specify a person and a reason, but then if you specify a person and a reason, then the first if does not work, but if you just specify a person with a reason, then the bot is silent and that's it
well, in short, 2 and 3 if do not work, but then 1 if does not work
What do you mean "the first if[-statement] does not work"? Do you want it to say "Выберите участника" if you pass a member?
no
What does "not work" means? Do you mean "not work as expected" or "not run"?
Where?
Well, like, if you do not specify a participant, then it will give an error "Укажите участника", and if you do not specify again, then the bot is silent
Okay let me try if it works
Oh, do you want the bot to ask and wait for you to send the participant?
._.
@minor totem Is there any way to apply for staff?
okay, let's do it later, why the command itself does not work, like I enter &пред @member reason it is silent
See #roles, but no. Helpers are the lowest tier of staff and there's a nomination process, you can't apply for some form. Help out around here and if they think you would be good staff you will be nominated and voted by moderators
Do you know if there's an error that happens that you don't handle? Do you have an error handler?
Ah okay, thanks.
the trial is a month right?
Everything works fine but it just doesn't send the message to react at
no...
Depends, from what I heard yes, it's usually a month after someone is nominated will the moderators discuss it.
It varies a lot. Ping me in one of the off-topic channels if you want to talk more about it
great!
Can you add a try/except like this: ```python
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
return
if reason is None:
try:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
except Exception as e:
print(repr(e))
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
@minor totem Sorry for the ping but, do you maybe got any idea?
code?
okay
Which message are you expecting to be sent?
As in, send the line of code.
Like a embed to react at
embed = discord.Embed(title="Giveaway!", description=f"{prize}", color=ctx.author.color)
# end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)
embed.add_field(name="Hosted By:", value= ctx.author.mention)
embed.add_footer(text=f"Ends {answers[1]} from now")
my_msg = await ctx.send(embed=embed)
``` that
Do you get this in your console? print('5')?
Yep
whats the problem and does it send the embed?
Just doesn't send the embed after: ```py
await ctx.send(f"The Giveaway will be in {channel.mention} and will last {answers[1]}")
5 is printed
Do you have an error handler?
I know you do, because you showed a fancy embed before, can you show it?
mhm i dont really see an issue maybe i cant find it because im on mobile or something else
I do in my main file, I'll show you.
@client.event
async def on_command_error(ctx,error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title=' Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
elif isinstance(error, commands.MissingRequiredArgument):
em = discord.Embed(title=' Error', description=f"{ctx.author.mention}, You are missing arguments.", color=0xCC1313)
await ctx.send(embed=em)
What happens if the error is none of those?
make an else statement
You need an else: that handles all other exceptions
ekls
Uh as in?
else🗿
Is that why it didn't send the embed?
Yes
Ah
I have heard a lot of devs don’t use else anymore lol
No clue what to add there though
tbh i would recommend you dont add if statements so the error handler catches all errors
Something may have gone wrong, and you'll never know
ah
Let me grab mine, hold on!
Cheers
i still do sometimes
I like the main error handler though, it works on all commands
cuz of return?
probably
I use python 3.9.10 and discord.py 1.7.3 @minor totem
its still used tho its pretty handy
Personally I just avoid it because I can handle it in otherways, I'd much rather do that than have a "ugly line"
Same with try-excepts, totally my bane of coding
Ah, here it is. So, I believe this is a variation of discord.py's built-in error handler that both sends the error and prints it: ```python
if isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, discord.HTTPException):
print(f'Unexpected HTTPException: {original}')
tb = ''.join(traceback.format_exception(
type(original), original, original.__traceback__
))
print(f'Inside command {ctx.command.qualified_name}:', file=sys.stderr)
traceback.print_tb(original.__traceback__)
print(f'{original.__class__.__name__}: {original}', file=sys.stderr)
await ctx.send(f'```py\n{tb}\n```')
mhmm
all good on the end, erm?
Here it is on paste: https://paste.pythondiscord.com/imifeyaver
I watched a video on C# object calisthenics that talked about not using else. Anyways off topic
Yes, the content formats the traceback into a codeblock which causes issues with the actual codeblock 😅
just came to my mind lol
Should that be after my elif statement?
@client.event
async def on_command_error(ctx,error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title=' Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
elif isinstance(error, commands.MissingRequiredArgument):
em = discord.Embed(title=' Error', description=f"{ctx.author.mention}, You are missing arguments.", color=0xCC1313)
await ctx.send(embed=em)
if isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, discord.HTTPException):
print(f'Unexpected HTTPException: {original}')
tb = ''.join(traceback.format_exception(
type(original), original, original.__traceback__
))
print(f'Inside command {ctx.command.qualified_name}:', file=sys.stderr)
traceback.print_tb(original.__traceback__)
print(f'{original.__class__.__name__}: {original}', file=sys.stderr)
await ctx.send(f'``py\n{tb}\n``')
``` like that
I recommend yours looking like this: https://paste.pythondiscord.com/fofujurogi
Please make sure to update the imports as well, I think your editor will tell you which ones are missing!
Ah yeah, looks better.
Yeah did already 😉
Let me see if it works
Bro those tracebacks are so usefull
In discord itself
Thank you so much
💙 did you get the issue fixed now that you can see the error?
Yeah, the giveaway works. But the reroll doesn't.
Does not give me a error either
getting this though
Oh no that's my fault. Do you see the if-statement where original is defined?
Change that to use error = error.original, then change all usages of original to error, does that make sense?
I think so
What happens is that you receive an error that isn't a command invocation, so it doesn't define original - but then it's used later in the code (because the else is run).
change these originals to error
Yes!
Aight
Here too?
k
@minor totem Since original is not accessed anymore
Yes, change it to error = error.original
It'll fix this ^, so now you can see the error on reroll
is python good for discord bot dev?
Yes
Yeah great
yes it is
very easy as well and beautiful with its syntax
@minor totem
love decos
ctx.command is None
Oh wow, I actually don't know how that happens. You can change it to ctx.command.qualified_name if ctx.command else None
Change ctx.command.qualified_command to what I sent, that way it doens't error if ctx.command is weirdly None
wait like this? huh ```py
print(f'Inside command {ctx.command.qualified_name if ctx.command else None}:', file=sys.stderr)
Yup, perfect!
Alright, let me see.
Hm?
@commands.command(name="Reroll",description="Rerolls the winner for the giveaway", aliases=["rr"])
@commands.has_permissions(administrator=True)
async def reroll(self, ctx, channel : discord.TextChannel, id_ : int):
print('8')
try:
new_msg = await channel.fetch_message(id_)
except:
await ctx.send("The id was entered incorrectly")
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
winner= random.choice(users)
await channel.send(f"Congratulations! The new winner is {winner.mention}.")
Wow I am quite interested in knowing what this error is now 😅, it has to be super odd.
Same issue as before! Yes haha
name
My bad, sorry.
@minor totem I gotta do .reroll (channel_id) right?
Just that
Yeah
Doesn't work
We getting this again
Wait
I made a mistake once again sorry
I have to include the message id as well xD
Happy you got it working then!
can someone help me with this? My bot doesnt send a welcome message when users with the default discord pfp joins, so i tried to code it to set the pfp image for them
@commands.Cog.listener()
async def on_member_join(self,member):
channel = self.bot.get_channel(933980539688460318)
responses = [f'Welcome {member.mention}. Annuit Coeptis Novus Ordo Seclorum.', f'Welcome to the Secret Society, {member.mention}!']
response = random.choice(responses)
embed=nextcord.Embed(color=0xfd9fa1, description=response)
if f"{member.avatar.url}" is None:
embed.set_thumbnail(url= 'https://discord.com/assets/f9bb9c4af2b9c32a2c5ee0014661546d.png')
embed.set_author(name=f'{member.name}', icon_url='https://discord.com/assets/f9bb9c4af2b9c32a2c5ee0014661546d.png')
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
else:
embed.set_thumbnail(url=f'{member.avatar.url}')
embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
await channel.send(embed=embed)
Is this 2.0?
client.run(token, bot=True)_CHANNEL))
^
SyntaxError: invalid syntax``` i need help anyone know how fix?
All you need is client.run(token)
i think python version is 3.6
it didnt work :/
it doesnt matter what version the discord.py is, if avatar exists it will always return Optional[Asset] , try and figure out why it returns Optional not Asset
In cases of a default avatar
shhh, you just ruined the fun
how can i make it set the default avatar then so it sends welcome messages to users with no pfp?
!d discord.User.default_avatar
property default_avatar```
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
How so?
do i code it like this?
if f"{member.avatar.url}" is None:
embed.set_thumbnail(nextcord.User.default_avatar)
embed.set_author(name=f'{member.name}', icon_url=nextcord.User.default_avatar)
The f-string is not needed here
And the thing you are passing to icon_url is wrong
You need to pass the instance attribute of the User instance
Here, it would be your member variable
You'd be accessing default_avatar through that
idk ill ask my friend bc he help me with code in the first place and dont wanna mess up really bad
No offense but your friend isn't the best source of information
please dont put others down
How is that putting someone down...?
I'm just telling them the truth
Also that's pretty hypocritical for you to say
is it like this?
embed.set_thumbnail(member.default_avatar)
embed.set_author(name=f'{member.name}', icon_url=member.default_avatar)
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
I'm literally helping him...
Why do you have the icon_url in a f-string
oh so just member.guild.icon.url?
send error?
i don't think its that
something else lemme check
ctx.guild.icon_url or member.guild.icon_url
if member.guild.icon_url is None:
embed.set_thumbnail(member.default_avatar)
embed.set_author(name=f'{member.name}', icon_url=member.default_avatar)
embed.set_footer(text=f'{member.guild}', icon_url=member.guild.icon.url)
line 22 is the if statement
What dpy version are you using?
my bad
client.run(token, bot=True)_CHANNEL))
^
SyntaxError: invalid syntax```
i mean after you do client.run(token)
File "main.py", line 91
client.run(token, bot=True)_CHANNEL))
^
SyntaxError: invalid syntax
µ§sµ§±@\¬²¬²¼³½
good job
!rule 7 thanks
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
no not this
if member.icon.url is None:
embed.set_thumbnail(member.default_avatar)
embed.set_author(name=f'{member.name}', url=member.default_avatar)
embed.set_footer(text=f'{member.guild}', url=member.icon.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
else:
embed.set_thumbnail(url=member.guild.icon.url)
embed.set_author(name=f'{member.name}', url=member.icon.url)
embed.set_footer(text=f'{member.guild}', icon_url=member.icon.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
await channel.send(embed=embed)
how do i check what version of nextcord i am using?
!rule 4
!d discord.version
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
discord.__version__```
A string representation of the version. e.g. `'1.0.0rc1'`. This is based off of [**PEP 440**](https://www.python.org/dev/peps/pep-0440).
do i put that in the shell?
No
the best version of nextcord is discord.py
bruh
if member.avatar.url is None:
embed.set_thumbnail(member.default_avatar)
embed.set_author(name=f'{member.name}', url=member.default_avatar)
embed.set_footer(text=f'{member.guild}', url=member.avatar.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
else:
embed.set_thumbnail(url=member.guild.avatar.url)
embed.set_author(name=f'{member.name}', url=member.avatar.url)
embed.set_footer(text=f'{member.guild}', avatar_url=member.avatar.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
await channel.send(embed=embed)
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
if member.avatar is None:
embed.set_thumbnail(member.default_avatar)
embed.set_author(name=f'{member.name}', url=member.default_avatar)
embed.set_footer(text=f'{member.guild}', url=member.avatar.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
else:
embed.set_thumbnail(url=member.guild.avatar.url)
embed.set_author(name=f'{member.name}', url=member.avatar.url)
embed.set_footer(text=f'{member.guild}', avatar_url=member.avatar.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
await channel.send(embed=embed)
You don't need to ask to ask
If anything, asking to ask just makes it less likely that someone will response
Just ask your question and somebody will help you if they want/can
i tried this
if member.avatar is None:
embed.set_thumbnail(url=member.default_avatar)
embed.set_author(name=f'{member.name}', url=member.default_avatar)
embed.set_footer(text=f'{member.guild}', avatar_url=member.default_avatar)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
else:
embed.set_thumbnail(url=member.guild.avatar.url)
embed.set_author(name=f'{member.name}', url=member.avatar.url)
embed.set_footer(text=f'{member.guild}', avatar_url=member.avatar.url)
embed.timestamp=datetime.datetime.utcnow()
channel=self.bot.get_channel(933980539688460318)
await channel.send(embed=embed)
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
I posted it in #help-cherries, should i paste it here too?
I'll visit the help channel
omg that fixed it, TYSM IVE BEEN STRUGGLING WITH THIS ISSUE FOR SO LONG 




same
OH HIIIII HAHAHAHA
lol hey
how do i make my bot post a message every hour?
use the tasks extension
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
thanks
why doesn't this work properly i don't get the error code sadly
Where are you starting the task?
i thought it started auto ok let put that in an on ready
wait hold on nvm
can the loop be ran and also be a command? so i can run it anytime doesn't matter if it posts in the channel i have it looping in
sure, you just have your command and loop use the same code, usually with a function
I keep getting the error
TypeErro: 'in <string>' requires string as left hand operand, not list
The list
list = []
yo i need some help, im getting TypeError: 'in <string>' requires string as left operand, not list
its not allowing me to send images
if list in msg:
list includes list = ["test", "test2"]
list = ["test", "test2"]
client = nextcord.Client(prefix=PREFIX, case_insensitive=False)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
msg = message.content.lower()
if message.author == client.user:
return
if list in msg:
await message.delete()
await message.channel.send(f"{message.author.mention}, you cannot say that here!")
idk how i got it to work earlier, but it was working earlier and i guess i forgot to save haha
because youre trying to do this if list in message
it should be if message in list
if list is in message then do this
is that not correct? if not can you explain how to correct it
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
!e
if "20" in ["20", "2"]: print("yup")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
yup
bro
i already gaved you the answer?
since message.content returns a string just check if the string is in the given list
explain because i tried @commands.command()
@tasks.loop(seconds=3600.0)
i got it working, turns out i wasnt turning anything lower and it just didnt recognize it
thats not the error.
well idk what i did but its working now
i just changed my event to this
@client.event
async def on_message(message):
triggerWords = ("test", "test2", "test3")
if message.author == client.user:
return
if any(triggerWords in message.content.lower() for triggerWords in triggerWords):
await message.delete()
await message.channel.send(f"{message.author.mention}, you cannot say that here!")
it works exactly like i want it to so
what are you trying to get done here?
make it where if the trigger word is ANYWHERE in the message, it does something
but i already fixed it
its working now
Oh alright
like if you say "words words test" itll delete the message
and if you say "test" itll delete the message
yk an automod thing im making
Ye I understand, i made an auto support bot for one of my clients
i hope nextcord is fine here since its a fork of discord.py lmao
if youre gonna make a filter use regex
ok good
Ñ
uhh not by stacking the decorator, by having a common function and both a command and a task that calls that function
how can i see if a id is in json file with a command?
json_data = ...
if str(ctx.author.id) in json_data:
...
ahhh the edit aint workng pfftt
@Client.command()
async def checkblacklist(ctx):
json_data = Client.Blacklisted
if str(ctx.author.id) in json_data:
await ctx.send('Denne person er blacklistet.')
if str(ctx.author.id) not in json_data:
await ctx.send('Denne person er ikke blacklistet.')```
I tried, but this ain't working
Whats Client.Blacklisted?
its my blacklisted
Hello
yk, blacklist people from the bot
i speak spanish
Well yeah obviously but what is it
A dictionary
Is it a dict?
why not use the on_command event and make one global check.....
What isn't working? Any errors?
The code doesn't look wrong so i'm asking what's the json_data
the id is clearly an int
🗿
Do json_data["Blacklisted"]
the if statement is always false as youre trying to do
if 1 == "1":
...
Why is there blacklisted inside your json file
That's not needed since you're checking whether or not they're in the json file
xd
Assuming you loaded that file into client.blacklisted, you can access a list of all blacklisted users using client.blacklisted["blacklisted"]
it is still not sending anything
Discord died on me
when javascript
No?
make sure you are invoking the command correctly 
example, and hes trying to look for an id thats a str lol

yeah
json doesn't allow integers as keys
{
"1234567875432": "uwu"
}
thats how data is stored in json 
just an example, we dont talk about arrays and nested objects 
bruh
Or you know... just don't use json as a database, sql lets you use integers as primary keys
json isnt always about database 
"as a database"

Unfortunately many here seem to think it is
A lot of people who help tell others to not use json
now a lot of people hate json for no reason
That's polarized. knowing the use case of json is very important
right
yeah use a .txt file

!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
#bot-commands
oh sorry


Thank you that helped me understand how it should go
Anyone knows?
nope
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
Why is this not working?
try ```py
CODE = "{'embed = disnake.Embed(title=title, description=description, timestamp=timestamp'}"
import("os").system(f"python -m black --code {CODE}")
Any errors?
Nvm the user I was kicking had higher role than the bot
Hmmmm that pretty much looks like what i had before but it was expecting a path
Don't mean to interrupt, if anyone gets a moment.
I've been using requests to requests data and I've began to realize it's too slow.
Is there a library that's most similar that I could use?
aiohttp
!pypi aiohttp
requests is synchronous but discord.py is asynchronous, thus requests will be blocking in an asynchronous context
Kayle do you know if the --code flag expects a path?
Okay, got it. I tried to incorporate it into one of my commands, couldn't figure it out. I checked a few vids and still can't figure it out, do you mind if I post a command and you show me how it integrates into it?
nope, you could try googling it though
Yeah just post relevant parts of code
Okay, got it.
I have that works fine for requests and it's fairly short.
How to make the bot reply that the user has been banned
sure ```py
import aiohttp
async def command(ctx):
async with aiohttp.ClientSession() as session:
data = await session.get(URL) # or .post, .put etc
You can also check this it should have examples

@client.slash_command(guild_ids=guild_ids)
async def profile(interaction : Interaction, battle_net):
await interaction.response.defer()
response = requests.get(f"https://overwatch-api.tekrop.fr/player/{battle_net}/info").json()
#pprint(response)
valueA = "`(Username: " + str(response["username"]) + ")`" + "\n"
embed = nextcord.Embed(description=valueA, color=15277667)
await interaction.followup.send(embed=embed)
Okay, I'll try to use that
I also cut out parts of the code, so to make it shorter
Well I'm not sure if a member profile update event shows you that
If it doesn't your best bet would be to check every X minutes, say 5, to see if someone has linked github to their profile
@client.slash_command(guild_ids=guild_ids)
async def test(interaction : Interaction, battle_net):
async with aiohttp.ClientSession() as session:
response = await session.get(f"https://overwatch-api.tekrop.fr/player/{battle_net}/info")
Like so?
yes
in a .env file, are multiple environment variables comma separated?
no
bots cant access a users connections
Okay, I'm normally used to adding the .json() at the end, when I do it for AIOHTTP, it doesn't "color" - does it work like that still on the URL?
no
token = ...
test = ...
okay so I'm not sure why it doesn't work maybe it can only be done in terminal or something
its not highlighted? you probably need to await it since its a coroutine
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
How can I make bot respond with a text that member is banned/kicked?
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
Ty
could be done shorter
@client.slash_command(guild_ids=guild_ids)
async def test(interaction : Interaction, battle_net):
async with aiohttp.ClientSession() as session:
response = await session.get(f"https://overwatch-api.tekrop.fr/player/{battle_net}/info").json()
print(response)```
This is the test command I added, this is my first time using `aiohttp` so just trying to understand it some.
I've used requests since I started coding (2 weeks ago) so It's kinda just stuck with me.
Usually, you can type `requests.get(url).json()`
What have I done wrong in my current one? If you can show me.
youre probably only awaiting the request and not the json coroutine
https://overwatch-api.tekrop.fr/player/CameronBryce-11490/info
That's the info I am trying to get, if that helps.
response = await (await session.get(f"https://overwatch-api.tekrop.fr/player/{battle_net}/info")).json()
print(response)
```try this
well requests was probably blocking something
So, for the response you gave me, would that be the way I should use to get a .json 99% of the time? From an API
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
if the api formats there data with json that is so.
Okay, got it.
The issue I was having before is someone told me there was "x" amount of time for me to get a response, or I get an error.
So, they said to add a "follow-up" interaction at the bottom.
I added the command you said into it and put it back to a regular response, it's still not fast enough, I'm not sure what to do or what I might be doing wrong
Not follow up, they must have told defer()
Oh, it was that, they just said to add both
And do either of you mind checking the code?
It works 100%, it just takes too much time otherwise as a regular command, it's only like 6-8 lines in the actual .json
Here's a tag - CameronBryce-11490 for the battle_net
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
That's the error
https://overwatch-api.tekrop.fr/player/CameronBryce-11490/info
15277667 what is this color value?
this could be because the code is taking over 3 seconds
Mhm, that's what they said.
Would there be a fix or is it just an issue with the endpoint?
It's only like 5-6 lines, not sure why it would take so long to go through
yes
its an issue with discord
Okay, I'll probably just go back to doing that for that endpoint.
Thank you pplz for showing me how to use the aiohttp though, I appreciate the help
not "you can", you have to
!d disnake.InteractionResponse.defer
await defer(*, ephemeral=False, with_message=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
without defer you have 3 seconds to respond to the interaction but with defer you have 15 minutes
Mhm, I came here wondering if there was a way around that, I was just saying I'll just suck it up and stick with the defer lol
after doing that, just do
await interaction.edit_original_message(content=..., embed=...) everything is a kwarg in this
thats the best one
Would there be a way to shorten the time?
it wont
Like, if someone types something in wrong
What can I do for it to respond?
make it faster in the sense.
?
use a proper event
!d discord.on_member_remove
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Wait why is this called when a member joins
Oh in that it's talking about the join event also
Sorry, I mean like this
Let's say someone typed in something wrong, would there be a way for it to immediately cancel sooner?
So it's not "thinking" for 15m
So, how would I get it to go away then?
Sorry, this is new to me.
Also this has a with_message kwarg
It goes when the code is complete
Well, for example I typed a profile name in wrong, it's still going on, for the last 3-4m.
Would you have to wait for 15m fully?
Are you getting any error,
Nope, just nothing comes back at all.
It keeps running when you enter a false profile
Ahh, I figured it out, nvm. Thank you
Can I ban my bot from every single server without being in them?
or altleast know in which all servers my bot is on?!
oh no
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
@slate swan
If there are four buttons A,B,C and D, how do I know what button has been pressed. Please send an example cuz my brain is kinda fried
Well each button is a function.
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
There are a lot of examples already inside the master.
like if I use py async def
in a codeblock the output is pyasync def
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
Anyone knows why this is not working?
if message.content == f"<@{client.user.id}>":
await message.channel.send("Hello", reference = message)
The bot does not send the text when mentioned.
await message.reply("")
i had a really simple q, how do i make a command that works only for those roles that have specific perms, like ban works only with ban members permission
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
thankyou
is there any list that indicates how all permissions can be used in the above function?
like
kick_members
ban_members
and so on..
yeah
thanks
!d commands
commands [bpnumber]```
Specify a list of commands for breakpoint number *bpnumber*. The commands themselves appear on the following lines. Type a line containing just `end` to terminate the commands. An example:
```py
(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)
``` To remove all commands from a breakpoint, type `commands` and follow it immediately with `end`; that is, give no commands.
With no *bpnumber* argument, `commands` refers to the last breakpoint set...
!d pip install discord
hi
make it an f-string
f"User {member} blabla"
and you don't need to create a variable
Ok
just await ctx.send(discord.Embed(...))
Ty
Alr
Use a library to connect to the discord API
!pypi discord
A mirror package for discord.py. Please install that instead.
!pypi discord.py
can u use replit??
Yes if you're not going to use replit to host it for a long period
plz help me to make bot
i know how to host 24/7
Do you know basic python
no 😢
like a basic bot with fun cmds
can we talk in dms??
hlo?
It's not recommended trying to tackle making a discord bot without having any basic python knowledge
can u just give me code
You'll get stuck easily at problems which you could of avoided if you knew basic python
We don't give out code
We help people with their problems
We help them through it
Damn
!cban 950994265377480705 nsfw
:incoming_envelope: :ok_hand: applied ban to @celest grove permanently.
According to the API, your request is malformed.
1 min and 1 sec for mods to respond
please don't ping admins unless the server is broken. Most admins have the moderators role, so we'll be pinged anyway.
Oh, ok
Thanks
Tysm
how do i print "you are missing {perms} permissions"
How can I add this
embed.set_author(name="vcokltfre", icon_url="https://avatars.githubusercontent.com/u/16879430")
Here:
heyo
!pypi aiohttp
Wow
sometimes my commands bring up specific errors I have made, and sometimes they just bring up a check error
I have an 'unregistered' error and a decorator that I have on some of my commands. But some of those commands don't bring up that error and some do.
How can I add this
embed.set_author(name="vcokltfre", icon_url="https://avatars.githubusercontent.com/u/16879430")
Here?
Guys, I want to make my discord bot wait for user reply, what do i do?
Because this isnt working https://cdn.discordapp.com/attachments/954336187085127711/956838574546898954/unknown.png
Why am i buttons not being send?
Show code
@Client.command()
async def button(ctx):
await ctx.send(
"",
components = [
Button(style=ButtonStyle.red, label = 'test!')
]
)
interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
await interaction.respond(content="test")```
Sorry i dont use these type of buttons
i have a very nice calculator with buttons but its not sending :(
Fellow
user
ye, and its a bit annoying its not sending
okay, thanks man
@slate swan i ghost ping u by mistake
xD
Hi have anyone tried this: https://support.discord.com/hc/en-us/community/posts/1500000729481-Multiple-pics-embed-suggestion
If yes, how can i send the raw data via discord.py
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Hi guys, I'm making a simple discord bot using discord.py but I cant use commands alongside with events, I have tried adding await bot.process_commands(message) but its not working either, can anyone help?
What's your code?
from datetime import datetime
import pytz
from datetime import date
from discord.ext import commands
bot = discord.Client()
prefix="??"
bot = commands.Bot(command_prefix = prefix)
my_time = datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).time()
my_date = date.today()
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("hello"):
await message.channel.send("hi")
if message.author == bot.user:
return
if message.content.startswith("timern"):
await message.channel.send("Bây giờ là " + str(my_time))
await bot.process_commands(message)
@commands.command()
async def datern(ctx):
await ctx.send("cc")
bot.run(token)```
!code
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.
Hm I have to add py
import discord
from datetime import datetime
import pytz
from datetime import date
from discord.ext import commands
bot = discord.Client()
prefix="??"
bot = commands.Bot(command_prefix = prefix)
my_time = datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).time()
my_date = date.today()
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("hello"):
await message.channel.send("hi")
if message.author == bot.user:
return
if message.content.startswith("timern"):
await message.channel.send("Bây giờ là " + str(my_time))
await bot.process_commands(message)
@commands.command()
async def datern(ctx):
await ctx.send("cc")
bot.run(token)```
Whydo you have 2 bot instances?
I thought I would need to add the client and the command thing
Also why are you using the @commands.command() decorator
That's for when you're in a cog
Oh
Thanks
No
You only need the commands.Bot instance since that inherits discord.Client
Oh
What i am wrong nee help !!!
Wow it works now, thanks
What's at line 11 in the extension you're loading?
Cog
It's def
Yours is deF
Just change the F to an uncapitalized one
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
A feature of objects is that an object's own procedures can access and often modify th...
this ??
that's not gonna explain
mean can't find the file ??
is it from a third party library?
wdym?
can't find raw_to_dict this file
so what i do now?
put back the file (raw_to_dict ) location in your code
i guess
i am new too
any good json tutorial website pls?
I suggest you watch tutorial videos on yt
ok
Someone who can help, how to do a giveaway bot with invite require ment?
stop using bold text for no reason
ok
What i am wrong
u already have a ping command
so i need to del this ?
delete one of them
done thx
np
:)
!d async
and what is ctx
how would I run a while loop while waiting for a response to a message?
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
thank you
I want to run code and at the same time have bot.wait_for still going
how i can make inventory command using sqlite database?
i want it to be like:
123... | name of | current
| item player | amount of
| has been | item player
| obtain | have```
👋
Are there any tutorials for making ticket system?
!paste
Lol
Hiya, so I gots a few issues
@commands.slash_command()
async def animals(self, inter, animal: AnimalsOptRand):
if animal == "random":
animal = random.choice(AnimalsOpt)
print(animal)
if animal == "duck":
async with aiohttp.ClientSession() as session:
async with session.get("https://random-d.uk/api/v2/random") as resp:
data = json.loads(await resp.text())
duckEmbed = disnake.Embed(
title = "Duck!"
).set_image(
url = data['url']
).set_footer(
text = "Powered by Random Duck")
await inter.response.send_message(embed = duckEmbed)
elif animal == "fox":
async with aiohttp.ClientSession() as session:
async with session.get("https://randomfox.ca/floof") as resp:
data = json.loads(await resp.text())
foxEmbed = disnake.Embed(
title = "Fox!"
).set_image(
url = data['image']
).set_footer(
text = "Powered by Random Fox")
await inter.response.send_message(embed = foxEmbed)
This doesn't work, I get a KeyError
Anyone know why?
| Python Version: 3.10.2
Ignoring exception in slash command 'animals':
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 597, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/params.py", line 778, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/utils.py", line 561, in maybe_coroutine
return await value
File "/storage/emulated/0/coding/discord-bots-repo/disarray/commands/animals.py", line 43, in animals
animal = random.choice(AnimalsOpt)
File "/data/data/com.termux/files/usr/lib/python3.10/random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
File "/data/data/com.termux/files/usr/lib/python3.10/enum.py", line 440, in __getitem__
return cls._member_map_[name]
KeyError: 4
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1332, in process_application_commands
await app_command.invoke(interaction)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 606, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 4
I am trying to code an event that deletes a channel in a specific category every 30mins
can someone help me, I don't know how to start it
Whats the problem here? https://cdn.drijon.tk/chrome_wbqQywsIKT.png
an event?
use tasks instead
alright, how would I do that
!d discord.ext.tasks.loop read this first
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
how do i get the contents of a discord.File as a str?
confused
click the link
yes I did
did you read it?
oh my
import tasks from discord.ext
use @commands.Cog.listener() first of all, you've missed the paranthesis
from disnake.ext import commands, tasks```
yes
now use tasks
no, use it as a decorator

Decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
• Corey Schafer's video on decorators
• Real python article
@boreal ravine also can you help me with this?
how would I use the task as a decorator
I should put it in ()
No
@tasks.loop(...)
async def loop():
...
https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html click this link, theres an example on tasks
it starts with @ so it's a decorator
oh wait
have you done from disnake.ext import tasks?
then use the decorator how kayle showed above.
get the category object -> get the channel -> .delete() it
alright
I'm running an async function as a task and I want to yield a result from it every time it loops so that I can update another function
why category object?
How would I yield it without 'yielding' it, because it won't let me create tasks out of generator objects
they said they wanted to delete a channel inside a specific category earlier
Why are you awaiting a property
what do you mean
to get the category
thats not how you get a category
oh
!d discord.ext.commands.Bot.get_channel this is how to get a category
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
thats for channels
A category is a channel
help? im trying to make a slash command but it gives me this error when syncing the commands
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py:416> exception=Forbidden('403 Forbidden (error code: 50001): Missing Access')>
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 440, in sync_all_commands
existing_cmds = await self.req.get_all_commands(guild_id=scope)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 332, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Does your bot have the application.commands scope?
No, it's a method so call it and pass in a valid category ID
yes
but thats gonna delete the category
oh
ok, How do I make it delete a specific channel maybe a unique name like (#BattBattling) only in the Closed Category
i forgot about that but theres another error
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py:416> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn name: String value did not match validation regex.')>
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 492, in sync_all_commands
raise ex
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 472, in sync_all_commands
existing_cmds = await self.req.put_slash_commands(
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 338, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: String value did not match validation regex.
what causes this error?
channel = discord.utils.find(lambda channel: channel.name.lower() == "battbattling", guild.channels)
await channel.delete()
at this point idk, try asking in d.py server
self.guild.channels?
because guild is not defined
does your class have that attribute? if so yes
yes it does
use that then ig
its alright 
the iterable comes as the first positional argument
what?
explain in a simpler term please
oh then how would I uh
oh nvm
?
Are you searching for text channels only or not
yes text channels only
Because if so, you could use discord.utils.get cause there's no need to lower the channel name, as they are always lowercased
Knock knock
Who's there?
channel = discord.utils.get(guild.text_channels, name="kayle")```
For example
channel = guild.get_channel(channel id here)
alright, so If I want multiple users and make another channel but with different name
Wut if there is 2 channels with the same name?
The best method
Yes
It will get the first one
isnt it guild.get_channel?
Oh ic
Yes sry
Anyways it is much better to get the channel by its ID
Yea
yes it is but there will be different channels with the same name
Ye that would work too
Do
channel = guild.get_channel(channel id here)
no, the id is going to be different
I want it to delete any channel with the name battbattling
no just one
Oh then just use a for loop
Bro what you want? Tell me problem I will tell if I know?
for channel in guild.text_channels:
if channel.name == "battbattling":
await channel.delete()```
how can I contain multiple channel names
It will work even if there are multiple channels with that name
I will tell a easy code
channel.name in (names_tuple)
you should specify the channel
Oh so u want to make it like a logs channel or something?
yes
so when someone renames the channel to #battbattling it will delete then log it somewhere
battbattling - 1
@client.command()
async def delete(ctx, channel=ctx.message.channel):
for c in channel:
try:
await c.delete()
except:
print(f"{c} deleted")
no, its not supposed to be a command
Then?
No thats a invalid syntax
Why?
it will automatically delete
Oh
It should just be channel and when u call the function u name the value
And except works only with try 
Oh wait u got try mb
did what?
delete_channel=[
"Channel name here"
]
await delete_channel.delete()
But look that is going to be a problem when u make a logs channel because there is a function like on_member_ban(member) and u will try to send this to the logs but this function only excepts one argument you will need guild to get the channel name
@tasks.loop(seconds = 5)
async def loop(self):
names_tuple = "batt-done"
for channel in self.guild.text_channels:
if channel.name in (names_tuple):
await channel.delete()```
wasn't deleted
o
How to get membercount?
Yea what you want
get the membercount, just .membercount will return the members in the server like 10
ctx.guild.member_count```
@clientt.command(name='membercount')
async def membercount(ctx):
await ctx.send(len(guild.member_count))
try this code bro
sure chill
Or
ctx.guild
@client.command(name='membercount')
async def membercount(ctx):
await ctx.send(ctx.guild.member_count)
ty\
@tasks.loop(seconds = 5)
async def loop(self):
delete_channel=[
"batt-done",
"sun-done"
]
await delete_channel.delete()```
the channel is still there
Yea
I got idea wait
channel = "name of channel"
for c in channl:
try:
await c.delet()
except:
print("{c} deleted")
Bro why are you taking Len of number of guild members
This guy said that
Thank You so much
@commands.command(name='membercount', description="Returns a number of people in the server", aliases=['mc'])
async def membercount(self, ctx):
await ctx.send(len(ctx.guild.member_count))
its just ctx.guild.member_count
That's too easy
alright
@stuck oyster
Who said that lol
It will print channel deleted when it was failed to delete
Did you make a typo or smth
nothing there makes sense
And yeah that looks weird
else:
print(f"{c} not deleted")
First str.delete wtf
!d discord.TextChannel.history guess you wanna loop through this?
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
Why are you iterating the string
What are you even trying to do
@vale wing can't understand

!e py channel = "nice name" for c in channel: print(c)
@vale wing :white_check_mark: Your eval job has completed with return code 0.
001 | n
002 | i
003 | c
004 | e
005 |
006 | n
007 | a
008 | m
009 | e
!e
channel = "name of channel"
for c in channl:
try:
await c.delet()
except:
print("{c} deleted")
@thorn ore :x: Your eval job has completed with return code 1.
001 | File "<string>", line 6
002 | except:
003 | ^
004 | IndentationError: unindent does not match any outer indentation level
and you made some typos
@client.command()
async def deleteChannel(ctx, channel: discord.TextChannel):
try:
await channel.delete()
await ctx.send("Successfully deleted the channel!")
except:
pass
me?
your computer is screaming of errors
It's not command it's loop
what even is the point of for c in channel
maybe he wanted to delete the messages
You mean channel is supposed to be a list?
in that specific channel
Maybe he meant delete all channels 😳
Yea when a channel is name "test" the bot should automatically delete channel
and we would be helping to make a nuke bot
I have already made that thing
That's simple list iteration lol
S
@thorn ore this is something similar to what you mean
@tasks.loop(seconds = 5)
async def loop(self):
delete_channel=[
"batt-done",
"sun-done"
]
for t in delete_channel:
await bot.delete_channel(t)
idk if this really works but give it a try
K
nah
You typically do it like TextChannel.delete()
that's not it anymore
@tasks.loop(seconds = 5)
async def loop(self):
delete_channel=[
"batt-done",
"sun-done"
]
for t in delete_channel:
channel = discord.utils.get(guild.text_channels, name=t)
await channel.delete()
hm
This is the most correct way to delete a channel with specific name, if there are several specific names just use in condition
probably sure this will work
It will do len(delete_channel) iterations as get iterates through all channels, so it is worse
That's what I did
Why won't they just look at that lol
@tasks.loop(seconds = 5)
async def loop(self):
for channel in self.guild.text_channels:
if channel.name == "batt-done":
await channel.delete()```
didn't work with `batt-done`
@tasks.loop(seconds=5)
async def loop():
guild = bot.get_guild(Id)
channel = discord.utils.get(guild.channels, name="batt-done")
await channel.delete()
Omg
what's self.guild?
What is the Problem here
to get the guild
guild isnt defined so I need to add self
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Bad indents
i have never really used tasks .loop do the functions need to be called or are they running every X seconds?
Probably you did something like
if condition:
try:
...
except: < issue is here
...```
Every X seconds after calling loop_func.start()
yes
oh okay
cause I won't be there to delete the channels
Just use the method I suggested lol no need for such loop
I think a tasks.loop would be better in this case for an async environment
How can i fix it?
What IDE are you using?
Looks like repl.it
repl.it premium
Not really. discord.utils.get iterates through the iterable given as a first argument and fetches first matching instance using the for loop. So why don't we make the for loop ourselves to delete all channels with matching name at once?
No they want to delete as soon as it's named ___
Um doesn't it highlight problems
As far as I remember replot does highlight indent errors as red lines
Ehm what do i do here
It is highlighted alright
def setup no indent
The content of that function should be indented
Also you don't put that function into the cog
It should be in the file but not in the cog
@tasks.loop(seconds = 5)
async def loop(self):
for channel in self.guild.text_channels:
if channel.name == "batt-done":
await channel.delete()```



