#discord-bots

1 messages Β· Page 82 of 1

maiden chasm
#

Can you explain to me

drifting arrow
#

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

maiden chasm
drifting arrow
#

it's up to you how you want your file structure to be

maiden chasm
#

What’s the easiest

drifting arrow
#

Β―_(ツ)_/Β―

maiden chasm
#

And what have I to code

drifting arrow
#

you'll need to learn how to use python first.

maiden chasm
#

How

#

Is it easie ?

drifting arrow
#

Python is easy

maiden chasm
#

And how can I learn

drifting arrow
maiden chasm
#

Example for course

#

@drifting arrow

#

@drifting arrow

drifting arrow
#

@maiden chasm freecodecamp?

slate swan
# maiden chasm .

"Developer" Rick,

Man actually using "Developer" in his username

πŸ’€ πŸ’€ πŸ’€

rugged shadow
#

I think they're trying to imply that you shouldn't put "Developer" in your name if you're not a developer yet

slate swan
#

Yeah

#

Anyways, do what you want

rugged shadow
#

But imo there is nothing wrong with that, besides people probably gonna dm u for some requests

slate swan
#

I just find it weird, using "Developer" in your name when 99% of the people in this server have more knowledge than you

drifting arrow
#

While I agree @slate swan, for now, try and keep it civil.

slate swan
#

Im just letting him know

drifting arrow
#

Just leave him alone? xD

slate swan
# maiden chasm i wanna learn it

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 πŸ˜‰

silk fulcrum
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
#

discordpy?

#

i think pycord is better, idk

silk fulcrum
#

that is a variant

silk fulcrum
strong crow
#

Tbh pycord has a nicer slash command API than discord.py

slate swan
#

yes

drifting arrow
#

At the end of the day, you're all wrong.

slate swan
silk fulcrum
drifting arrow
#

discord.js is where it's at

slate swan
#

yeah i agree

strong crow
#

Not looking at using other wrappers anyway, making my own

slate swan
#

but js is advanced

drifting arrow
#

is it tho?

slate swan
#

you can do more stuff with python

drifting arrow
#

I know some pretty stupid people.. and they manage to use it

slate swan
#

like overall

silk fulcrum
#

oh my gosh im late to my chess torunament

#

bye guys, good luck at deciding which wrapper is the best

slate swan
#

but tampermonkey is insane extension for js

drifting arrow
drifting arrow
#

Prove it. Send me the competition results when you win.

slate swan
#

Nah man just livestream the whole tournament

#

in 4k

drifting arrow
#

No. That'd risk doxxing him and idk who he is and nor do i want to

silk fulcrum
rugged shadow
strong crow
#

Don't make yourself more late!

silk fulcrum
#

true

digital charm
#

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```
slate swan
vale wing
drifting arrow
digital charm
vale wing
rugged shadow
silk fulcrum
#

im just a 13 y/o who plays chess and knows quite more in maths then his classmates

drifting arrow
#

I've done it before and I'll do it again

drifting arrow
#

dont underestimate my stupidity with money

vale wing
silk fulcrum
#

ok ima go now, bye

rugged shadow
#

glhf

vale wing
#

Bye

digital charm
vale wing
#

Why tf do people put two k

#

Like does that mean "okay okay"

digital charm
vale wing
#

Why would they need to double a word

digital charm
#

I just got used to it

vale wing
#

Just put a single key

digital charm
#

k

drifting arrow
#

Atm machine

vale wing
#

Nice

drifting arrow
#

rest in rip peace

slate swan
vale wing
#

I mean n🧊

drifting arrow
#

and finally, okay k?

vale wing
#

kkay

drifting arrow
#

kk

#

has been typing for a while.

#

im concern..

vale wing
#

He's trying to type semicolons

vale wing
#

N🧊

#

@faint sapphire just use async db wrapper bruh

frail sedge
#

the website link it's working in that part but idk how the body thing works.

faint sapphire
#

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)

vale wing
#

What wrapper are you currently using

maiden chasm
#

@drifting arrow how can i run the programm in visual

drifting arrow
faint sapphire
#

cause its a discord bot command doing this

vale wing
#

@faint sapphire what db wrapper are you currently using

drifting arrow
maiden chasm
#

k

faint sapphire
unkempt canyonBOT
faint sapphire
#

ok thanks

drifting arrow
#

@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.

drifting arrow
#

In the workplace you wont be able to constantly run to your colleagues to answer these things.

slate swan
#

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

digital charm
#

I'm a beginner so I need some help...

frail sedge
#

i need help. how do you send a jsom body post method to a website endpoint?

#

json*

drifting arrow
faint sapphire
vale wing
slate swan
slate swan
slate swan
drifting arrow
slate swan
#

anyone know how to fix this? ive tried making a global variable but then i get multiple not defined errors

drifting arrow
#

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

frail sedge
drifting arrow
#

So create the dictionary as you would the json file.
and yeet that dictionary as a json

drifting arrow
digital charm
drifting arrow
#

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.

sick birch
#

Yes you need to acquire a cursor first

drifting arrow
#

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.

slate swan
#

why would you create a pool inside a button callback?

#

that's something which should go into the setup_hook

drifting arrow
slate swan
#

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())
drifting arrow
#

πŸ€”

#

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.

slate swan
#

apostrophe lover or what

drifting arrow
#

Well I don't want you to get confused with "wes"

#

incase "Wes" is an actual word somewhere.

slate swan
#

it's not

#

not in english at least

drifting arrow
#

like 200 languages on this planet, you cant be sure

slate swan
#

What even is we's in the first place, that ain't a short abbreviation or anything

drifting arrow
#

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...

shrewd apex
slate swan
#

I'm sure asher ain't never so simpsons 😳

radiant parrot
#

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)

slate swan
#

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

paper sluice
#

where are you deleting the message?

drifting arrow
#

you arent defining mess..

ruby spoke
#

embed

paper sluice
#

do you know how scopes work?

slate swan
#

woah, how do you think mess gonna tp to the callback

ruby spoke
#

hiow do i make embed

slate swan
#

no

#

!d discord.Embed

unkempt canyonBOT
#

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...
paper sluice
#

great, go learn that then

radiant parrot
ruby spoke
#

ppap

radiant parrot
ruby spoke
#

title=embed

paper sluice
ruby spoke
#

@bot.slash_command()
asnyc def embed(ctx)
embed = discord.Embed(title="idk", description="desc", color=0xff0000)
await ctx.respond(embed=embed)

paper sluice
#

the copy pasting begins πŸ˜”

slate swan
#

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

slate swan
#

no not for you peyton

ruby spoke
#

init

#

discord.Embed(init)

slate swan
#

...?

ruby spoke
#

....

drifting arrow
#

are you using discordpy?

ruby spoke
#

waht is discord oy

drifting arrow
#

is your import import discord?

paper sluice
ruby spoke
drifting arrow
#

oh lord

paper sluice
vale wing
#

You take it and eat

drifting arrow
#

im out. Back later..

vale wing
radiant parrot
# slate swan if you are inside a view class, you could make an embed inside the `__init__` me...

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
slate swan
#

My PoV

slate swan
paper sluice
#

bro....

#

do you even read the error messages?

vale wing
#

"That's just some random machine code I don't give a frick"

paper sluice
#

!e

class Foo:
  def bar(self):
    print('bar')

inst = Foo()
notinst = Foo
inst.bar()
notinst.bar()
unkempt canyonBOT
#

@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'
radiant parrot
slate swan
#

just a single embed

#

with changing titles using the title setter

#

basically, the embed remains same but the title changes

radiant parrot
paper sluice
slate swan
paper sluice
#

yea πŸ˜”

radiant parrot
slate swan
radiant parrot
#
    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)```
slate swan
#

and that should fix it

radiant parrot
#

so delete this? py async def callback(inter: discord.Interaction):

#

or get rid of my intial button_callback

slate swan
radiant parrot
#
    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?

slate swan
#

right

#

looks cool it me

#

but

radiant parrot
#

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

slate swan
#

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

radiant parrot
#
        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?

slate swan
#

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

radiant parrot
#

@slate swan no error now but its not sending to the channel tht it shld be :/

slate swan
#

I'll help, but one at a time

slate swan
radiant parrot
slate swan
#

make sure if you have an error handler, that you're raising the error

radiant parrot
#

nah no error handlers

slate swan
#

you sure that you're sending the message inside the channel_sent_in valid ids also

radiant parrot
#

yep

#

do u want me to send whole code in paste bin?

slate swan
#

mhm

slate swan
#

that's such messy code...

radiant parrot
#

oh

#

as long as it works ig

slate swan
#

I mean, just set the callback for the buttons before you add the buttons to the view

hushed galleon
#

im starting to realize how frequent this is done now too...

radiant parrot
#

Tbh i dnt mind abt messyness, just as long as works

slate swan
slate swan
radiant parrot
#

so put these py button1.callback = button_callback button2.callback = button_callback_2 button3.callback = button_callback_3

slate swan
#

before view.add_item yes

radiant parrot
#

before adding buttons to view?

slate swan
#

yes

radiant parrot
slate swan
#

but that would break your callbacks...hmm

#

I seriously wanna ask why no subclass πŸ’€

#

but as long as it works

radiant parrot
#

what u think i do then?

slate swan
#

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

radiant parrot
#

rewrite code for me x

slate swan
#

^

radiant parrot
#

only joking haah

slate swan
#

I mean, I didn't want that you'll have to rewrite but considering what you want to do

radiant parrot
#

Yh i understand

#

Tbh only issue i fast atm is it not sending to the channel

#

When pressing approve

rare jewel
#

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")```
Gist

Walkthrough guide on subclassing HelpCommand. GitHub Gist: instantly share code, notes, and snippets.

slate swan
#

why are you following a discord.py gist for a tanjun-hikari help command

rare jewel
#

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

slate swan
#

hm, cool

#

reasons I love lightbulb-hikari πŸ˜”

rare jewel
#

Yeah lightbulb would be a lot easier…

#

I just wanted to try out tanjun cuz I already made a lightbulb bot

rare jewel
slate swan
#

got no experience with tanjun

scarlet aurora
#
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?
scarlet aurora
#

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```
paper sluice
#

hint: change the type hint

scarlet aurora
#

so user = discord.Member

rare jewel
scarlet aurora
#

?

#
        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?

paper sluice
scarlet aurora
#

how do I do that

paper sluice
#

just like you did for discord.User

scarlet aurora
#
(self, ctx, *, user: discord.User = None):```I don't wanna change it here though
paper sluice
#

why?

scarlet aurora
#

I need both

#

for the full code to work my guy

paper sluice
#

Member is a subclass of User

#

so it will work

scarlet aurora
#

discord.Member runs everything discord.User can?

radiant parrot
#

My code is all going wrong and idk why

scarlet aurora
#

is what ur saying @paper sluice ???

paper sluice
#

yea

scarlet aurora
paper sluice
radiant parrot
# scarlet aurora send code
 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

paper sluice
#
        else:
            channel_sent_in == 1018468004121542716

pithink

radiant parrot
#

even if it elif, i dnt work

vale wing
#

== is a conditional operator and the statement some_var == 1234 has literally no effect

radiant parrot
#

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)

hushed coral
#

On my pc I do not get this error, but on vps I do any ideas?

primal token
silk fulcrum
silk fulcrum
scarlet aurora
primal token
primal token
#

Because its type can be either one of those types specified?

primal token
# silk fulcrum 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.

silk fulcrum
#

πŸ—Ώ ok

vale wing
#

What editor is that

#

🧐

drifting arrow
silk fulcrum
#

in what format i mean

drifting arrow
#

coz I still think it's a likely excuse to go afk

shrewd apex
silk fulcrum
#

i can send a batch record sheet

shrewd apex
drifting arrow
#

coz im bored

drifting arrow
#

thats how..

silk fulcrum
#

but anyways i was in a tournament

shrewd apex
#

πŸ‘ u won or tournament still ongoing

primal token
#

!ot

unkempt canyonBOT
silk fulcrum
#

i just won this round

#

i have 2/3 points

shrewd apex
#

noice noice ducky_beer

drifting arrow
#

Whats the prize at the end?

errant coral
#

embed = nextcord.Embed( Error: Expected indented block It the embed that has the error.

naive briar
#

Your indentation is wrong.

errant coral
sick birch
#

What's the line above it?

errant coral
#
    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

sick birch
#

Your function is empty

#

Anything inside of the function needs to be indented

errant coral
#

ok

errant coral
vocal snow
#

see !indent if you don't know what it is

errant coral
#

!indent

unkempt canyonBOT
#

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

errant coral
vocal snow
#

and consider learning python before trying out discord.py, because it can be complicated and make things harder for you

errant coral
#

im using nextcord

vocal snow
vocal snow
shrewd apex
#

kek 2022 comeback i am using nextcord

primal token
errant coral
#

i know how to code but this error messed my mind

vocal snow
#

if you say so

paper sluice
errant coral
shrewd apex
#

prevention better than cure code carefully so that u get minimal errors pithink

errant coral
#

ok

slate swan
paper sluice
#

whats Asuna?

lethal patio
#

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?

shrewd apex
#

looks nice

slate swan
shrewd apex
#

but same question whats asuna πŸ‘€

paper sluice
vocal snow
slate swan
#

ok zeffo

vocal snow
#

i am going to have nightmares about this.

paper sluice
#

do C

shrewd apex
#

just don't sleep stay awake Β―_(ツ)_/Β―

paper sluice
#

you will feel alright πŸ˜„

shrewd apex
paper sluice
#

yup

shrewd apex
#

rip πŸ™

#

not even a string type

primal token
paper sluice
shrewd apex
#

char str[];

shrewd apex
paper sluice
# shrewd apex 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.

slate swan
shrewd apex
#

well thats not strictly oop tho struct is just at best minimal class storage

primal token
slate swan
primal token
#

If youre going to make a wrapper atleast have a unique personalized impl

slate swan
#

I'm not even making a wrapper

shrewd apex
paper sluice
#

yea, cpp aint bad, they do try their hardest to avoid pointers though

primal token
shrewd apex
#

ryuga how many languages u know now pithink

paper sluice
#

2

shrewd apex
slate swan
shrewd apex
#

it gives quite a speed boost also

paper sluice
#

yea

shrewd apex
#

direct memory address

slate swan
shrewd apex
primal token
shrewd apex
#

when did he say ptrs are hard πŸ‘€

heady citrus
#
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

primal token
paper sluice
shrewd apex
#

they do try

primal token
shrewd apex
#

bruh no ones avoiding

#

he meant in general

paper sluice
shrewd apex
#

he didn't specify anyone in particular

primal token
shrewd apex
#

πŸ˜”

paper sluice
# primal token 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

primal token
#

Yeah i would agree with them

faint sapphire
#

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'}

faint sapphire
#

btw these headers were working when i did normal requests

silk fulcrum
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

bold kernel
#

Hello, what this error mean shard id none heartbeat blocked for more than ?

errant coral
#
    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(```
primal token
bold kernel
primal token
#

!blockingio

unkempt canyonBOT
#

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!

bold kernel
#

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)

heady citrus
#

how would i make my bot update it’s status every 5 minutes

primal token
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@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").
heady citrus
#

how would i make my bot update it’s status every 5 minutes

bold kernel
# primal token Can you show your code?

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()```

primal token
heady citrus
#

@primal token

primal token
#

Its an async function, upon a calling of the function you would await its return value thats a coroutine

primal token
bold kernel
#

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 ?

gusty shard
#

is there any way to prevent my bot from getting ratelimited?

primal token
#

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

primal token
shrewd apex
shrewd apex
#

nope its sync

gusty shard
#

im changing the color of a role every 5.5sec

#

can that cause ratelimit?

primal token
shrewd apex
bold kernel
primal token
shrewd apex
primal token
bold kernel
#

this my issue, which library for async webscrapping ?

primal token
#

Its me using your info!

shrewd apex
#

πŸ™

#

okie okie

shrewd apex
bold kernel
primal token
#

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

shrewd apex
#

it's discord.ext.commands.Bot.loop.run_in_executor()

#

ie just use bot.loop.run_in

bold kernel
#

library thread?

shrewd apex
#
def foo():
    ...  # Blocking code

async def bar():
    await bot.loop.run_in_executor(None, foo)
bold kernel
#

Blocking coderefers to the main function that is looping ?

shrewd apex
primal token
shrewd apex
#

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

shrewd apex
#

so general blocking libs are pillow and requests bs4 almost all base libs python are blocking

bold kernel
shrewd apex
#

like opening and writing to a file is also blocking in such cases u should use aiofiles

shrewd apex
bold kernel
#

ohhh so it's not really a "coding error" of my person, it is "normal" that bs4 in async function blocked the heartbeat ?

primal token
# bold kernel `Blocking code`refers to the main function that is looping ?

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.

shrewd apex
shrewd apex
bold kernel
primal token
shrewd apex
#

sigh not me i meant for ppl asking the doubts if they already understood would they be asking here

toxic hornet
#

hmm

primal token
bold kernel
#

have you some links to doc ?

shrewd apex
shrewd apex
primal token
#

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

shrewd apex
bold kernel
# shrewd apex if u use requests lib its blocking yeah so use aiohttp

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

shrewd apex
bold kernel
#

coupling aiohttp to bs4 to scrape balise

primal token
bold kernel
shrewd apex
#

since if u are using bs4 here u will need a thread at some point might as well use the built in one

primal token
shrewd apex
#

thats our role isnt it πŸ˜‰

shrewd apex
primal token
# shrewd apex thats our role isnt it πŸ˜‰

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.

shrewd apex
#

fair enough everyone has their own opinions topic itself is subjective

primal token
#

Not really an opinion either.

#

Its teaching pedagogy.

shrewd apex
#

well not to shift topic but there are various teaching philosophies its not universal to follow a certain method πŸ—Ώ

primal token
#

You just defined what teaching pedagogy is?

#

Not sure what your point exactly is

shrewd apex
#

did i? thats what i said mine and urs opinions and thoughts are different

#

ok rip nvm we are deviating too off topic now πŸ’€

primal token
#

Teaching pedagogy is the use of methods, practices and concepts to use to teach, thats subjective, yes, but i wouldnt say its an opinion.

craggy haven
shrewd apex
#

wut?

craggy haven
#

i heard it was

#

or is that just a rumor

shrewd apex
#

thats old news it was for a period of time then work on it started again

#

now even 2.0.1 is out

craggy haven
shrewd apex
#

most guides are now outdated

craggy haven
#

dm me some good tutorial i gtg

#

i will look at them tmr

#

bye

shrewd apex
#

ik none as of now

craggy haven
#

lk bye

#

ok*

shrewd apex
#

πŸ‘‹

faint sapphire
#

getting this strange error

#

read_timeout=None, conn_timeout=None, timeout=sentinel
what should i set these timeouts to

vale wing
# faint sapphire getting this strange error

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

faint sapphire
#

yh, i saw a stackoverflow doing it like that, i was confused, but thought it was necessary

#

ill make the changes

sick birch
#

this is why we don't use SO for discord bots

faint sapphire
#

SO?

#

i was told to use aiohttp

#

i was using concurrent.futures before, hadnt tested it

pulsar thistle
#

guys never had such error and rn its popping up, how to fix?

'dict' object has no attribute 'Cog'```
faint sapphire
heady citrus
#
@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

slow fog
#

You must define a new function for it

#

And then start the loop within the on_ready section

faint sapphire
# faint sapphire

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)

faint sapphire
#

yh some links work and some dont

#

thats to do with aiohttp

#

:/

dark pine
#
@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?

primal token
#

and can you show cogs/point.py ?

dark pine
#

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!')

primal token
dark pine
#

but still shows the same error

primal token
#

can you show all of your code?

dark pine
dark pine
primal token
#

!paste

unkempt canyonBOT
#

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.

dark pine
#

ty

#

it works fine without this

#

this command addrole

dark pine
primal token
#

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

dark pine
#

what to use a database?

primal token
#

That whole Cog needs a rewrite tbh

dark pine
#

i have user: points

primal token
unkempt canyonBOT
dark pine
primal token
dark pine
primal token
faint sapphire
#

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

primal token
#

I wouldnt say its directly related to discord bots at all

echo cobalt
#

bot1

#

1

mossy jacinth
#

Is there any possible way to use a number as command name?

primal token
dark pine
#

how can i catch RoleNotFound error?

                except commands.errors.RoleNotFound:
                    await ctx.send('That is not a correct role!')
                    return
dark pine
# primal token ?

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

primal token
#

You arent passing a role and whats your issue on

how can i catch RoleNotFound error?

dark pine
#

i want it to get a message back

primal token
#

!d discord.ext.commands.Command.error

#

any time now

dark pine
#

?

primal token
#

The bot isnt responding for some reason

dark pine
#

:C

primal token
west escarp
#

It's offline ohno

velvet compass
#

!ping

primal token
#

Blame chris

velvet compass
#

Oh that's not good

primal token
#

freak out, ahhhhhh!!!!

dark pine
#

wahhhhhhhhhhhhhhhhh

faint sapphire
#

and in a string "1"

faint sapphire
#

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

mossy jacinth
primal token
#

!f-strings

unkempt canyonBOT
#

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.

dark pine
#

id doesnt work i get int error and role name gives me str error

primal token
#

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

sick birch
#

maybe not bad but... strange

primal token
#

congrats on your baby and being famous now!

slate swan
#

anyone help me

#

what is this?

#

turns bot on, but wont load commands

#

@full lily

full lily
dark pine
#

how can i make the bot auto give role according to points amount

cunning trellis
wary shadow
wicked atlas
slate swan
#

How do discord bots measure the MS between the time it takes to send the message

hushed galleon
#

you can time it like anything else with time.perf_counter()

#
start = time.perf_counter()
await channel.send('hello!')
elapsed = time.perf_counter() - start```
slate swan
#

perf_counter?

#

Oh πŸ™‚ Thank you.

hushed galleon
#

its a function from the time module

craggy haven
#
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
craggy haven
#

yup

#

I am new to programming'

sick birch
#

Here's some advice: don't

craggy haven
#

oh

sick birch
#

They're terrible as is evident here

#

I'm guessing this is some really badly coded ban command

craggy haven
#

unban*

#

should I send my unban command

sick birch
#

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 πŸ˜›

craggy haven
#

ok

#

can you tell me how to fix it or how to learn to make it

sick birch
#

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

unkempt canyonBOT
#

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.
craggy haven
#

do you know how to unban them using the ID instead of a username cuz they might change their name

bright wedge
#

you are trying to make an unban command?

craggy haven
#

yup

bright wedge
#

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)

slate swan
#

object has no attribute 'tree' what does this mena?

bright wedge
#
@bot.tree.command()
slate swan
#
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()
bright wedge
#

as i said

slate swan
#

I did do commands.Bot though

bright wedge
#

am sry i have many months to use discordpy :/

#

where are you getting error

#

i mean line?

slate swan
#
@Client.tree.command()
AttributeError: 'Arcade' object has no attribute 'tree'
craggy haven
#

i want to make sure what is the difference between py await ctx.channel.send("...")
and py await ctx.send("...")

bright wedge
#

as i remeber is the same thing

craggy haven
#

Ok ok thanks

bright wedge
slate swan
#

It does not work.

#

I am already using bot.

bright wedge
slate swan
#

ah

bright wedge
# slate swan ah

i have never use "tree" commands sry, im moving on js πŸ˜›

slate swan
#

Noooo

#

please help me 😭 dont move on to js

#

I still can't find any

craggy haven
#

same dont move we need help

bright wedge
#

alr

craggy haven
#
@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

bright wedge
#

am

#

try and see

#

if he cant display the member, try to move your channel.send() before the member ban

craggy haven
#

ok

sick birch
#

Also it needs to be discord.User not discord.Member because if a user is currently banned they can't be a member

craggy haven
#

oh ok

craggy haven
sick birch
#

Just use await ctx.message.delete()

naive briar
#

Use ctx.message.delete

bright wedge
craggy haven
#

whats the deletes

sick birch
#

It deletes the provided message

craggy haven
#

sorry difference*

#

ok ok

sick birch
#

Because purge is meant for deleting multiple messages at once

craggy haven
#

should I pass something or just like that

bright wedge
#

deletes the author's message

bright wedge
#

no parameters

craggy haven
#

btw @bright wedge I tried it didn't work

bright wedge
#
@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!")
craggy haven
#

ye

#

ok ok

bright wedge
#

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)?

craggy haven
#

i gtg bye see yaafter school

bright wedge
#

ahahh, take care!

slate swan
#

The Engineer is a cool man

#

how will dpy parse the member argument to a Member object

bright wedge
slate swan
#

you'll have to accept a user id or a User object

bright wedge
slate swan
bright wedge
slate swan
#

how will a banned user be a member of that particular guild

#

I need an explanation

#

not "working code"

bright wedge
#

im not here to explain, just to help

#

in my bots its working!

slate swan
#

help me understand huh

bright wedge
#

and you can try it, but not here, here is for help (feel free to dm me!)

slate swan
#

this channel is also for discussing on certain topics if they are related, so it's fine

bright wedge
#

i can prove it! but not here!

silk fulcrum
#

what a topic man

slate swan
#

no master

silk fulcrum
#

but i think the topic says that this channel is also for discussions related to bots

bright wedge
silk fulcrum
#

what!

bright wedge
slate swan
bright wedge
silk fulcrum
slate swan
slate swan
bright wedge
#

i dont got you bro sry

slate swan
bright wedge
#

you said we cant use member_id for get access in discord.Member object right?

slate swan
#

?

#

I never said that

slate swan
# bright wedge .

I said that how are you gonna get the Member object when the user isn't even in the guild

bright wedge
#

then i understand wrong

silk fulcrum
slate swan
#

like running
!unban user_id and converting that to a Member object will fail 99% of the times

vagrant brook
#

Just change it to User smh

slate swan
#

I know lol

rare echo
#

yeah use discord.User? (just got here)

silk fulcrum
vagrant brook
#

UserConverter can take ID

#

Apparently

silk fulcrum
slate swan
silk fulcrum
#

I just use Annotated[discord.BanEntry, BannedMemberConverter]

#

BannedMemberConverter is my subclass of Converter btw if some1 thought it's commands.BannedMemberConverter

austere vale
#

do replit discord bots get rate limited more than pc hosted bots?

slate swan
#

yes

slate swan
#

What is ctx?

cold sonnet
#

I just read a whole discussion about someone telling Ashley you should use discord.Memeber in an unban command

stray carbon
#

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?

bright wedge
#

reaction roles but with buttons?

naive cedar
#

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

vale wing
stray carbon
#

Omg wait nvm i can do that

vale wing
#

Yes

pulsar thistle
#

guys never had such error and rn its popping up, how to fix?

'dict' object has no attribute 'Cog'```
#

anyone could help?

unkempt canyonBOT
#

@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'
paper sluice
#

you are trying to do that

pulsar thistle
plush rock
#

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

paper sluice
pulsar thistle
maiden fable
#

@pulsar thistle you had a dict named Commands, right?

pulsar thistle
shrewd apex
#

!d discord.EmbeddedActivity

unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

shrewd apex
#

embedded activity is not even a thing

slate swan
slate swan
#

thanks

naive briar
#

attachment://billboard.png

paper sluice
#

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

faint sapphire
#

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

paper sluice
#

you were the one who pinged me, but ok

velvet sierra
#

someone know why async def X(ctx, *args): give a error?

paper sluice
#

what is the error?

slate swan
#

!e ```py
async def X(ctx, *args): ...

unkempt canyonBOT
#

@slate swan :warning: Your 3.11 eval job has completed with return code 0.

[No output]
hollow ice
#

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'

naive briar
faint sapphire
#

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()
unkempt canyonBOT
#

Hey @hollow ice!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

shrewd apex
#

imagine using event loop for an async function in an async function pithink

paper sluice
faint sapphire
#

cool thanks

#

i know it looks weird

#

kinda new with this

shrewd apex
mossy jacinth
#

Hey! My bot is sending a new question if u start the command twice and reacts to itself... Aka its talking to itself

shrewd apex
#

are u using on_message for commands?pithink

hollow ice
shrewd apex
#

nope

hollow ice
#

ok fine!

shrewd apex
mossy jacinth
slate swan
#

Hello guys

#

πŸ‘‹

shrewd apex
faint sapphire
#

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

naive briar
#

What the

light violet
#

Slash is not working with hybrid cmds

vale wing
slate swan
#

🀣lol

faint sapphire
#

lol

vale wing
#

Or you just don't understand what you are doing

#

Have you ever read asyncio docs

faint sapphire
#

yes

slate swan
#

Define asyncio

vale wing
#

The module

slate swan
#

!d asyncio

unkempt canyonBOT
#

Hello World!

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())
```...
slate swan
#

This

faint sapphire
vale wing
#

Why the heck for does he want to execute multiple coros at once

#

Why not one by one

slate swan
#

SPEED

vale wing
#

Depends

faint sapphire
#

bruh its u who doesnt know what asyncio is

slate swan
#

Nice

faint sapphire
#

itll be almost the same as doing requests if u do session.get then await res.text() for each

vale wing
#

Eh think what you want but I have developed several apps with asyncio

#

@faint sapphire one question - what exactly do you want to achieve

slate swan
#

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

vale wing
#

You need to import the commands submodule

slate swan
shrewd apex
#

if u are gonna multi thread coros u might as well just use normal function as in sync and then thread them

faint sapphire
vale wing
#

Wtf ok

vale wing
slate swan
#

im new to slash commands...

shrewd apex
#

which version of dpy are u on?

slate swan
shrewd apex
#

check once

#

which line is the error in bot.tree.command or self.tree?

slate swan
shrewd apex
#

hmm where is ur guild id for discord.Object?

slate swan
#

oh

#

how do i make it global?

vale wing
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
vale wing
#

Ok it's predefined thx god

#

@slate swan what does this print

import discord
print(discord.__version__)```
shrewd apex
slate swan
#
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 😦
cloud dawn
#

🚢

vale wing
#

This is not the latest version

#

Update with pip install -U discord.py

slate swan
#

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

shrewd apex
slate swan
#

doesnt let me update.. 😦

vale wing
#

Why the heck do you have 2.7 installed

naive briar
#

πŸ₯΄

shrewd apex
#

kek

faint sapphire
#

it updates when u ask to install

slate swan
shrewd apex
#

how are u even using 1.7.3 with 2.7 is that even supported?

slate swan
#

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

faint sapphire
#

just do pip install discord then

cloud dawn
vale wing
#

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

faint sapphire
#

maybe u dont have pip

slate swan
faint sapphire
#

ig ur computer is forbidden

cloud dawn
#

I mean duh

vale wing
#

Why did I suddenly lose my connection when panda started a conversation with me bruh

cloud dawn
#

discord.py-2.1.0a4591+gedfacb36

shrewd apex
#

2.1.0

shrewd apex
#

^^

faint sapphire
#

i thought .py was discontinued

cloud dawn
vale wing
slate swan
#

help, i have a cmd, and how do i get a reaction that is reacted on the msg that bot sent as a string,

vale wing
faint sapphire
#

n🧊

slate swan
#

literally im using python3

vale wing
slate swan
vale wing
#

I mean that's 100% gonna fix everything