#discord-bots
1 messages Β· Page 82 of 1
decide if you want to store it in bots memory (not recommended)
in some form of file, such as json
or as a database (recommended if it's a lot.)
So storing it in a database or in a json file means that if the bot goes offline it's fine. it wont erase anything.
but using the bots memory, will mean if the bot goes offline, it's all gone
So I make an folder with database
it's up to you how you want your file structure to be
Whatβs the easiest
Β―_(γ)_/Β―
And what have I to code
you'll need to learn how to use python first.
Python is easy
Online. Do some free online courses. Watch some tutorials.
@maiden chasm freecodecamp?
"Developer" Rick,
Man actually using "Developer" in his username
π π π
and?
i wanna learn it
I think they're trying to imply that you shouldn't put "Developer" in your name if you're not a developer yet
But imo there is nothing wrong with that, besides people probably gonna dm u for some requests
I just find it weird, using "Developer" in your name when 99% of the people in this server have more knowledge than you
While I agree @slate swan, for now, try and keep it civil.
yeah ok
wdym
Im just letting him know
i know
Just leave him alone? xD
If you really want to learn python, just watch that 10h tutorial, then visit some websites, do the boring stuff, it will probably take like a week if you give it 1 hour every day, learn packages, pyinstaller, pyqt5, requests, after you learn all this, you will have "basic" knowledge of python, so you can start creating discord bots using pycord π
!resources to learn python :good:
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
nonono not pycord pls
that is a variant
π€’
Tbh pycord has a nicer slash command API than discord.py
yes
At the end of the day, you're all wrong.
thanks
π
at least use disnake then
discord.js is where it's at
yeah i agree
Not looking at using other wrappers anyway, making my own
but js is advanced
is it tho?
you can do more stuff with python
I know some pretty stupid people.. and they manage to use it
like overall

oh my gosh im late to my chess torunament
bye guys, good luck at deciding which wrapper is the best
but tampermonkey is insane extension for js
you're not late. that's just a terrible excuse to leave.
i am
Prove it. Send me the competition results when you win.
No. That'd risk doxxing him and idk who he is and nor do i want to
i can send you the page of the tournament, it's russian tho
don't give the introvert a hard time
Don't make yourself more late!
true
Code:
balem=discord.Embed(description=f"**{user.mention}'s balance**", color=discord.Color.blue())
balem.add_field(name="Cash:", value=f"{result[1]}", inline=False) #line 46
balem.add_field(name="crystals:", value=f"{result[2]}", inline=False)
balem.add_field(name="event pearls:", value=f"{result[3]}", inline=False)
balem.add_field(name="weapon shards:", value=f"{result[4]}", inline=False)
balem.add_field(name="fusion earring:", value=f"{result[5]}", inline=False)
balem.add_field(name="merging stones:", value=f"{result[6]}", inline=False)
balem.add_field(name="enhancing stones:", value=f"{result[7]}", inline=False)
Error:
line 46, in balance
balem.add_field(name="Cash:", value=f"{result[1]}", inline=False)
TypeError: 'module' object is not subscriptable```
doxxing? I didnt know that you can find someones full name, home adress, phone numbers, just by seeing him on a livestream thats not even shared anywhere ?
Have you ever heard about for loop
what the hell is this code
People have found flags hidden around the world from a single picture of a cloud. dont underestimate the internet
ok
ye
Unless they have their biometrical data leaked
who would need me?
π
im just a 13 y/o who plays chess and knows quite more in maths then his classmates
If I found your address I'd send you a book on scientology.
I've done it before and I'll do it again
no thanks
dont underestimate my stupidity with money
Then why don't you use it
ok ima go now, bye
glhf
Bye
kk
idk
Why would they need to double a word
I just got used to it
Just put a single key
k
Atm machine
Nice
rest in rip peace
kkk
I mean nπ§
and finally, okay k?
kkay
He's trying to type semicolons
yo
i got blocking code, heres my attempt at solving it
https://paste.pythondiscord.com/inihodevoz
function originally is:
https://paste.pythondiscord.com/isuqapidiy
im not sure if its correct, documentation i used:
-https://stackoverflow.com/questions/65881761/discord-gateway-warning-shard-id-none-heartbeat-blocked-for-more-than-10-second
-https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor
-https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
the website link it's working in that part but idk how the body thing works.
like this? idk how to use it```py
def to_thread(func: typing.Callable) -> typing.Coroutine:
@functools.wraps(func)
async def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
wrapped = functools.partial(func, *args, **kwargs)
return await loop.run_in_executor(None, wrapper)
return wrapper
@to_thread
def blocking_func(a, b, c=1):
time.sleep(a + b + c)
return "some stuff"
await blocking_func(1, 2, 3)
What wrapper are you currently using
@drifting arrow how can i run the programm in visual
uhh. why are u asking here anyway?
cause its a discord bot command doing this
@faint sapphire what db wrapper are you currently using
Look it up. if you want to be a developer, sometimes you'll have to google this stuff yourself.
k
idk what u mean,
thats my attempt: https://paste.pythondiscord.com/inihodevoz
and i use sqlite3
!pypi aiosqlite just use this
ok thanks
@maiden chasm - Your first actions should always to attempt to solve the issue yourself. Google some things. Try solutions you find.
Then after it all fails, ask.
sorry
In the workplace you wont be able to constantly run to your colleagues to answer these things.
inb4 someone contradicts me.
So I get this error randomly when issuing commands, why?```py
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/bot.py", line 997, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 359, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientOSError: [Errno 104] Connection reset by peer
uh @vale wing could u give me an example of how I could possibly use for loops for my code
I'm a beginner so I need some help...
You might be doing something wrong in the command?
for i in [1, 2, 3]:
print(i)
1, 2, 3
names = ("Gold", "Silver", "Copper")
for i, name in enumerate(names):
embed.add_field(name=name, value=res[i])```
Yeah, but the command only gives this error about 25-50% of the time
Amazing
url = f"myurl"
async with aiohttp.ClientSession() as session:
async with session.post(url,json=myobj, headers=headers) as r:
response = await r.json()
print(json.dumps(response, indent=4))
anyone know how to fix this? ive tried making a global variable but then i get multiple not defined errors
in your classes init, assign "self.db = db" or whatever the global is called.
then reference self.db
There are other ways but that's how I'd do it
since i'm currently using slashcommands
where do i put the like the names ( username ) ( account id )
JSON is just a dictionary that wants to be on its own.
So create the dictionary as you would the json file.
and yeet that dictionary as a json
mydictionary = {
"name": "Gnomeslayer",
"Password": "Password1234",
"email": "Gnome.Slayer@Fake.email.org"
}
url = "my url goes here"
response = ''
async with aiohttp.ClientSession() as session:
async with session.post(url, json=mydictionary) as r:
response = r.json()
print(json.dumps(response, indent=4))
thnx
thnx
aaaaaaahh okay
ty
cursor is not defined
Β―_(γ)_/Β―
I just read your error message and it says cursor is not defined
and that's where I'd start
In your code @slate swan, you're trying to call it, however it is not defined to begin with.
So the part of your code that defines it, needs to yeet it to the parent class and then the function can reference it
idk
based on your code, you're using buttons call the next database object.
But the code itself has no idea what a database is. or what the cursor is.
Yes you need to acquire a cursor first
oh ur the same guy from earlier
with the buttons issue!
remember how I showed you to pass the message object through to the classes for the buttons?
tomorrows me is gonna wake up and see all my random code scattered about the place
and is gonna be like "dafuq was yesterdays me doing?"
def __init__(self):
super().__init__(timeout=None)
self.message = ''
self.mydatabase = ''
``` and just update that variable.
or whatever.
why would you create a pool inside a button callback?
that's something which should go into the setup_hook
move to discord.py
ew
well, you could still create a setup_hook-like function in py-cord
async def setup_hook() -> None:
...
async def main() -> None:
await bot.login(...)
await setup_hook()
await bot.connect()
#or you can use bot.run or bot.start in case your setup_hook does not require to communicate with the discord api
asyncio.run(main())
π€
You know he's be's using the pythons properlies when he has the functions return thingies there
We's simple folk we's is.
apostrophe lover or what
Well I don't want you to get confused with "wes"
incase "Wes" is an actual word somewhere.
like 200 languages on this planet, you cant be sure
What even is we's in the first place, that ain't a short abbreviation or anything
Na it's not a word at all
You know how in the simpsons theres cletus ?
well he talks in his weird simple mannerism.
I was trying to mimic that...

I'm sure asher ain't never so simpsons π³
This isnt sending through the image and no error coming thr py async def button_callback(interaction): if channel_sent_in == 1017792577740734536: await interaction.response.send_message(f'Approved and sent to #{channel_final}!') embed_approve = discord.Embed(title=f"{channel_final} ping!", color=discord.Color.purple()) embed_approve.add_field(name='Message: ', value=f"{message.content}") embed_approve.add_field(name='Sent in by: ', value=f"{message.author}") embed.set_image(url=message.attachments[0].url if message.attachments else None) embed_approve.set_footer(text=f'Provided by Donks#1048 β’ {current_time}') await channel_final.send(embed=embed_approve) elif channel_sent_in == 1018468004121542716: await interaction.response.send_message(f'Approved and sent to #{channel_final_mi}!') embed_approve_mi = discord.Embed(title=f"{channel_final_mi} ping!", color=discord.Color.purple()) embed_approve_mi.add_field(name='Message: ', value=f"{message.content}") embed_approve_mi.add_field(name='Sent in by: ', value=f"{message.author}") embed.set_image(url=message.attachments[0].url if message.attachments else None) embed_approve_mi.set_footer(text=f'Provided by Donks#1048 β’ {current_time}') await channel_final_mi.send(embed=embed_approve_mi)
so much redundant code...
could have made a single embed and changed just the title inside every conditional using the title setter
and that would actually solve most of your problems
where are you deleting the message?
you arent defining mess..
embed
do you know how scopes work?
woah, how do you think mess gonna tp to the callback
hiow do i make 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.
x == y Checks if two embeds are equal.
New in version 2.0...
great, go learn that then
could you help me with making it better? π
mhm
ppap
thank you greatly
title=embed

@bot.slash_command()
asnyc def embed(ctx)
embed = discord.Embed(title="idk", description="desc", color=0xff0000)
await ctx.respond(embed=embed)
the copy pasting begins π
if you are inside a view class, you could make an embed inside the __init__ method and add all the fields there, leave the title inside the discord.Embed() object to be an empty string and define all the other vars you need like channel_sent_in and stuff... or if you aren't inside a class, simply make it inside the command function
when you hit the callback, you can use the title setter like so
embed = discord.Embed(title="")
async def callback(inter: discord.Interaction):
if channel_sent_in == 12345678098765432:
embed.title = "my_title"
channel_to_send_in = 123456765432 #channel_id
elif channel_sent_in == 19856789:
embed.title = "uwu_title"
channel_to_send_in = 1234567654321 #other channel_id
channel = bot.get_channel(channel_to_send_in) or await bot.fetch_channel(channel_to_send_in)
await channel.send(embed=embed)
f
you made another gist
@radiant parrot
no sire, I didn't. Opinion respected
no not for you peyton
...?
....
are you using discordpy?
waht is discord oy
is your import import discord?
a discord api wrapper written in python
how do i use it ?
oh lord
check out the docs
You take it and eat
im out. Back later..
Or feed it to a snake
so cld swap out this? ```py
async def button_callback(interaction):
if channel_sent_in == 1017792577740734536:
await interaction.response.send_message(f'Approved and sent to #{channel_final}!')
embed_approve = discord.Embed(title=f"{channel_final} ping!", color=discord.Color.purple())
embed_approve.add_field(name='Message: ', value=f"{message.content}")
embed_approve.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed_approve.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
await channel_final.send(embed=embed_approve)
elif channel_sent_in == 1018468004121542716:
await interaction.response.send_message(f'Approved and sent to #{channel_final_mi}!')
embed_approve_mi = discord.Embed(title=f"{channel_final_mi} ping!", color=discord.Color.purple())
embed_approve_mi.add_field(name='Message: ', value=f"{message.content}")
embed_approve_mi.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed_approve_mi.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
await channel_final_mi.send(embed=embed_approve_mi)
async def button_callback_2(interaction):
await interaction.response.send_message(f'Disapproved and muted user!')
await send_mute(message.author, f'Suggesting non-needed post for #{channel_sent_in}')
async def button_callback_3(interaction):
await interaction.response.send_message(f'Disapproved, user not muted')
button1.callback = button_callback
button2.callback = button_callback_2
button3.callback = button_callback_3``` for wot u sent
My PoV
no lol, just for the button_callback, let the other callbacks be in peace
gotcha
"That's just some random machine code I don't give a frick"
!e
class Foo:
def bar(self):
print('bar')
inst = Foo()
notinst = Foo
inst.bar()
notinst.bar()
@paper sluice :x: Your 3.11 eval job has completed with return code 1.
001 | bar
002 | Traceback (most recent call last):
003 | File "<string>", line 8, in <module>
004 | TypeError: Foo.bar() missing 1 required positional argument: 'self'
do i still need seperate embeds yea?
nop
just a single embed
with changing titles using the title setter
basically, the embed remains same but the title changes
Ryuga why making errors
ahhh smart ty
Got tired of segfaults, wanted to see real error messages
Ryuga, need to get a life at this point π
yea π
now when i press approve, the message isnt sending to channel
show the current code
async def button_callback(interaction):
await interaction.response.send_message(f'Approved and sent to #{channel_final}!')
embed.add_field(name='Message: ', value=f"{message.content}")
embed.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
async def callback(inter: discord.Interaction):
if channel_sent_in == 1017792577740734536:
embed.title = "Generic-info ping!"
channel_to_send_in = 942848242616516638 # generic-info
elif channel_sent_in == 1018468004121542716:
embed.title = "Member-important ping!"
channel_to_send_in = 640107632690200587 # member-important
channel = client.get_channel(channel_to_send_in) or await client.fetch_channel(channel_to_send_in)
await channel.send(embed=embed)```
oof, not a nested callback, whatever is inside the callback will be inside the button_callback, I just gave an example then
and that should fix it
so delete this? py async def callback(inter: discord.Interaction):
or get rid of my intial button_callback
get rid of this, the content inside this should remain in button_callback
gotcha
async def button_callback(interaction):
await interaction.response.send_message(f'Approved and sent to #{channel_final}!')
embed.add_field(name='Message: ', value=f"{message.content}")
embed.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
if channel_sent_in == 1017792577740734536:
embed.title = "Generic-info ping!"
channel_to_send_in = 942848242616516638 # generic-info
elif channel_sent_in == 1018468004121542716:
embed.title = "Member-important ping!"
channel_to_send_in = 640107632690200587 # member-important
channel = client.get_channel(channel_to_send_in) or await client.fetch_channel(channel_to_send_in)
await channel.send(embed=embed)```
Looking good now?
This error now py channel = client.get_channel(channel_to_send_in) or await client.fetch_channel(channel_to_send_in) UnboundLocalError: local variable 'channel_to_send_in' referenced before assignment
this may throw an error that if none of the conditionals hit and embed.title won't be set which will return an error and channel_to_send_in will also get away undefined and will throw an error
you should add an else statement to counter this
else:
return
@radiant parrot ^ that'll fix your issue
that if none of the conditionals are triggered, it will stop the function there and then
add this after your elif
await interaction.response.send_message(f'Approved and sent to #{channel_final}!')
embed.add_field(name='Message: ', value=f"{message.content}")
embed.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
if channel_sent_in == 1017792577740734536:
embed.title = "Generic-info ping!"
channel_to_send_in = 942848242616516638 # generic-info
elif channel_sent_in == 1018468004121542716:
embed.title = "Member-important ping!"
channel_to_send_in = 640107632690200587 # member-important
else:
return
channel = client.get_channel(channel_to_send_in) or await client.fetch_channel(channel_to_send_in)
await channel.send(embed=embed)```
Good?
huh? wdym
you probably added them on the wrong number I think
add the one you want first
I see
you're probably doing something wrong there then
@slate swan no error now but its not sending to the channel tht it shld be :/
I'll help, but one at a time
huh? is that so? there should be an error though
nah no error coming through
make sure if you have an error handler, that you're raising the error
nah no error handlers
that's weird then, I see nothing wrong in the code really
you sure that you're sending the message inside the channel_sent_in valid ids also
mhm
that's such messy code...
I mean, just set the callback for the buttons before you add the buttons to the view
im starting to realize how frequent this is done now too...
Tbh i dnt mind abt messyness, just as long as works
that's so freaking true lol
nice, and I was serious about the callback setting
gotcha
so put these py button1.callback = button_callback button2.callback = button_callback_2 button3.callback = button_callback_3
before view.add_item yes
before adding buttons to view?
yes
define the callbacks too
but that would break your callbacks...hmm
I seriously wanna ask why no subclass π
but as long as it works
what u think i do then?
should prefer to learn how subclassing a View is done because that's the only way to do whatever you're tryign to achieve rn and you can use the variables anywhere after adding them to the instance of the view
even if you go back to the old code, you'll face the same issues
rewrite code for me x
^
only joking haah
I mean, I didn't want that you'll have to rewrite but considering what you want to do
Yh i understand
Tbh only issue i fast atm is it not sending to the channel
When pressing approve
would this be right and does it look right? im making a help command in hikari-tanjun and this is part of the code
elif obj in ctx.client.iter_commands():
command = component.slash_commands(obj)
if isinstance(command, SlashCommandGroup):
await ctx.respond("This is group help")
else:
await ctx.respond("This is help command")```
im just following it off of this from the dpy gist someone made for the help command https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
```py
elif argument in bot.all_commands:
command = bot.get_command(argument)
if isinstance(command, commands.Group):
# !help <group>
await ctx.send("This is help group")
else:
# !help <command>
await ctx.send("This is help command")```
why are you following a discord.py gist for a tanjun-hikari help command
Cuz tanjun doesnβt have an automated help command so I have to hard code it
And the example in the gist is an okay implementation and helps me interpret it better
@slate swan
Yeah lightbulb would be a lot easierβ¦
I just wanted to try out tanjun cuz I already made a lightbulb bot
But when I try this, it doesnβt work and just says βapplication did not respondβ do you know how to help with this? @slate swan
got no experience with tanjun
for role in user.roles:
if role.id in biglist:
rank = role.name``` this only works if user is discord.Member and not discord.User right?
right
how can I change it to discord.Member
for that piece of code
@commands.command()
async def whois(self, ctx, *, user: discord.User = None):
if user is None:
user = ctx.author
date_format = "%a, %d %b %Y %I:%M %p"
for role in user.roles:
if role.id in biglist:
rank = role.name
for role in user.roles:
if role.id in biglist2:
company = role.name```
hint: change the type hint
so user = discord.Member
Hm sad, thanks anyway
?
user: discord.Member
for role in user.roles:
if role.id in biglist:
rank = role.name
for role in user.roles:
if role.id in biglist2:
company = role.name
user: discord.User``` Would this work?
in the case where user will be discord.Member until it finish the for role in funciton?
thats assignment not type hint
how do I do that
just like you did for discord.User
(self, ctx, *, user: discord.User = None):```I don't wanna change it here though
why?
discord.Member runs everything discord.User can?
My code is all going wrong and idk why
is what ur saying @paper sluice ???
yea
send code
thats sad
async def button_callback(interaction):
if channel_sent_in == 1017792577740734536:
await interaction.response.send_message(f'Approved and sent to #{channel_final}!')
embed_approve = discord.Embed(title=f"{channel_final} ping!", color=discord.Color.purple())
embed_approve.add_field(name='Message: ', value=f"{message.content}")
embed_approve.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed_approve.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
await channel_final.send(embed=embed_approve)
else:
channel_sent_in == 1018468004121542716
await interaction.response.send_message(f'Approved and sent to #{channel_final_mi}!')
embed_approve_mi = discord.Embed(title=f"{channel_final_mi} ping!", color=discord.Color.purple())
embed_approve_mi.add_field(name='Message: ', value=f"{message.content}")
embed_approve_mi.add_field(name='Sent in by: ', value=f"{message.author}")
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed_approve_mi.set_footer(text=f'Provided by Donks#1048 β’ {current_time}')
await channel_final_mi.send(embed=embed_approve_mi)```
Stuff is sending to wrong channels
and images not being sent through
else:
channel_sent_in == 1018468004121542716

even if it elif, i dnt work
== is a conditional operator and the statement some_var == 1234 has literally no effect
why is this not sending an image thorugh if user sent one? py async def button_callback(interaction): await interaction.response.send_message(f'Approved and sent to #{channel_final}!') embed_approve = discord.Embed(title=f"{channel_final} ping!", color=discord.Color.purple()) embed_approve.add_field(name='Message: ', value=f"{message.content}") embed_approve.add_field(name='Sent in by: ', value=f"{message.author}") embed.set_image(url=message.attachments[0].url if message.attachments else None) embed_approve.set_footer(text=f'Provided by Donks#1048 β’ {current_time}') await channel_final.send(embed=embed_approve)
On my pc I do not get this error, but on vps I do any ideas?
The annotation isnt really correct
I won this round
I think your indentation is broken, I'm not sure tho, I'm on phone
wym
To be specific the correct annotation is user: discord.User | None = None
why
Because its type can be either one of those types specified?
Optional π
You can also use it but i'm showing the usage of the built in union as in typing.Optional it also suggests to take a look
Changed in version 3.10: Optional can now be written as X | None. See union type expressions.
πΏ ok
send proof
of ur "chess"
coz I still think it's a likely excuse to go afk

no
i can send a batch record sheet
how does someone else's going afk matter 
coz im bored
no idea actually
thats how..
but anyways i was in a tournament
π u won or tournament still ongoing
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
still going
i just won this round
i have 2/3 points
noice noice 
Whats the prize at the end?
embed = nextcord.Embed( Error: Expected indented block It the embed that has the error.
Your indentation is wrong.
and what does that mean. Im not the smartes guy when it comes to error
What's the line above it?
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(label="Accept", style=nextcord.ButtonStyle.blurple, custom_id="Accept")
async def Accept(self, button: nextcord.ui.Button, interaction: nextcord. Interaction):
embed = nextcord.Embed(```
i have title and stuff under
ok
and how to i fix so its not empty
@errant coral
see !indent if you don't know what it is
!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
k
and consider learning python before trying out discord.py, because it can be complicated and make things harder for you
im using nextcord
Python isnt the only thing!
that's a discord.py fork and you'll need to learn python nevertheless
it's a good place to start
kek 2022 comeback i am using nextcord
Yes
i dont know how to fix the most errors
i know how to code but this error messed my mind
if you say so
learn how to fix errors 
good idea lol
prevention better than cure code carefully so that u get minimal errors 
ok
Asher, how does this look π³
whats Asuna?
I have two buttons in two different messages and I want to do something after both the buttons are pressed by two different person. How can I make the bot do it when both buttons were clicked?
looks nice
totally my personal discord.py wrapper
but same question whats asuna π
oh, nice
package name does not follow convention!!!
ok zeffo
i am going to have nightmares about this.
do C
just don't sleep stay awake Β―_(γ)_/Β―
you will feel alright π
c language?
yup
too alike like dpy, looks like a garbage fork at first look
strings are for the weak!
char str[];
oop too?
it does have OOP, its just not in terms of classes. You can make objects (structs) and add methods to them if you wish to do so.
when did I say that's a fork
well thats not strictly oop tho struct is just at best minimal class storage
looks like
skill issue
it gets the job done
If youre going to make a wrapper atleast have a unique personalized impl
I'm not even making a wrapper
fair enough i still like cpp better
yea, cpp aint bad, they do try their hardest to avoid pointers though
If youre making objects with a Gateway and REST API its a wrapper?
ryuga how many languages u know now 
2
pointers are fun to play with
I'm not making objects either
it gives quite a speed boost also
yea
direct memory address
or maybe I am
nice nice
Pointers arent really hard?
when did he say ptrs are hard π
File "/app/cogs/filtered.py", line 254, in on_message
anti = db.find_one({ "guild_id": message.guild.id })['filter']
AttributeError: 'NoneType' object has no attribute 'id'
discord.client: Ignoring exception in on_message
Traceback (most recent call last):
await coro(*args, **kwargs)
File "/app/cogs/antilink.py", line 307, in on_message
anti = db.find_one({ "guild_id": message.guild.id })['anti-link']
AttributeError: 'NoneType' object has no attribute 'id'
@primal token
hardest to avoid pointers
why would you avoid pointers in the first place?
they just try to stick the builtins as much as possible, its not about it being hard
they do try
Then whats so scary to avoid about it?!?!?
nothing? I didn't say they were scary
he didn't specify anyone in particular
I'm a bit confused on your wording can you rephrase that?
π
like, instead of using int *, they will use array. Instead of char * they use string. If you use such pointers in cpp which already have some type builtin, people in the cpp community will not be happy. I think the cpp community also said like use the builtins instead of pointers in one of their standards thing. Its mainly to avoid unsafe code
and good ol segfaults
Yeah i would agree with them
yo i get an error at resp.text()
im suspecting it to do with the headers
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}
send the error πΏ
https://github.com/aio-libs/aiohttp/issues/4549 @faint sapphire
thanks i tried applying it
i think its to do with my bad wifi connection
so i think i also have to increase the timeout from the default one
Hello, what this error mean shard id none heartbeat blocked for more than ?
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(label="Accept", style=nextcord.ButtonStyle.blurple, custom_id="Accept")
async def Accept(self, button: nextcord.ui.Button, interaction: nextcord. Interaction):
embed = nextcord.Embed(
title="Application Accepted",
description="The role the person is applying for is now added", color = nextcord.Color.from_rgb(3,200,255)
)
await interaction.channel.send(embed=embed)```
Error:
```Expected indented block```
this is the line with the problem
```embed = nextcord.Embed(```
It probably means the wrapper didnt acknowledged a few heartbeats
how can I fix it ?
!blockingio
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!
I used it, i do not understand really the error, all of my function are asynchronous, et one of it is coupled with discord.tasks to loop every 30s (@tasks.loop(seconds=30.0)
Can you show your code?
how would i make my bot update itβs status every 5 minutes
!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/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
how would i make my bot update itβs status every 5 minutes
That's my main code :```py
class Bot(commands.Bot):
def init(self, command_prefix):
self.command_prefix = command_prefix
super().init(command_prefix = "!", intents=intents, help_command=None)
async def setup_hook(self):
await self.tree.sync(guild = discord.Object(id = guild_id))
async def on_command_error(self, ctx, error):
await ctx.reply(error, ephemeral = True)
bot = Bot(command_prefix="!")
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game("Je cherche des deals..."))
@tasks.loop(seconds=30.0)
async def deal():
#doing something (really long so i prefer not to sent)
@bot.command()
async def script(ctx):
global channel_suivi_id
channel_suivi_id = ctx.channel.id
await ctx.message.delete()
deal.start()```
Its suggested not to change your bots status in on_ready just use the status and activity kwarg in your bots initiater and your code doesnt really help much especially how you removed the part that may cause the issue
@primal token
Its an async function, upon a calling of the function you would await its return value thats a coroutine
^
The part that may cause the issue is only web scrapping with bs4, there is anything other
So i modify this for this : py @bot.event async def on_status(): await bot.change_presence(activity=discord.Game("Je cherche des deals..."))
So on_status instead of on_ready ?
is there any way to prevent my bot from getting ratelimited?
Its a basic issue related to python's asynchronous implementation so reading up on the topic is your best solution as it can fix that issue and others you may come across, you shouldnt call yourself dumb either because of your knowledge on a topic as we all started as a beginner in any topic you read up on
just a task loop
make*
Dont use replit and follow per endpoint base bucket ratelimits
send less req to discord api
Isnt bs4 not asynchronous?
nope its sync
Well then thats your issue
make it like 20 atleast 5 too frequent
so i delete the part that i would edit ?
should make it 10 secs
how that my issue 
Its not a reply to you hence me not pinging you
this my issue, which library for async webscrapping ?
Its me using your info!
run it in an executor
creating an executable ?
no running it in a thread thats not your main one/the one that contains your event loops mostly know as the main or os thread it would also depend where you started an event loop as its been deprecated to always have one running iirc
library thread?
def foo():
... # Blocking code
async def bar():
await bot.loop.run_in_executor(None, foo)
Blocking coderefers to the main function that is looping ?
nope if u wanna multi thread u better use concurrent.futures
no? A CPU thread.
nope
blocking means in normal circumstances u can't run multiple instances of the code or function coz its blocking in such cases we open a thread for each of these blocking code functions so that we can execute them simultaneously
ohhhh okay
so general blocking libs are pillow and requests bs4 almost all base libs python are blocking
So what do i write in the blocking code ? Have you an example to understand better
like opening and writing to a file is also blocking in such cases u should use aiofiles
blocking code shouldn't need much change unless there is an asynchronous version of the lib which does the job if there isn't put that blocking code under a function and then run it in the executor like i did with foo
ohhh so it's not really a "coding error" of my person, it is "normal" that bs4 in async function blocked the heartbeat ?
Blocking code refers to running code/tasks on bare python which executes in order, no matter what happens so no concurrency, While asyncio was created, which it has an event loop that is used to schedule many tasks in a loop to reach concurrency, so blocking code is a task that doesnt get schedule/managed from the event loop hence blocking the event loop and not giving the event loop and IO, ownership for concurrency.
yeah so for example if u have blocking code in a command that means the first call of the command needs to be completed till the next call process starts ie only one person can use that function at a time
i still feel its better to explain in beginners terms π
let's imagine in a function I execute requests via requests, so it is this function that is considered blocking?
Is it too hard for you to understand?
sigh not me i meant for ppl asking the doubts if they already understood would they be asking here
hmm
Well then its beginner approved if you can understand it, kek
have you some links to doc ?
if u use requests lib its blocking yeah so use aiohttp
smh go read this https://www.brainyquote.com/quotes/albert_einstein_383803
"If you can't explain it simply, you don't..." - Albert Einstein quotes from BrainyQuote.com
Its quite simple if you have the knowledge needed to understand it, If you dont, go read up on it, im doing you and me a favor
i don't think dpy documents this part
I find this example ```py
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[:15], "...")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())```
I will check that, thanks a lot @primal token @shrewd apex
i never said it was tough but if that is how u are going to explain to a layman and expect them to understand then i pity the layman π
coupling aiohttp to bs4 to scrape balise
I wouldnt recommend it as you dont need to run it until complete, right? just schedule a task to the event loop
I do not use the last 2 lines, i use the integrated discord.tasks library
seems fine u can put the aiohttp part in the async function and the bs4 part in a separate sync function ie def and then run it using executor
since if u are using bs4 here u will need a thread at some point might as well use the built in one
Your analogy is quite terrible i must say, no offense, well would you like only to know briefly how a topic works or how it actually works and search between multiple sources and get extra info and become knowledgeable on the topic?
I can't put all in one ?
well we have no idea how much the opposite person knows do we so we should try our best to make sure wether layman or someone with some amount of knowledge is able to understand
thats our role isnt it π
better not to
Well i have explained it quite correctly, if he doesnt understand he can read up on it and get more knowledgeable and understand better than me explaining it, no? Better to have multiple resources than one mind.
Im helping him more than just resuming the topic and him calling it a day.
fair enough everyone has their own opinions topic itself is subjective
well not to shift topic but there are various teaching philosophies its not universal to follow a certain method πΏ
did i? thats what i said mine and urs opinions and thoughts are different
ok rip nvm we are deviating too off topic now π
Teaching pedagogy is the use of methods, practices and concepts to use to teach, thats subjective, yes, but i wouldnt say its an opinion.
guys is discord.py getting discontinued
wut?
thats old news it was for a period of time then work on it started again
now even 2.0.1 is out
but i was following a guide on how to make an unban command I copied it and it didn't work
most guides are now outdated
ik none as of now
π
getting this strange error
read_timeout=None, conn_timeout=None, timeout=sentinel
what should i set these timeouts to
First, this is totally not a discord bot related question. Secondly, what for are you even using asyncio.gather, can't you just execute them one by one, I don't see any point in executing everything at once. This is what causes the error most likely
yh, i saw a stackoverflow doing it like that, i was confused, but thought it was necessary
ill make the changes
this is why we don't use SO for discord bots
SO?
i was told to use aiohttp
i was using concurrent.futures before, hadnt tested it
guys never had such error and rn its popping up, how to fix?
'dict' object has no attribute 'Cog'```
@tasks.loop(minutes=5)
async def on_ready():
await bot.change_presence(
status=discord.Status.online,
activity=discord.Activity(
type=discord.ActivityType.competing,
name=f"with {len(bot.users)} users"))
Would this work @primal token
Probably not properly because you are doing it under the on_ready section
You must define a new function for it
And then start the loop within the on_ready section
i cant get it to work with aiohttp, so is it okay with this method?
(i do a for loop to request 11 web pages)
@commands.command()
async def rankup(self, ctx, role: discord.role, user: discord.member = None, amount=0):
if amount is None: # sets amount value to 1 if not indicated by user
amount = 0
if user is None:
user = ctx.message.author # sets the user to the one who typed the message if not specified
uid = user.id
uid = str(uid)
if uid not in self.names:
await ctx.send("That user is not in the Database \n Hit =create @user") # , delete_after=10
return
if uid in self.names:
await user.add_roles("role id")
what i have done wrong?
Reset your token
and can you show cogs/point.py ?
i built in a new command
this ```python
@commands.command()
async def addrole(self, ctx, user: discord.Member, role: discord.Role):
try:
await user.add_roles(role)
await ctx.send(f'{user.mention} was given the role: {role.name}')
except commands.BadArgument:
await ctx.send('That is not a correct role!')
This code can be done allot better
but still shows the same error
can you show all of your code?
yes, can you send me the link of the copy thing?
!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.
this one when a user does !addrole @scenic thicket
give the user that role
change the name of this
as youre overwriting the name space and why are you using JSON as a database? your bot is going to be so slow
what to use a database?
That whole Cog needs a rewrite tbh
i have user: points
!pypi aiosqlite
XD
im new to this so idk what can i do
We already had a discussion about how to extend your knowledge #discord-bots message
why?
as youre overwriting the name space and why are you using JSON as a database? your bot is going to be so slow
oh thats right
anyone knows why doing request.get for some URLs but with aiohttp and asyncio can error at return await response.text()
in #help-lemon i gave more details
some links work, others dont
it is related to discord bots, as its a command im trying to implement
I wouldnt say its directly related to discord bots at all
Is there any possible way to use a number as command name?
iirc you can just pass a name kwarg into discord.ext.commands.Command
how can i catch RoleNotFound error?
except commands.errors.RoleNotFound:
await ctx.send('That is not a correct role!')
return
im trying to make the bot send an error message when the role the player is trying to get isnt found but i get this error
You arent passing a role and whats your issue on
how can i catch RoleNotFound error?
yeah thats what im trying to do, when a player isnt passing a role
i want it to get a message back
?
The bot isnt responding for some reason
:C
<@&831776746206265384> Just want to let you guys know that @unkempt canyon is being mean to me and not responding /j, just wanted to let you guys know this isnt normal behavior.
It's offline 
!ping
Blame chris
Oh that's not good
freak out, ahhhhhh!!!!
wahhhhhhhhhhhhhhhhh
mke it an alias
and in a string "1"
^
idk what that looks like
anyway, im still tryna get requests to work for bot commands
its so bloody hard to figure out why some urls dont work while others do
!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.
id doesnt work i get int error and role name gives me str error
What do you guys think about these emojis? Personally they look like garbage, like nitro emojis kek (some are old yes)
mobile client still doesnt have them kek
the new emojis are bad π«
maybe not bad but... strange
Omg they added you
congrats on your baby and being famous now!
hello?
how can i make the bot auto give role according to points amount
Are you trying to send a message on start up to a channel? or anything related to that
Well for starts you have a 403 forbidden error which is always permissions. Secondly, what is this Boosting?
Just took a look at the site they have in their description, seems like they've got a site for selling nitro tokens or something
How do discord bots measure the MS between the time it takes to send the message
you can time it like anything else with time.perf_counter()
start = time.perf_counter()
await channel.send('hello!')
elapsed = time.perf_counter() - start```
its a function from the time module
Traceback (most recent call last):
File "C:\Users\adama\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\adama\Documents\Coding\Python\Python Projects\Discord bots\TheGOATsUniverse Bot\main.py", line 50, in unban
banned_users = await ctx.guild.bans()
TypeError: object async_generator can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\adama\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\adama\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\adama\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object async_generator can't be used in 'await' expression```
Please help I am new to discord.py
and python in general
Are you following a tutorial?
Here's some advice: don't
oh
They're terrible as is evident here
I'm guessing this is some really badly coded ban command
Yeah. You can really get away with making it just one line
No, I know how it looks
I've seen it plenty of times π
All you need to do is take a discord.User typehint, and pass it into discord.Guild.unban(...)
!d discord.Guild.unban the appropriate documentation can be found here
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
thanks a lot
do you know how to unban them using the ID instead of a username cuz they might change their name
you are trying to make an unban command?
yup
use discord.Member object
do something like that:
async def unban(ctx,member:discord.Memeber)
then you can do
<prefix>unban @bright wedge or use id (mention or id)
object has no attribute 'tree' what does this mena?
ok thanks
Only commands.Bot instances have a tree by default. For client, you need to make and bind one yourself
@bot.tree.command()
Well I do this
class Arcade(commands.Bot):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def setup_hook(self) -> None:
self.tree.copy_global_to(guild = discord.Object(id = 1009249121590312980))
await self.tree.sync(guild = discord.Object(id = 1009249121590312980))
# Miscellaneous:
Client = Arcade(intents = discord.Intents.all(), command_prefix = '/')
@Client.tree.command()
as i said
I did do commands.Bot though
am sry i have many months to use discordpy :/
where are you getting error
i mean line?
@Client.tree.command()
AttributeError: 'Arcade' object has no attribute 'tree'
i want to make sure what is the difference between py await ctx.channel.send("...")
and py await ctx.send("...")
bscly there is not differences
as i remeber is the same thing
Ok ok thanks
am click here -> #discord-bots message maybe that will help you (message link is from this channel)
i mean read the messages above this link
ah
i have never use "tree" commands sry, im moving on js π
same dont move we need help
alr
@client.command()
async def unban(ctx,member:discord.Memeber):
await ctx.channel.purge(limit = 1)
await ctx.guild.unban(member)
await ctx.channel.send(f"{member} has been Unbanned")
print(f"{member} has been Unbanned!")```
is this good
am
try and see
if he cant display the member, try to move your channel.send() before the member ban
ok
why ctx.channel.purge(limit = 1)?
Also it needs to be discord.User not discord.Member because if a user is currently banned they can't be a member
oh ok
I want it to delete the command
Just use await ctx.message.delete()
Use ctx.message.delete
use
await ctx.message.delete()
whats the deletes
It deletes the provided message
Because purge is meant for deleting multiple messages at once
should I pass something or just like that
deletes the author's message
ok ok
no parameters
btw @bright wedge I tried it didn't work
@client.command()
async def unban(ctx,member:discord.Memeber):
await ctx.guild.unban(member)
await ctx.channel.send(f"{member} has been Unbanned")
await ctx.message.delete()
print(f"{member} has been Unbanned!")
yea, it not work because you forgot remove the await ctx.channel.purge(limit = 1), so the bot can find the author's message. you got it (you already delete it)?
i gtg bye see yaafter school
ahahh, take care!
give me one good reason that is supposed to make this work
The Engineer is a cool man
how will dpy parse the member argument to a Member object
you can check it out, we are here to help!
I was just saying that it won't work
you'll have to accept a user id or a User object
did you try this and it didn't work?
I mean, that's common sense, isn't it
no offence
try and see π
how will a banned user be a member of that particular guild
I need an explanation
not "working code"
help me understand huh
and you can try it, but not here, here is for help (feel free to dm me!)
this channel is also for discussing on certain topics if they are related, so it's fine
i can prove it! but not here!
what a topic man
but i think the topic says that this channel is also for discussions related to bots
im not talking about slash commands!
what!
this is not a slash command, is a normal command!
and what am I supposed to pass in as my argument for member?
in slash commands?
the Memeber :lmao:
no prefix commands
ikr
i dont got you bro sry
how am I supposed to invoke the command...?
you said we cant use member_id for get access in discord.Member object right?
I said that how are you gonna get the Member object when the user isn't even in the guild
then i understand wrong
.
it's also Memeber but that doesnt really matter
I know
like running
!unban user_id and converting that to a Member object will fail 99% of the times
Just change it to User smh
I know lol
yeah use discord.User? (just got here)
or to int cus sometimes you can't get the User, and ID is enough since unban takes a snowflake
is the 1% when you try to unban the member who is in not banned?
no when the member is in the cache and the member was banned and unbanned during the same restart
inseresting
I just use Annotated[discord.BanEntry, BannedMemberConverter]
BannedMemberConverter is my subclass of Converter btw if some1 thought it's commands.BannedMemberConverter
do replit discord bots get rate limited more than pc hosted bots?
yes
What is ctx?
a discord.ext.commands.Context instance that discord.py passes to your Command
I just read a whole discussion about someone telling Ashley you should use discord.Memeber in an unban command
i want to make button roles in my public discord.py bot
how can i store roleids and guild ids in my database and then make them work on correct messages persistently (storing in database so that a guild can have multiple button roles panels), maybe i will also use name as a primary key?
reaction roles but with buttons?
iam getting a file .. um when that command is used it throw a error telling in this directory of pyhtin in this line something, something and ... error in console idk how to solve it anyone can help ? my code doset throw any error
u misspelled member

Make each button have unique ID (you can use uuid lib or os.urandom) and listen for low-level interaction events, get the role id associated with the button ID in a database and assign it
Buttons have custom id in discord.py
Omg wait nvm i can do that
Yes
guys never had such error and rn its popping up, how to fix?
'dict' object has no attribute 'Cog'```
anyone could help?
!e
print({}.Cog)
@paper sluice :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'dict' object has no attribute 'Cog'
you are trying to do that
no, its shows error here:
@Commands.Cog.listener.event
I'm working with embeds and I'm trying to get something like this on discord.py, but I can't figure out how to make it so "tight". The example wasn't made on discord.py so I'm not too sure it's even possible
what is Commands and why are you trying to get event from listener?
oh i solved it lol just deleted, im dumbass π₯², thanks for the help!
@pulsar thistle you had a dict named Commands, right?
Yes but if Iβm not mistaken it showed an error too
!d discord.EmbeddedActivity
No documentation found for the requested symbol.
embedded activity is not even a thing
how do i make slash commands in discord.py?
thanks
attachment://billboard.png
where did you copy that code from?
where did you copy the other code from π
sus, but ok, learn to debug your code then
you have so many variables, you are sourcing from other files
you just send a small screenshot and expect us to fix all your problems
anyone can review my function?
it uses asyncio and aiohttp, returns status 200 but errors for returning await resp.text()
i showed output in #help-mango
solved, adding keep alive was needed
you were the one who pinged me, but ok
someone know why async def X(ctx, *args): give a error?
what is the error?
!e ```py
async def X(ctx, *args): ...
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
anyone help! i'm feeling :(
this own create slash commands is timeout.
Here code:
@client.tree.command()
@commands.has_permissions(moderate_members= True)
async def timeout(interation: discord.Interaction, member: discord.Member, reason: str, day: int,
hour: int, mintue: int):
if member.guild_permissions.moderate_members:
await interation.response.send_message("You can't do this person is moderate", ephemeral=True)
return
duration = timedelta(days=day, hours=hour, minutes=mintue)
if duration >= timedelta(days = 28):
await interation.response.send_message("No more than 1 billion years LOL, just means default is 28 days", ephemeral=True)
return
if reason == None:
await member.timeout(duration)
await interation.response.send_message(f"Good! Just timeout {day} days, {hour} hours, {mintue} minutes!")
else:
await member.timeout(duration)
await interation.response.send_message(f"Good! Just timeout {day} days, {hour} hours, {mintue} minutes!\nReason: **{reason}**")
output has error: 2022-09-13 17:46:01 ERROR discord.app_commands.tree Ignoring exception in command 'timeout'
Can you send the entire traceback?
using asyncio and aiohttp to do webscraping for a bot command
it runs the script but gives a strange output, havng trouble finding answers on google```py
async def fetch(session, url):
async with session.get(url) as resp:
assert resp.status == 200
return await resp.text()
async def getInfo(Type, updatedInfoMv):
async with aiohttp.ClientSession(headers=headers, connector=aiohttp.TCPConnector(ssl=False)) as session:
if Type=="mv":
mm2vContent = []
ittt = 0
for Class in MvClasses:
newpage = await fetch(session, getURL("mv", Class))
ittt+=1
itt = 0
for mm2vPage in mm2vContent:
await mm2vFilter(mm2vPage, updatedInfoMv, fnlist[itt], Class)
itt+=1
print(len(updatedInfoMv))
@bot.command(aliases=['ud'], case_insensitive=True)
async def update(ctx):
await ctx.send("beginning update")
Type = "mv"
updatedInfoMv = []
loop = asyncio.get_event_loop()
loop.run_until_complete(await getInfo(Type, updatedInfoMv))
#loop.close()
Hey @hollow ice!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
imagine using event loop for an async function in an async function 
you can just do await your_coro inside an async function, you don't need to make an event loop
u didn't respond to the interaction in 3 seconds defer ur interaction
Hey! My bot is sending a new question if u start the command twice and reacts to itself... Aka its talking to itself
are u using on_message for commands?
can fix this code? @shrewd apex
nope
ok fine!
in ur check add m.author == ctx.author
thanks
π
some dude on yt said its better to do this
tasks = [session.get(URL.format(symbol, API_KEY), ssl=False) for symbol in SYMBOLS]```than this```py
# Can't do this!!
for symbol in symbols:
tasks.append(session.get(url.format(symbol, api_key)))
idk why tho
What the
Slash is not working with hybrid cmds
That youtuber you watch has definitely smoked some weird asyncio grass
π€£lol
lol
yes
Define asyncio
The module
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
This
i posted this here cause its the same thing imo and i dont see the difference
SPEED
Depends
bruh its u who doesnt know what asyncio is
Nice
itll be almost the same as doing requests if u do session.get then await res.text() for each
Eh think what you want but I have developed several apps with asyncio
@faint sapphire one question - what exactly do you want to achieve
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=">", intents=discord.Intents.default())
async def setup_hook(self) -> None:
self.tree.copy_global_to(guild=discord.Object)
await self.tree.sync()
bot = MyBot()
@bot.tree.command(name="test", description="test slash command")
async def test(interaction: discord.Interaction) -> None:
await interaction.response.send_message("true")
bot.run('insert_token_here')```
**error:**
```Traceback (most recent call last):
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika beta discord bot.py", line 3, in <module>
class MyBot(commands.Bot):
NameError: name 'commands' is not defined```
how to fix?
from discord.ext import commands below import discord smh
You need to import the commands submodule
AttributeError: 'MyBot' object has no attribute 'tree'
new error
if u are gonna multi thread coros u might as well just use normal function as in sync and then thread them
getting html code from 11 pages / 22 webpages
im new with asyncio but ive used coroutines in lua
script sends a bunch of requests then reads the response for each
Wtf ok
how to fix
Read the error, think and fix
im new to slash commands...
which version of dpy are u on?
latest
in bot.tree.command
hmm where is ur guild id for discord.Object?
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
Ok it's predefined thx god
@slate swan what does this print
import discord
print(discord.__version__)```
just remove the copy to line
from discord.ext import commands
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=">", intents=discord.Intents.default())
async def setup_hook(self) -> None:
await self.tree.sync()
bot = MyBot()
@bot.tree.command(name="test", description="test slash command")
async def test(interaction: discord.Interaction) -> None:
await interaction.response.send_message("true")
bot.run('insert_token_here')```
still no work π¦
@slate swan
1.7.3
πΆ
pip install -U discord.py
zsh: /usr/local/bin/pip: bad interpreter: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: no such file or directory
literally my feelings rn
doesnt let me update.. π¦
Why the heck do you have 2.7 installed
π₯΄
kek
try without the -U
it updates when u ask to install
still no work
how are u even using 1.7.3 with 2.7 is that even supported?
pip install discord.py
zsh: /usr/local/bin/pip: bad interpreter: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: no such file or directory
just do pip install discord then
You don't even know the latest version.
I recommend removing all versions of python on your machine and install the latest from site, when installing put "Add Python to PATH" checkmark on
maybe u dont have pip
i do...
ig ur computer is forbidden
I mean duh
It's 2.0.x or smth
Why did I suddenly lose my connection when panda started a conversation with me bruh
actually were on 2.1.x already
discord.py-2.1.0a4591+gedfacb36
2.1.0
@slate swan do this
^^
i thought .py was discontinued
wRoNg
omnious omen
Ok, I just don't use it so idk the latest version you are correct lol
help, i have a cmd, and how do i get a reaction that is reacted on the msg that bot sent as a string,
The development resumed in like march or april
nπ§
literally im using python3
Have you uninstalled all the pythons
no
I mean that's 100% gonna fix everything