#discord-bots

1 messages Β· Page 468 of 1

slate swan
#

Music bots are being shut down, making your bot TTS something is allowed.

lament mesa
#

just text to speech

maiden fable
#

@drifting arrow who says it's against ToS?

white perch
#

yeah in this one its just tts

crude crater
#

Why lol

drifting arrow
#

Then I appologize @white perch. I was mistaken.

crude crater
#

I said I don’t know but google will lmao

white perch
#

No prob

maiden fable
#

Music Bots are, but not tts

slate swan
#

Even music is allowed, as long as you don't use YouTube

drifting arrow
#

Im gonna go take a shower and when I return I'll educate myself better.

maiden fable
white perch
maiden fable
slate swan
#

You can download a music a play it in a loop if you want, you don't rely and stream directly from YouTube so yeah

maiden fable
#

Yea

crude crater
#

Also, music bots are not against TOS!!! Rythm is literally a VERIFIED BOT

maiden fable
#

Bro...

#

YouTube ToS

#

Not Discord

slate swan
#

Rythm is being shut down

white perch
#

Rythm is shutting down anyways we shouldnt discuess that here

maiden fable
#

Yea

slate swan
#

In case you didn't know

crude crater
#

Oh lmao I didn’t even know my fault

crude crater
#

Why tf is it verified then that’s dumb lmaooo

slate swan
#

Because it's YOUTUBE ToS

#

Not Discord

maiden fable
#

Isn't that what I said....?

slate swan
#

Discord never forced any bot to shut down

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
lament mesa
#

its against tos

white perch
#

Music bots are allowed if you have a legal written permission from youtube which is a 0.01% chance of anyone having written permission though

#

But anyway

slate swan
#

Well, just asking what is wrong won't help

#

Do you get any error?

lament mesa
#

Just buy YouTube and you'll be fine

slate swan
#

What do you expect, what happened, etc.

white perch
# slate swan Do you get any error?

No error, It joins the vc, sends the making audio message, it also saves the audio file but doesn't play it in vc and doesn't send the Played! text

white perch
visual island
#

guys, what python version does supports:

except A, B:
drifting arrow
visual island
drifting arrow
#

Back to my shower

lament mesa
visual island
slate swan
#

Is this an effective way to get a list for the names of all the roles in my server:

boreal ravine
slate swan
#

[i.name for i in cl.guild.roles]

white perch
#

I found outtt my mistake

#

I typoed ffmpeg

#

Btw guys

slate swan
white perch
#

Music is illegal if you use youtube

#

But is using a music api illegal?

visual island
#

oh

#

wow

white perch
#

Like you only get lyrics from the api of the song you want

slate swan
#

Again

#

Everything is based on the ToS of the service

#

We don't know what service you use, we don't know if it's allowed or not

#

Read their ToS

maiden fable
white perch
#

No, just asking in general, Ksoft shut down for legal reasons (the api rythm used before)

visual island
white perch
#

So i was just confused

gilded kite
maiden fable
#

Yes

#

Remove the ()

lament mesa
boreal ravine
#

oo wrong parentheses sorry

maiden fable
#

That's why. Gimme 2.5 billion USD and I'mma revive every music bot :D

slate swan
#

For fucks sake, finally figured out this stupid API

maiden fable
#

Which one?

slate swan
#

dude Ive been working on the same command for like a week

#

the discord one

maiden fable
#

Ok?

slate swan
#

It's literally just a self-role command

maiden fable
#

πŸ˜‚

slate swan
#

been working on this way too long

#

It's been taking me forever to figure python out ya know

maiden fable
#

Understandable

maiden fable
visual island
#

its 2020 anyways

slate swan
#

My IDE kinda lookin like a fine plate of spaghetti rn. Seasoned with just the right amount of bullshittery

#

I love Python man, It's so fun

dapper cobalt
boreal ravine
#

Can my command errors be in a separate file than the command?

spring flax
#

sure

dapper cobalt
boreal ravine
#

o ok

heavy radish
#

Hello??

#

Whats the template for Embeds??????

boreal ravine
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
sweet pilot
#

how can I get message by id?

lament mesa
#

TextChannel.fetch_message

drifting arrow
#

Time to attempt to add an api to my bot \o/

maiden fable
#

Best of Luck!

#

I added the AI API to my bot and it was a pain to implement

slate swan
#

!voiceverify

visual island
lament mesa
#

python java is cooler

boreal ravine
slate swan
#

can anyone help me with wavelink??

lament mesa
#

isnt it used to download yt vids?

dapper cobalt
lament mesa
#

i wasnt talking about that

drifting arrow
#

Neato. League of legends has an api 😼

slate swan
drifting arrow
sweet pilot
#

is it possible to get the message that a message replies to?

novel rampart
#

how can i host my bot for free

drifting arrow
novel rampart
#

any other ways

dapper cobalt
novel rampart
dapper cobalt
#

Paid and paid hosting.

novel rampart
#

mm

drifting arrow
dapper cobalt
#

Yes, it's free. Lmao.

heavy radish
#

hm

dapper cobalt
#

But I chose the paid plan because it's really good.

boreal ravine
#

KeyError: Python

heavy radish
#

Hello

#

I want to make an Embed for my help things

dapper cobalt
unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
heavy radish
#
@bot.command()
async def help(ctx):
embed = discord.Embed(
        title = 'JarvisBOT Help',
        description =
    'Prefix is $',
        color = 0x8b0000)
  await ctx.send(embed=embed)

crude skiff
#

is this channel still used for discord.pyPyc-cord

dapper cobalt
boreal ravine
heavy radish
#

Whats kwargs

boreal ravine
dapper cobalt
heavy radish
#

hm

#

Okay then

#

I'll be back soon....

boreal ravine
#

btw @heavy radish

heavy radish
#

Yes

boreal ravine
#

i think the color code is wrong

heavy radish
#

Yea, Its a copy paste

boreal ravine
#

-_-

heavy radish
#

I'll have to figure something out

#

Lol

boreal ravine
#

ok

novel rampart
#

this have no reply

boreal ravine
#

use vsc

#

good and free hosting πŸ‘

drifting arrow
#

Outside of paying or finding a free VPS, there's just hosting it yourself.

dapper cobalt
novel rampart
#

mm

#

yes

dapper cobalt
drifting arrow
# novel rampart this have no reply

At the end of the day, you get what you pay for. If you choose to go the free route, you may not get the greatest service.
Alternatively, you'll have to host the bot yourself (simply run it on your computer or some other device.)

If you do decide to pay out 5 bucks a month, there's some decent options available.

dapper cobalt
#

I paid only $3 to this host and it isn't even monthly, it's once a lifetime.

drifting arrow
#

For me right now, I am contemplating getting a go-daddy VPS. since I already have my website hosted through them.

lament mesa
drifting arrow
#

rito games made me read all their TOS for using their api only for it to essentially say 'Be good. dont break shit you lil' shit.'

novel rampart
#

did i can host on heroqu

slate swan
#

You can, it's just not recommended

#

Heroku is not made to host Discord bots

novel rampart
#

but

drifting arrow
novel rampart
#

the youtube videos on it have

dapper cobalt
drifting arrow
dapper cobalt
novel rampart
slate swan
#

Again, it's not recommended

slate swan
#

Why do you ask us if you're so sure you want to host it there when we say it's not a good plat

novel rampart
drifting arrow
#

@novel rampart Just because he uses it, doesn't mean you should. Not every hosting service is ideal for your needs. For example, some hosting services require you to use UBUNTU or LINUX. I dont have those, and therefore i cant use them. despite wanting to coz of their prices.

slate swan
#

Now choose whatever you want to do.

novel rampart
#

mm

slate swan
#

You should not use Heroku to host your bot.

  • Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.

  • Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.

  • Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.

  • Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)

  • Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.

novel rampart
slate swan
#

Enjoy the reasons on why not to use Heroku

novel rampart
#

for free

sweet merlin
#

i want to make a command run like this
!download AWebsite
so i can automate it by using discord

dapper cobalt
slate swan
novel rampart
dapper cobalt
slate swan
drifting arrow
#

@novel rampart just listen to these smart people and they'll do you aight. i been here for like 2 weeks now and they dont lead a man astray

novel rampart
slate swan
#

Then ask there

dapper cobalt
slate swan
#

Not here

novel rampart
sleek kindle
#

πŸ™

novel rampart
sleek kindle
#

buy it?

#

*from dpy server

drifting arrow
#

remove embeds

lament mesa
drifting arrow
#

why wont the embeds get removed?

sleek kindle
#

nono I was removing it so editing it again and again got back the embeds

untold token
#

Hosting service?

ocean leaf
#

any mistake?

untold token
#

Is there even any by the name of vsc?

drifting arrow
untold token
untold token
ocean leaf
untold token
#

But they are taking about hosting service

drifting arrow
#

Take code -> open in vsc -> click run

ocean leaf
untold token
#

That's just running the code, not really hosting it

ocean leaf
#

not even any error

drifting arrow
boreal ravine
boreal ravine
ocean leaf
boreal ravine
drifting arrow
boreal ravine
#

!indents

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

untold token
boreal ravine
untold token
#

And you wrote
{member}

ocean leaf
boreal ravine
#

why??

untold token
#

Which will send the whole member object

#

do str(member)

#

If you want the name / tag

ocean leaf
#

i made it and i forgot about it

#

member.avatar_url will work

boreal ravine
#

@ocean leaf remove the variable

ocean leaf
boreal ravine
#

also why make on_message events for commands?

untold token
#

f'Avatar of member {member}`
Will send the whole member object

#

@ocean leaf

#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
drifting arrow
#

i typed it out myself. ty for not posting code @ocean leaf =.=

slate swan
#

It will send the username#tag

boreal ravine
#

yes

untold token
slate swan
#

Wouldn't

boreal ravine
#

no it would just send the member's name

slate swan
#

No

untold token
#

ctx.author would send the whole member object

slate swan
#

Username#tag

slate swan
untold token
#

You need to do str(member)

#

To get username and tag?

slate swan
#

It's already in a string

untold token
#

ctx.author doesn't return a string

maiden fable
#

It returns the discord.Member object

untold token
#

It returns a member object

ocean leaf
untold token
#

Yes

maiden fable
#

Or discord.User if the command is invoked in DMs

untold token
#

!d discord.ext.commands.Context.author

unkempt canyonBOT
ocean leaf
drifting arrow
#

I like to run the code to test it

untold token
#

Yes this will work

#

But try it and see

ocean leaf
#

ok

#

disn't work

slate swan
#

If u put it inside an f-string it does

untold token
#

It returns a Member object not a string

slate swan
ocean leaf
#

oh

#

it actually works right?

maiden fable
unkempt canyonBOT
lament mesa
#

putting an object inside f-string will call object.__str__

slate swan
#

^

maiden fable
#

Yes

untold token
#

Oh yeah

maiden fable
#

So u can also do str(ctx.author)

untold token
#

it would call the str dunder method

ocean leaf
untold token
drifting arrow
#

@ocean leaf

@bot.command()
async def avatar(ctx, *, member: discord.Member):
    userAvatar = member.avatar_url

    embed = discord.Embed(color = member.color, timestamp = ctx.message.created_at)
    embed.set_author(name = f'Avatar of {member}')
    embed.set_image(url = userAvatar)
    embed.set_footer(text = f'REquested by {ctx.author}', icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

this works for me

ocean leaf
drifting arrow
#

Change @raven peak to @client.command()

ocean leaf
#

yes ik

untold token
#

Lol

drifting arrow
#

cool

ocean leaf
#

StIlL DiDnT WoWk

untold token
#

What

drifting arrow
#

What is the expected outcome?

ocean leaf
untold token
#

Wdym empty

ocean leaf
ocean leaf
drifting arrow
#

Your bot is online. run the command on discord.

ocean leaf
#

dosen't work nothing happens

slate swan
#

Do u have an on_message event

drifting arrow
#

just out of curiosity.. do you have

from discord.ext import commands
```?
untold token
#

Are you running the correct bot token?

ocean leaf
untold token
drifting arrow
drifting arrow
maiden fable
maiden fable
untold token
#

do you have any bare on_message event

ocean leaf
untold token
#

Show it

slate swan
#

Do u have process_commands at the end of it

untold token
#

I bet you didn't call process_commands

#

In it

ocean leaf
untold token
#

Or better

slate swan
#

!d discord.ext.commands.Bot.process_commands

untold token
#

Yup

unkempt canyonBOT
#

await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
slate swan
#

Add that at the bottom of your on_message

untold token
#

Or better, use .listen()

slate swan
#

^

untold token
#

@client.listen()

#

You don't need to call process_commands

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").

Example...
ocean leaf
untold token
#

Hmm

ocean leaf
#

with what i have to use .listen? client.listen?

untold token
#

@client.listen()

#

You need the parentheses and it's a decorator

ocean leaf
#

under all on_message commands?

untold token
#

How many do you have

ocean leaf
untold token
#

And yes, if you have multiple on_message events then use .listen()

ocean leaf
#

bellow all?

untold token
#

It's a decorator

#

So

#
@client.listen()
async def on_message(message):
  ... 
#

Like this

ocean leaf
#

ok

#

without brackets?

untold token
#

It's an external event listener, so you have multiple event listeners of same type, it would work asynchronously and will.not block other events and commands

untold token
ocean leaf
frosty prairie
#

i tried editing a embedded message but it gave this errror.. i tried same type of file but it sends the file at first but when editing it gives this error

untold token
#

Okay

steep estuary
#

anyone pls help me i have a variable and i want that its value should me different for all servers

#

how i can do that

untold token
#

Code?

lament mesa
#

Have a dictionary and have the guild id as a key

frosty prairie
#

..

ocean leaf
#

really?

lament mesa
untold token
ocean leaf
frosty prairie
#

i tried editing a embedded message but it gave this errror.. i tried same type of file but it sends the file at first but when editing it gives this error

#

..

untold token
#

Because if you are using d.py 2.0

ocean leaf
#

how can i check?

untold token
#

Use member.avatar.url

dapper cobalt
frosty prairie
#

.

untold token
#

discord.__version__

steep estuary
untold token
dapper cobalt
ocean leaf
#

how to check

frosty prairie
untold token
#

Print that

drifting arrow
#

back

#

we still working with @ocean leaf ? πŸ€”

ocean leaf
untold token
#

Lol they are using d.py 2.0

frosty prairie
boreal ravine
frosty prairie
#

..help

#

mhm

drifting arrow
ocean leaf
untold token
#

See

#

That's why

boreal ravine
frosty prairie
# untold token Code?
embed = discord.Embed(title=f"{str(ctx.author)}'s new cards", description=f'You have successfully created a profile, **{name[0:-5]}**\nYou got a {card1} of {choose} and {card2} of {choose2}')
            embed.set_image(url=f'attachment://{card_name1}.png')
            file = discord.File(f'C:/Users/ogtla/OneDrive/Desktop/python/cogs/{card_name1}.png')

            message = await ctx.send(embed=embed, file=file)
            await message.add_reaction(':rewind:')
            await message.add_reaction(':fast_forward:')

            def check(reaction, user):
                return reaction.emoji == ':fast_forward:' or reaction.emoji == ':rewind:' and user == ctx.author

            react = await self.bot.wait_for('reaction_add', check=check)
            embed2 = discord.Embed(title=f"{str(ctx.author)}'s new cards", description=f'You have successfully created a profile, **{name[0:-5]}**\nYou got a {card1} of {choose} and {card2} of {choose2}')

            embed2.set_image(url=f'attachment://{card_name1}.png')
            file2 = discord.File(f'C:/Users/ogtla/OneDrive/Desktop/python/cogs/{card_name1}.png')
            await message.edit(embed=embed2, file=file2)
ocean leaf
#

member.avatar.url

drifting arrow
#

are you using commands.client or commands.bot? idk if it makes a difference but I am using commands.bot

frosty prairie
#

..

untold token
ocean leaf
#

ok

steep estuary
#

anyone pls help me i have a variable and i want that its value should me different for all servers
how i can do that i learnt python properly also oop but i am confused in discord.py

hasty iron
#

avatar can be None if they have the default one

boreal ravine
hasty iron
#

use display_avatar instead

lament mesa
untold token
#

display_avatar? hmm)

untold token
#

Sed

hasty iron
#

the bot doesn’t have 2.0 docs

steep estuary
lament mesa
#

what?

#

I just sent how to do it

steep estuary
#

to make different values?

ocean leaf
#

it worked

#

thanks

lament mesa
steep estuary
#

like i have a variable giveawayStatus

#

if someone start giveaway

#

its value changes to true

#

but in other servers also

#

😦

lament mesa
#

bruh, i literally said what to do

hasty iron
#

dont use a dict, use a database instead

lament mesa
#

No.

hasty iron
#

json isnt a db

steep estuary
#

yes

lament mesa
drifting arrow
#

a json file can pretend to be a database tho πŸ˜‰

hasty iron
#

no it cant

drifting arrow
#

Lol

untold token
#

If you use json as a db, you would deal with more issues that good

lament mesa
#

its mostly used to send data throughout the web

drifting arrow
#

If you're willing to put the work in, you can use a json file as a database. wont be very good but it will work

steep estuary
#

how to create and use a db?

drifting arrow
shy schooner
#
Traceback (most recent call last):
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "d:\Coding\Python\Discord.py\Economy Bot\economy.py", line 70, in on_command_error
    raise error
TypeError: exceptions must derive from BaseException

when i run any command it shows this error, which is triggered by the error handler

steep estuary
#

this will work pls tell??

#

no

#

wait i am trying

hasty iron
#

you’re probably overriding error somewhere

drifting arrow
#

I prefer to have the code, run it. Fiddle with it and if I can get it to work, send the revised code.

steep estuary
#

here it checks the value (pls ignore the variable names)

hasty iron
#

you should definitely use a database

steep estuary
#

it is looking easy

hasty iron
#

what

drifting arrow
hasty iron
#

that’s not a database

shy schooner
# hasty iron send your code
@client.event
async def on_command_error(error, ctx):
    if isinstance(error, commands.CommandOnCooldown):
        cooldown_emb = discord.Embed(title="Hey, you are on a cooldown", description='Please try again in {:.2f}'.format(error.retry_after))
        cooldown_emb.set_author(name=ctx.author.name, icon_url=f'{ctx.author.avatar_url}')
        await ctx.send(embed=cooldown_emb)
    elif isinstance(error, commands.CommandNotFound):
        pass
    else:
        raise error
    

here

shy schooner
steep estuary
#

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

drifting arrow
#

@shy schooner Always remember:
if it's a top level function (not a cog or in class), ctx is always first.
If it's a lower level function (in a cog or in a class), self then ctx

hasty iron
#

what is "share my whole class"

steep estuary
hasty iron
#

oh man

#

globals inside a class?

#

sounds like you lack knowledge

steep estuary
#

i know how to use class

hasty iron
#

you clearly don’t

steep estuary
#

i have no idea

hasty iron
#

???

#

it’s the same??

steep estuary
#

no

hasty iron
#

it’s still python

steep estuary
#

:/

hasty iron
#

what

drifting arrow
#

@steep estuary you arent referencing your functions in your class to be 'self'

hasty iron
#

a cog is a class

#

what do you think it is

drifting arrow
#
async def gstart(ctx ...)

could be

async def gstart(self, ctx ...)
steep estuary
#

than it worked

steep estuary
#

with self

hasty iron
#

because you aren’t inheriting from Cog

#

please lear how to use classes and cogs

#

learn*

steep estuary
frosty prairie
hasty iron
#

cogs are classes

steep estuary
#

wht

#

πŸ˜₯

drifting arrow
#

I can send you my example cog code if you want @steep estuary

hasty iron
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
hasty iron
#

thats a class

#

you clearly can see class

steep estuary
#

aa i never heard about in it python

#

also i search codes

hasty iron
#

you clearly lack python knowledge

#

you should go learn some OOP

steep estuary
#

i watched some tutorials of python oop atleast 3-4 tutorials

#

they didn't explained that

hasty iron
#

and yet you still don’t know what you’re doing

#

!resources

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.

frosty prairie
#

..

frosty prairie
lament mesa
lament mesa
steep estuary
#

:(

frosty prairie
#

:/

valid galleon
#

so i deployed my bot to heroku, and when i run it, it doesnt come online. i have no errors in my code, and it runs fine when executed in the IDE. how do i fix this?

hasty iron
#

by not using heroku

valid galleon
hasty iron
#

heroku is not for discord bots

#

heroku is for web applications

valid galleon
#

free

hasty iron
#

and also we are not heroku support

valid galleon
#

can you recommend any other free hosting service?

hasty iron
#

there aren’t

#

buy a vps or self host

lament mesa
steep estuary
#

:(

lament mesa
#

?

steep estuary
#

i think i should delete the class and code it again

lament mesa
#

why sad face

slate swan
#

how do i set a custom attribute to the Context class when a command is called? im trying to make a queue for my soundboard

ocean leaf
#

how do i send a message in a channel by just knowing the channel id?

normal bison
#

pls bal

slate swan
slate swan
normal bison
#

what bots are here?

slate swan
normal bison
#

i want to code turtle graphics... how do i do that

#

on python 3

#

i want help

normal bison
#

thx @slate swan

slate swan
#

yes

sweet merlin
#

how do i make command from different files?
like
1st file is for making bot online and listening to 2nd file

drifting arrow
#

if the bots rise against us, you'll be the first to go

sweet merlin
#

i see some people use it for multi process(?)

drifting arrow
#

This is the main loader/unloader for cogs in the main script.```py
#Loads the cogs
@bot.command()
@commands.is_owner()
async def load(ctx, extension):
bot.load_extension(f'cogs.{extension}')

@bot.command()
@commands.is_owner()
async def unload(ctx, extension):
bot.unload_extension(f'cogs.{extension}')

@bot.command()
@commands.is_owner()
async def reload(ctx, extension):
extension = extension.lower()
bot.unload_extension(f'cogs.{extension}')
time.sleep(1)
bot.load_extension(f'cogs.{extension}')
actx.send(f'Reloaded {extension}')

for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')

Your cog.
```py
class MyExample(commands.Cog):
  stuff for a class here.

def setup(client):
    client.add_cog(MyExample(client))
drifting arrow
# sweet merlin ya how do i make that

The first block of code is your main discord bot code.
The first 3 functions allow you to manually load, reload, and unload a cog.

The loop is to essentially auto load them so you dont have to.

The second block of code is your cog. A class of commands specific to that cog. You're grouping commands so you dont have a big ol' mess.

#

You turn this:

#

into this:

sweet merlin
#

thankyouu

drifting arrow
#

OH RIGHT this reminds me. need to educate myself on TTS

frosty prairie
#
    message = await ctx.send(file=discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\king_of_diamonds.png'))
    await message.add_reaction('πŸ€™')
    def check(reaction, user):
        return reaction.emoji == "πŸ€™", user == ctx.author


    msg = await bot.wait_for('reaction_add', check=check)
    embed2= discord.Embed(title='bye')
    await message.edit(file=discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\red_joker.png'))

why it gives this error :/
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type File is not JSON serializable

sweet merlin
drifting arrow
frosty prairie
#

..

lament mesa
#

not a string

frosty prairie
lament mesa
#

Because you need to pass in a file like object

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
lament mesa
#

try discord.File(open(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\red_joker.png'))

vocal magnet
#

Poor @small crown

dusk pumice
#

ahhh

#

oh my

vocal magnet
#

Lol that ninja edit

drifting arrow
#

code mostly works until this line:

await message.edit(file=discord.File(r'C:/Users/[My Name]/Desktop/example2.png'))
``` 😦
#

Nobody saw my original message πŸ˜‰

frosty prairie
#

..

#

it still givin same error

cyan bay
#

hey so basically i want my bot to be able to edit the messages that he posted

#

so for example, if my bot said something like "ello wassup", i want him to be able to edit it to say something like "hello wassup"

thorny flint
#

HelloHi,
how to ignore " when typing a command where " might include`?
discord.ext.commands.errors.UnexpectedQuoteError: Unexpected quote mark, '"', in non-quoted string

dapper cobalt
unkempt canyonBOT
#

await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
cyan bay
thorny flint
frosty prairie
cyan bay
dapper cobalt
waxen granite
#

Can we load/unload cogs for specific guilds?

dapper cobalt
cyan bay
#

also, can you delete certain words in a sentence?

#

if so, how?

dapper cobalt
#

What do you mean?

frosty prairie
#

huh?

#

..

cyan bay
#

cause in my bot, i dont know what the message is gonna be until runtime, sooooooooooooo the edit thingy wont really work

dapper cobalt
#

What message?

#

Can you show your code, please?

cyan bay
#

ok so basically im making it so that if i say a command

#

the bot prints out the words after the command

dapper cobalt
#

str.replace()

cyan bay
#

so if the command is "imitate", if i type "imitate hello", it shuld print out "hello"

dapper cobalt
#

!e

text = "hello scoopy"
text = text.replace("scoopy", "")
print(text)
unkempt canyonBOT
#

@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.

hello 
frosty prairie
#

:/ what to do

cyan bay
#

ohhh, ty

drifting arrow
stark bobcat
#

hi

drifting arrow
#

Unless πŸ€”

frosty prairie
#

unless???

drifting arrow
#

Hold up. my internet decided to say no to me.

frosty prairie
#

..

stark bobcat
#

how do i print the reaction user has reacted

drifting arrow
#

I'll do a thing and get back to you.

frosty prairie
#

aightt

stark bobcat
#
@bot.event
async def on_message(message: discord.Message):
  if message.guild is None and not message.author.bot:
    print(message.content)  
    print(message.author)

    embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
  
    a=await message.author.send(embed=embed)
    await a.add_reaction('\u2705')
    await a.add_reaction('\U0001f6ab')

    def check(reaction, user):
      return user == message.author and str(reaction.emoji) == ['\u2705','\U0001f6ab']```
dapper cobalt
stark bobcat
dapper cobalt
#

reaction.emoji.

#

!d discord.Reaction.emoji

unkempt canyonBOT
frosty prairie
stark bobcat
frosty prairie
stark bobcat
#

will reaction.emoji be enough

#
   def check(reaction, user):
      return user == message.author and str(reaction.emoji) == ['\u2705','\U0001f6ab']```
#

or also must use check

#

@dapper cobalt

lone aurora
#

Are there any examples of tempmute commands?

unkempt canyonBOT
#
Bad argument

Unable to convert 'temmute' to valid command, tag, or Cog.

lament mesa
#

!src mute

unkempt canyonBOT
#
Command: tempmute

Temporarily mute a user for the given reason and duration.

Source Code
keen talon
drifting arrow
#

@frosty prairie i give up. 😦 i cant figure it out

#

I have fail D:

#

I shall go and repent while listening to Taylor Swift

frosty prairie
drifting arrow
#

is what I was trying to do

#

but i havent got the brainstems to figure out how.

dapper cobalt
frosty prairie
frosty prairie
drifting arrow
frosty prairie
sick talon
#

hello
I am making help command in cogs
There are no error popping in the console but the bot isnt responding to the fl.help <command> type commands

frosty prairie
#

..

sick talon
#

hello
I am making help command in cogs
There are no error popping in the console but the bot isnt responding to the fl.help <command> type commands

This is my code for the one the fl.help <command> type command

  #Help mute command
  @help.command()
  async def mute(self, ctx):
    em10 = discord.Embed(title="Mute πŸ”‡", description="A mute command through which the admin,mods of the the server can mute the server members\n**NOTE**:- This command requires you to have a admin or mod role to use it")
    em10.add_field(name="**Syntax**", value="`fl.mute <mention>`")
    await ctx.send(embed=em10)
frosty prairie
sick talon
frosty prairie
#

ight

calm vortex
sleek ore
#

and str(reaction.emoji) == ['\u2705','\U0001f6ab'] is wrong

#

to check if a string is in a list, you use the in keyword

#

str(reaction.emoji) in ['\u2705','\U0001f6ab']

stark bobcat
sleek ore
#

wait

#

you haven't add the await bot.wait_for()

#

hmm

#

this is a sample for it

id_correct = user.id == turn.id
emoji_correct = str(reaction.emoji) in (nagant_str, "❌")
reaction_correct = reaction.message.id == react_message.id
reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: id_correct and emoji_correct and reaction_correct)), timeout=150.0)```
stark bobcat
#

hm

sleek ore
#

if not the bot won't actually wait for a reaction to be added

stark bobcat
#

hmm ok

stark bobcat
#

the bot alrdy has the reactions added

#

i want to print the reaction the user reacted on

sleek ore
#

yeah... you need await client.wait_for for that

#

client.wait_for is to "read" what the user reacts

willow vine
#

how to make command.has_roles work for more than one role

sleek ore
#

add_reaction is to add the reaction

lament mesa
unkempt canyonBOT
#

discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
willow vine
#

thanks

boreal ravine
#

How do i fetch a users' avatar?

#

Like I want the link to be https://cdn.discordapp.com/avatars/656073353215344650/c82b734a7e7c1eb6bea0086e6400d344.png?size=128 and not https://cdn.discordapp.com/avatars/656073353215344650/c82b734a7e7c1eb6bea0086e6400d344.webp?size=1024

steep estuary
#

how i can purge messages for only specified user?

boreal ravine
#

hmmm

boreal ravine
#

no the 1st one is png and the 2nd one is webp

steep estuary
boreal ravine
steep estuary
#

k

boreal ravine
#

"k"

#

πŸ˜‚

steep estuary
#

:/

boreal ravine
night onyx
#

Please tell me how to put slash command in a group like
Music
Slash command related to music

boreal ravine
#

yes i'm using an api and it doesn't work with .webp only .png

steep estuary
#

i want to purge messages of a particular specified user :/

boreal ravine
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages
steep estuary
#

check = ctx.auhor for ex?

tardy swallow
#

I have a problem, basically my slash command works well but every time i use it the bot sends an error message that only the author can see. It's just a message but is there any way to fix that

boreal ravine
#

idrk lmfao

#

hmm

#

btw what does c82b734a7e7c1eb6bea0086e6400d344 mean?

surreal dust
#

hey there i want to make a bot which will react on every message on the server

#

how do i?

surreal dust
#

people read messages after half an hour

#

how

#

api abuse

#

he isnt spamming or pinging

boreal ravine
#

he?

boreal ravine
#

thats api abooz

surreal dust
night onyx
#

Please tell me how to put slash command in a group like
Music
Slash command related to music

boreal ravine
#

theres a reason why you can only change ur pfp twice per hour

surreal dust
#

no man it wont please hep

#

help*

boreal ravine
#

yeah I've seen someone getting API banned when he hit 25k requests

#

😬

surreal dust
tardy swallow
#

there is some on reaction thing, just find it yourself in docs

boreal ravine
#

adding a reaction adds one request right?

#

I think? Not sure

surreal dust
#

so i dont want reaction

#

i want just a message saying stay active

boreal ravine
#
while True:
  print('hey yall stay alive')
  other stuff
surreal dust
#

okay

steep estuary
surreal dust
#

i only want it to be sent when someone comes online to send a message

tardy swallow
#

so is there any solution to my problem? slash command, everything works well but bot sends an error message that only author can see, I want to get rid of that somehow :o

surreal dust
#

whenever a person sends a message

boreal ravine
surreal dust
#

ok how do we detect spam

boreal ravine
#

@bitter depot mod

bitter depot
#

!warn 762007641455067169 You've been told that this is classed as API abuse and not something we can help with here, so please stop asking and trying to find ways to get around it.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied warning to @surreal dust.

boreal ravine
surreal dust
#

and you just

boreal ravine
#

wut

surreal dust
#

warn me uselessly

boreal ravine
#

hes doing his job as discord moderator πŸ‘

bitter depot
#

!custom-cooldown You can use a custom cooldown for detecting spam, depending on your definition of spam @surreal dust

unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

surreal dust
#

ohok thanks

slate swan
#

anyone uses SNEKBOX?

surreal dust
#

wait a minute let me try

bitter depot
#

But you wouldn't want to be sending a message every time a message gets sent, because that's just going to get your bot banned for API abuse @surreal dust

surreal dust
#

ohok

bitter depot
slate swan
bitter depot
#

if ... you need help with it then you should ask in #dev-contrib

slate swan
#

k ty

tardy swallow
#

every time I execute a slash command it works but the bot says it failed. is it possible to fix that or disable these automatic error messages?

heavy radish
#

How do I code the uptime??

lone aurora
#

How do i put an emoji like im making

emoji = 'emoji'
await message.add_reaction(emoji)

#

what will i put in emoji =

boreal ravine
#

How do I convert png images on discord to webp?

boreal ravine
lone aurora
#

i mean its a command none the less

boreal ravine
lone aurora
#

can always check if it works

boreal ravine
#

no its a slash command

boreal ravine
lone aurora
#

how do i make an if condition of

if message is in a certain channel

#

@spring flax sorry for the ping but u prolly know this so can u help me ._.

spring flax
lone aurora
#

So like lets say

channel = general
so IF there is a message in the channel GENERAL then the bot will react with an emoji

spring flax
#

i probably do not have time now, someone else would help i assume but if not will do once I have time

lone aurora
#

Al righty, thanks for checking on it though

spring flax
#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have `read_message_history` permissions to use this.

Examples

Usage...
spring flax
#

uh if i got what you said correctly this might help

spring flax
lone aurora
#

yes what would be the if statement

#

just

if == message.in channel``` will this work?
#

if i make a channel = client.get_channel()

lone aurora
#

welp there's my question, how do i make if = message.in channel statement

hasty iron
#

what even is that

lone aurora
#

i want to add a reaction if a message is in a certain channel

drifting arrow
#

So I got this code:

@bot.command()
async def build_deck(ctx):
    category = get(ctx.guild.categories, name = "deckbuilder")
    await ctx.guild.create_text_channel("CHANNEL_NAME", category=category)

How would I make it so that specific channel is only viewable by specific people? sorta like how the ticketsbot does it

#

Can discordpy create threads?

#

πŸ€”

hasty iron
#

2.0 yes

drifting arrow
#

How do I check what discordpy im using? i assume i am using latest. but to confirm

drifting arrow
hasty iron
#

how what

#

if you're asking about how to install it

#

you first need to install git

#

and then pip install git+<github url>

#

or you could git clone the repo

#

cd into it and execute setup.py

drifting arrow
#

No i meant, how do to discordthreads with discordpy

hasty iron
#

you need 2.0

drifting arrow
#

alright

#

assume i have it.

hasty iron
#

i just told you how to install it

#

its not on pypi

drifting arrow
#

Whats the github url for discordpy 2.0?

hasty iron
#

its the master branch

drifting arrow
#

oh i probs have the latest version of discord.py then

#

since i started like a week ago.
I did pip install discord.py

hasty iron
#

and for creating a thread you need Message.create_thread or TextChannel.create_thread

#

as i said, its not on pypi

#

you can only install it through git

#

pip install discord.py this fetches it via pypi

drifting arrow
#

aight

#

i got the new 2.0 one. is it the same imports? or how do I import it into my code?

hasty iron
#

its just a new version

hasty iron
gloomy coral
#

Why is this error coming? ```
@commands.Cog.listener()
async def on_ready(self):
global startTime
startTime = time.time()

#create a command in the cog
@commands.command(name='Uptime',aliases=['uptime','onlinetime'])
async def _uptime(self,ctx):
    global startTime
    # what this is doing is creating a variable called 'uptime' and assigning it
    # a string value based off calling a time.time() snapshot now, and subtracting
    # the global from earlier
    uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
    await ctx.send(embed=discord.Embed(title=f"Chad has been online for:",description=f"{uptime}:zo_tick_anim:",color=discord.Color.random()))
hasty iron
gloomy coral
#

shows starttime not defined

hasty iron
#

because you're using global

#

learn how to use class attributes

gloomy coral
#

uhhhh then wht can i do?

waxen granite
#

futuredate = message.created_at + timedelta(seconds = timeremaining)
how can i convert futuredate in seconds?

hasty iron
#

futuredate.total_seconds()?

waxen granite
hasty iron
#

oh right

#

what do you want exactly

#

cuz there is datetime.seconds

#

are you trying to store it?

lament mesa
#

its timedelta.total_seconds iirc

hasty iron
#

yeah

grim oar
#

!d datetime.timedelta.total_seconds

unkempt canyonBOT
#

timedelta.total_seconds()```
Return the total number of seconds contained in the duration. Equivalent to `td / timedelta(seconds=1)`. For interval units other than seconds, use the division form directly (e.g. `td / timedelta(microseconds=1)`).

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

New in version 3.2.
grim oar
#

See I told you

brisk helm
hasty iron
#

if they want to store it, they could store its timestamp

heavy radish
#

Why am I getting this error?

hasty iron
#

its pretty clear

#

your bot object doesnt have an attribute called launch

#

and that's probably copied code, so stop copying code

gloomy coral
hasty iron
#

learn how to use class attributes

lament mesa
#

instance attributes

waxen granite
#

x = datetime.datetime.utcnow() futuredate = message.created_at + timedelta(seconds = timeremaining)
i have these 2 objs, now i am trying to do is send a msg before 15 mins than futuretime

lament mesa
#

futuredate - timedelta(minutes=15)

gloomy coral
lament mesa
#

!e ```py
import datetime as dt

class Foo:
def init(self):
self.time = dt.datetime.utcnow()

def foo(self):
    print(self.time)

foo = Foo()
foo.foo()``` mhm

unkempt canyonBOT
#

@lament mesa :white_check_mark: Your eval job has completed with return code 0.

2021-09-13 11:28:10.596614
lament mesa
#
class Foo:
    x = 10 # class attribute
    
    def __init__(self):
        self.y = 20 # instance attribute

Foo.x
>>> 10
Foo.y # Not initialized
>>> AttributeError
Foo().y
>>> 20```
winter jetty
#

Hey guys, i'm trying to turn the binary from gateway.discord.gg to human readable format

#

I've tried a bunch of stuff, but have no idea how to do this

#

b'\xc2\x1b\x1a86\x83\x91\xd7\xe6\xa2\xee\xcc\xc1h\x911Zd\xd0\xad\xc8\x00\x00\x00\x00\xff\xff'

#

An example of binary received

hasty iron
#
# Z_SYNC_FLUSH suffix
ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()

# ...
def on_websocket_message(msg):
  # always push the message data to your cache
  buffer.extend(msg)

  # check if the last four bytes are equal to ZLIB_SUFFIX
  if len(msg) < 4 or msg[-4:] != ZLIB_SUFFIX:
    return

  # if the message *does* end with ZLIB_SUFFIX,
  # get the full message by decompressing the buffers
  # NOTE: the message is utf-8 encoded.
  msg = inflator.decompress(buffer)
  buffer = bytearray()

  # here you can treat `msg` as either JSON or ETF encoded,
  # depending on your `encoding` param
#

an example from docs

winter jetty
#

I've read through those docs too, but I don't understand this

hasty iron
#

this is how dpy does it

        if type(msg) is bytes:
            self._buffer.extend(msg)

            if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff':
                return
            msg = self._zlib.decompress(self._buffer)
            msg = msg.decode('utf-8')
            self._buffer = bytearray()
``` `self._zlib` is just an instance of `zlib.decompressobj()`
winter jetty
hasty iron
#

and then you json.loads the msg

winter jetty
#

Is the error i'm getting

hasty iron
#

you need to decompress the bytes

winter jetty
hasty iron
#

using that method

winter jetty
# hasty iron you need to decompress the bytes

i've compressed it now.

import zlib


ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()

to_decode = b'\xc2\x1b\x1a86\x83\x91\xd7\xe6\xa2\xee\xcc\xc1h\x911Zd\xd0\xad\xc8\x00\x00\x00\x00\xff\xff'
buffer.extend(to_decode)
print(inflator.decompress(buffer))

The error:

Traceback (most recent call last):
  File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 52, in <module>
    asyncio.run(go())
  File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 42, in go
    print(inflator.decompress(buffer))
zlib.error: Error -3 while decompressing data: unknown compression method
hasty iron
#
            if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff':
                return
``` you need to check this too
#

oh wait, its correct

spring flax
lone aurora
#

ahh i see thanks

#

diabolical stonks

#

they increased the msg delay on this channel ._.

waxen granite
#
                    if x >= earlyrem:
                        earlymsg = await message.reply(f"**The event will start in 15 minutes.**")
                        print("First reminder has been sent.")
                        earlymsgtime = message.created_at
                    if earlymsgtime >= x <= futuredate:
                        pass                        
                    if x >= futuredate:  # timer for event reminder
                        await message.reply("**The event has started.**")```
it spams for `if x>= earlyrem` how can i make it send once and then wait for futuredate?
wispy sequoia
#

I want to make a battle command

#

how to get the avatar url?

#

I know it's avatar_url

spring flax
#

!d discord.Member.avatar_url

unkempt canyonBOT
#

avatar_url```
Equivalent to [`User.avatar_url`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.avatar_url "discord.User.avatar_url")
wispy sequoia
#

but it's not working

spring flax
#

what is your code

slate swan
wispy sequoia
#

no

slate swan
#

make sure intents and not discord py 2.0

#

for 2.0 its avatar.url

sweet herald
#

hey guys, so i want to have a timer in a discord channel, what would be the best way to go about doing that
it could be updating on a minute basis

wispy sequoia
# spring flax what is your code
@client.command()
async def battle(ctx, member: commands.MemberConverter):
    yourAvatar = ctx.author.avatar_url
    memberAvatar = member.avatar_url
    await ctx.send(f"{yourAvatar} {memberAvatar}")```
wispy sequoia
spring flax
#
member : discord.Member``` you can typehint to that
wispy sequoia
#

no

#

I prefer MemberConverter

wispy sequoia
unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
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/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
fading harness
#

hey

#

how can i repeat forever in python?

slate swan
wispy sequoia
#

is it possible to set 2 images in an embed?

slate swan
wispy sequoia
#

sad

#

what I want to do is make a battle command that shows the avatars of the 2 fighters

#

in 1 embed

wispy sequoia
#

it's ugly

maiden fable
#

Or PIL

wispy sequoia
maiden fable
#

To merge the two images

wispy sequoia
#

TELL HOW

slate swan
#

!pypi Pillow

unkempt canyonBOT
maiden fable
#

Ah yea pillow. My bad

wispy sequoia
#

it gives an url

maiden fable
#

Ah yea

wispy sequoia
#

do I keep it url or do I need to save it?

maiden fable
#

!d discord.Asset

unkempt canyonBOT
#

class discord.Asset```
Represents a CDN asset on Discord...
maiden fable
#

U can save it with this

wispy sequoia
#

ok but

lament mesa
wispy sequoia
#

I'm asking if I must have files or I can use also urls to merge images

lament mesa
#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO([initial_bytes])```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3.10/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3.10/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3.10/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3.10/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3.10/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3.10/library/io.html#io.IOBase "io.IOBase"):
lament mesa
wispy sequoia
#

uhm

#

lol

rapid whale
wispy sequoia
#

how do I check the content of the message next the bot? example:

user: >battle another user
bot: another user do you accept?
another user: yes
bot: battle started

lament mesa
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
winter jetty
# hasty iron can you send your full code
import asyncio
import base64
import secrets
from json import load

import aiohttp


ws_key = base64.b64encode(secrets.token_bytes(16)).decode('utf-8')
headers = {
    'Pragma': 'no-cache',
    'Origin': 'https://discord.com',
    'Accept-Language': 'en-US,en;q=0.9,es;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Sec-WebSocket-Key': ws_key,
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/93.0.4577.63 Safari/537.36',
    'Upgrade': 'websocket',
    'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
    'Cache-Control': 'no-cache',
    'Connection': 'Upgrade',
    'Sec-WebSocket-Version': '13',
}


async def go():
    from main import buffer, inflator
    session, ws = None, None
    try:
        with open('first_message.json') as file:
            to = load(file)
        session = aiohttp.ClientSession()
        ws = await session.ws_connect(url='wss://gateway.discord.gg/'
                                          '?encoding=json&v=9&compress=zlib-stream',
                                      headers=headers)
        msg = await ws.receive()
        print(msg.data)
        await ws.send_json(to)
        async for msg in ws:
            print(msg)
            buffer.extend(msg.data)
            print(inflator.decompress(buffer))

    finally:
        if ws:
            await ws.close()
        if session:
            await session.close()


if __name__ == "__main__":
    asyncio.run(go())
#

first message is just the hello, nothing weird there

#
import zlib


ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()
#

This is what gets imported

wispy sequoia
#

or can I put it into a command

lament mesa
#

you can

wispy sequoia
#

ok

#

let's try

wispy sequoia
# lament mesa you can
@client.command()
async def battle(ctx, member: commands.MemberConverter):
    await ctx.send(f"<@!{ctx.author.id}> wants to battle. <@!{member.id}> do you accept?")
    await client.wait_for("message", check="yes")
    await ctx.send("Test")```
like this?
lament mesa
#

no

wispy sequoia
#

hmm

lament mesa
#

the check need to be a callable

wispy sequoia
#

so

#

def ?

lament mesa
#

no, it can also be a lambda

maiden fable
#

check="yes"

#

And what do u think it should check for?

#

Also save it to a variable

lament mesa
neat birch
#

I'm a noob, so can you send the code if message = .delete [channelname]

valid galleon
#

so i previously had written some code to send a post from a subreddit, but users complained that it was too slow, and its cuz praw isnt made for an async environment, so i decided to move to asyncpraw. i changed the stuff that was mentioned in the docs, but i get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'ListingGenerator' object is not iterable
My code:

        subreddit = await reddit.subreddit("memes")

        all_subs = []

        hot = subreddit.hot(limit = 50)

        for submission in hot:
            all_subs.append(submission)

        random_sub = await random.choice(all_subs)

        name = random_sub.title
        url = random_sub.url

        embed = discord.Embed(title = name)
        embed.set_image(url = url)

        await ctx.send(embed=embed)```
#

the for loop is causing the error

lament mesa
#

random.choice isnt coro

#

and i think subreddit.hot needs to be awaited

#

and you need to have an async for loop

valid galleon
#

@lament mesa discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object ListingGenerator can't be used in 'await' expression

#

my code:

        subreddit = await reddit.subreddit("memes")

        all_subs = []

        hot = await subreddit.hot(limit = 50)

        async for submission in hot:
            all_subs.append(submission)

        random_sub = await random.choice(all_subs)

        name = random_sub.title
        url = random_sub.url

        embed = discord.Embed(title = name)
        embed.set_image(url = url)

        await ctx.send(embed=embed)```
lament mesa
valid galleon
#

so that fixed the listing generator error, but now i get this:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object Submission can't be used in 'await' expression

#

@lament mesa

lament mesa
#

Send your code mhm

valid galleon
# lament mesa Send your code <:mhm:687726663676592145>
        subreddit = await reddit.subreddit("memes")

        all_subs = []

        hot = subreddit.hot(limit = 50)

        async for submission in hot:
            all_subs.append(submission)

        random_sub = await random.choice(all_subs)

        name = random_sub.title
        url = random_sub.url

        embed = discord.Embed(title = name)
        embed.set_image(url = url)

        await ctx.send(embed=embed)```
lament mesa
#

and random.choice is not coro mhm

valid galleon
lament mesa
valid galleon
#

ty! its fixed now

lament mesa
#

πŸ‘

upbeat otter
#

guys, i cant seem to find DiscordUtils' docs. Anyone can help?

round yarrow
#
def get_prefix(client, message):
    conn = sqlite3.connect("prefix.db")
    c = conn.cursor()
    with conn:
        c.execute("""SELECT * FROM prefix_data WHERE guild_id = :id""", {"id" : message.guild.id})
        data = c.fetchone()
        return data[1]

client = commands.Bot(command_prefix=get_prefix, intents = discord.Intents.all())```

my error:
```py
  File "main.py", line 17, in get_prefix
    c.execute("""SELECT * FROM prefix_data WHERE guild_id = :id""", {"id" : message.guild.id})
AttributeError: 'NoneType' object has no attribute 'id'```
lament mesa
#

The message was sent in dm

round yarrow
native harness
#

Is.... Is it true discord.py won't work anymore by April 2022