#discord-bots

1 messages · Page 1023 of 1

wispy solstice
#

None

heady sluice
#

cuz your client's cache is empty

wispy solstice
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'

heady sluice
#

cuz your client is not your client

wispy solstice
heady sluice
#

is it in the main file now

wispy solstice
#

but how if it didn't work?

heady sluice
#

GRRR

wispy solstice
#

😂

heady sluice
#

how did you do it then

wispy solstice
#

i just changed fetch to get

slate swan
#

You still haven't changed what I've said...

heady sluice
#

but the cache is empty

wispy solstice
#

It worked

#

But if the cache is emptyn

#

it should not sending messages right?

slate swan
#

^

heady sluice
wispy solstice
#

It sends the messages so the client works right?

slate swan
#

hey guys why does it say interactin failed when it worked?
It keeps loading when I click it as well.

heady sluice
#

no

#

they're not the same

wispy solstice
#

I'm using client.command, it shouldn't mark the command even?

heady sluice
#

it's a Command instance whatsoever

#

if you add it to the bot, it works

#

ey that's one year of python right there

slate swan
#

Now simply do await ctx.respond(..., ephemeral=True) to make it an ephemeral message

#

Why did you have to change everything?

#

Keep your old code and just append , ephemeral=True as I've said above.

wispy solstice
#

I forgot about ctx.guild, let's try it

slate swan
#

Just like a normal embed

#

Right above your respond

#

And pass embed=x in the call

heady sluice
#

bro you got the cup of tea already which you put on the table, you know where the tablet is, just take the tablet and put the cup on it before serving

slate swan
#

Yeah instead of msg

#
class Suggestion(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(emoji="✅", style=discord.ButtonStyle.green, custom_id = 'upvote')
    async def check_callback(self, interaction, button):
        message = interaction.message
        embed = message.embeds[0]
        embed_dict = embed.to_dict()
        upvotes = embed_dict["fields"][0]["value"].replace(" Votes```","").replace("```","")
        downvotes = embed_dict["fields"][1]["value"].replace(" Votes```","").replace("```","")
        author_url = embed_dict["author"]["url"]
        author_name = embed_dict["author"]["name"]
        description = embed_dict["description"]
        embed = discord.Embed(description=description)
        embed.set_thumbnail(url=author_url)
        embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"```{int(upvotes)+1} Votes```",inline=True)
        embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"```{downvotes} Votes```",inline=True)
        embed.set_author(name=author_name.replace("' Suggestion","") + "'s Suggestion",url= author_url)
        try:
            embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
        except: 
            embed.set_footer(text="Use -suggest to leave a suggestion!")

    @discord.ui.button(emoji="❎" , style=discord.ButtonStyle.red, custom_id = 'downvote')
    async def x_callback(self, interaction, button):
        message = interaction.message
        embed = message.embeds[0]
        embed_dict = embed.to_dict()
        author_url = embed_dict["author"]["url"]
        author_name = embed_dict["author"]["name"]
        downvotes = embed_dict["fields"][1]["value"].replace(" Votes```","").replace("```","")
        upvotes = embed_dict["fields"][0]["value"].replace(" Votes```","").replace("```","")
        description = embed_dict["description"]
        embed = discord.Embed(description=description)
        embed.set_thumbnail(url=author_url)
        embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"```{upvotes} Votes```",inline=True)
        embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"```{int(downvotes)+1} Votes```",inline=True)
        embed.set_author(name=author_name,url= author_url)
        try:
            embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
        except: 
            embed.set_footer(text="Use -suggest to leave a suggestion!")
        await interaction.message.edit(embed=embed)```
Hey there guys!
Why does only the x button work?
heady sluice
#

your code formatting messed it up

slate swan
#

woah wtf

#

Well you never respond in the first case

#

You just do some embed formatting, just never do anything at the end

#

Unlike the second where you await interaction.message.edit(embed=embed)

#
class Suggestion(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(emoji="✅", style=discord.ButtonStyle.green, custom_id = 'upvote')
    async def check_callback(self, interaction, button):
        message = interaction.message
        embed = message.embeds[0]
        embed_dict = embed.to_dict()
        upvotes = embed_dict["fields"][0]["value"].replace(" Votes","").replace("","")
        downvotes = embed_dict["fields"][1]["value"].replace(" Votes","").replace("","")
        author_url = embed_dict["author"]["url"]
        author_name = embed_dict["author"]["name"]
        description = embed_dict["description"]
        embed = discord.Embed(description=description)
        embed.set_thumbnail(url=author_url)
        embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"{int(upvotes)+1} Votes",inline=True)
        embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"{downvotes} Votes",inline=True)
        embed.set_author(name=author_name.replace("' Suggestion","") + "'s Suggestion",url= author_url)
        try:
            embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
        except: 
            embed.set_footer(text="Use -suggest to leave a suggestion!")

    @discord.ui.button(emoji=":negative_squared_cross_mark:" , style=discord.ButtonStyle.red, custom_id = 'downvote')
    async def x_callback(self, interaction, button):
        message = interaction.message
        embed = message.embeds[0]
        embed_dict = embed.to_dict()
        author_url = embed_dict["author"]["url"]
        author_name = embed_dict["author"]["name"]
        downvotes = embed_dict["fields"][1]["value"].replace(" Votes","").replace("","")
        upvotes = embed_dict["fields"][0]["value"].replace(" Votes","").replace("","")
        description = embed_dict["description"]
        embed = discord.Embed(description=description)
        embed.set_thumbnail(url=author_url)
        embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"{upvotes} Votes",inline=True)
        embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"{int(downvotes)+1} Votes",inline=True)
        embed.set_author(name=author_name,url= author_url)
        try:
            embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
        except: 
            embed.set_footer(text="Use -suggest to leave a suggestion!")
        await interaction.message.edit(embed=embed)```
#

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

slate swan
#

But as I said

#

Please read it, you will see

heady sluice
#

I only see like 200 variables

slate swan
#

Just compare the end of your both callbacks

wispy solstice
#

And it worked without cogs @slate swan @heady sluice xD

slate swan
#

One has await interaction.message.edit(embed=embed)

#

The other one has nothing

#

didn't copy the edit
thank a lot

slate swan
#

Indentation is wrong

heady sluice
#

you've got limitations

languid jungle
#

hey, please don't use ableist words

wispy solstice
#

I'll see what the issue is

slate swan
#

what is that?

heady sluice
languid jungle
#

nope, I've been around for a while

heady sluice
#

or just really rare to see here

languid jungle
#

more than 1 year

heady sluice
#

I'm newer

slate swan
languid jungle
slate swan
#

Embed needs to have some indentation like the following

embed = discord.Embed(
    title="...",
    color=....
)
embed...
await...
slate swan
#

Your profile picture look like jesus

#

Nope

heady sluice
slate swan
#

Oh sorry
who is that?

heady sluice
#

da heck

slate swan
#

You did like

    embed = discord.Embed(
    title="...",
    color=....
)
embed...
await...
heady sluice
#

star wars

slate swan
#

this one?
that's the first gif I found lol

heady sluice
#

...

slate swan
#

Everything should be aligned at the same place as embed = ...

#

Nope, under msg

#

Otherwise it won't be executed if it's in the if statement

#

Which would be unfortunate

#

Yep, and put at the same level embed = ... and everything else

#

You have:

    msg = "..."
embed = ...
...

You need:

    msg = "..." # Which will then be deleted
    embed = ...
    ...
spring flax
#

there's nothing wrong with this line right? if isinstance(original_error, (commands.CommandNotFound, commands.CheckAnyFailure, disnake.HTTPException)):

slate swan
#

See the lines, needs to be aligned

#

!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

slate swan
#

Nope, not all

#

Everything needs to be at the third line

#

Can you send code, easier for me to show

#

Almost

#

The last two needs to be at the same level

#

Yep

#

Yep

#

How to get id of the person that clicked the button?

#

You have

    embed = discord.Embed(
        title="...",
        color=....
)
embed...
await...

You need

    embed = discord.Embed(
        title="...",
        color=....
    )
    embed...
    await...
#

Nope, they're one below

#

Right now there will be only embed = discord.Embed(...) executed if it goes in the if statement

#

The ) might confuse you and make you think it's aligned correctly

slate swan
#

Yep

#

oh ok thank

slate swan
#

Oh ok

#

I think interaction.author is disnake

#

nice

#

Oh yeah that's normal

#

The .format(...) goes at the end of your string

#

So like

x = "Blah {...}".format(...)
sick birch
#

Use f strings instead

slate swan
#

Should use f-strings though

#

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

little ivy
#

Who can help me, buttons dont work anymor after a certain amount of time

#

first they do, but after a restart or after 10 minutes they stop

cloud dawn
#

I recommend using f strings as robin mentioned.

little ivy
#

Let me show my code.

cloud dawn
#

Did you restart the bot?

little ivy
#

Yes

#

And saved script

cloud dawn
#

Yeah that's the problem

#

You restarted the bot.

#

!d discord.Client.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components
that last longer than the lifecycle of the program.

New in version 2.0.
cloud dawn
#

Use this if you want to restore interactions.

slate swan
#

how can i check if a user is already banned?

little ivy
little ivy
cloud dawn
slate swan
wispy solstice
#

How can I hold the exception of forbidden?

cloud dawn
slate swan
#

I tried this but get_ban has no attribute```py
entry = await ctx.guild.get_ban(user)

if user in entry:
await ctx.reply("This user is already banned!")```

cloud dawn
#

Yeah just try to ban the user and catch the exception.

slate swan
#

how?

cloud dawn
unkempt canyonBOT
#

await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to
do this.
slate swan
#

yes yes i know that part

#

i’m asking how do i catch the exception

cloud dawn
#

!except

unkempt canyonBOT
#

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

cloud dawn
#

!d round

unkempt canyonBOT
#

round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
#

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.

cloud dawn
#

You can't mix f-string and format.

#

99/100 times choose f-strings

slate swan
#
try:
    entry = await ctx.guild.get_ban(user)
  except discord.NotFound:
      await ctx.reply("This user is already banned")
  return```
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'get_ban'```
pliant gulch
#

There is no get_ban, only fetch_ban

slate swan
#

In my discord bot, when i type a command it doesn't send a message but when i try ctrl + c it doesn't break out of the script, but sometimes it completely works fine i don't know why

slate swan
little ivy
#

What should i make it then

regal pulsar
#

lol

#

why f strings and .format

#

value = f"X **Still on cooldown, please try again in {error.retry_after}s"

fading marlin
#

don't use f strings and .format on the same string

cloud dawn
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
regal pulsar
#

just copy paste what i sent

#

how hard is that 💀

slate swan
cloud dawn
slate swan
#

i swear it was always None

cloud dawn
regal pulsar
#

well what is error.retry_after

regal pulsar
#

i thought it was none too 💀

#

nothing

#

delete it

coarse dawn
#

How do I install disnake to macOS?

#

Already tried that

slate swan
#

read what it says ( yellow text)

velvet compass
#

You need to pass a cooldown duration to the decorator

honest shoal
#

also there's no need to add aliases in slash commands :)

velvet compass
toxic thicket
#
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
    base.commit()
    print(1)
    
    warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
    print("работает")
    
    
    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if warnings is None:
        cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
        base.commit()
        print(2222)
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
    else:
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")         

How to make it so that if the reason was not specified, then Отсутствует was not written at the end, and if the reason was specified, then this was entered into the database and the reason was shown in the chat. Help me plz.

civic flower
#

What is async?

sick birch
# civic flower What is async?

Normally, python runs your code line by line, and holds up the entire thread while waiting for something. This can be problematic from I/O tasks, such as waiting for a web server to respond, waiting for a database server to respond, etc

#

Async was created to solve this issue: while you're waiting for something to respond, you can go and do something else, and come back later when the server has responded

civic flower
#

Ah I see, that makes a lot of sense.

sick birch
#

discord.py greatly benifits from this because due to the way that Discord's Gateway API works, you have to send a heartbeat to the gateway every 45ish seconds letting it know you're still on the other end waiting. This is a problem, because your code would look something like this:

while True:
  send_heartbeat()
  time.sleep(45)

Which means your code would hang on that part, and it would never do anything else. With asynchronous code however, it can heartbeat, go do something else for 45 seconds, then come back and heartbeat, rinse & repeat

civic flower
#

Thank you so much, I understand it now.

slate swan
#

Hello Robin, can you help?

sick birch
#

Yup. It gets a lot more complex, so if this is interesting to you, I suggest you do some more research on it and try to understand how things such as the executor, event loop work, and differences between parallel computing and concurrency

sick birch
slate swan
#
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
    base.commit()
    print(1)
    
    warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
    print("работает")
    
    
    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if warnings is None:
        cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
        base.commit()
        print(2222)
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
    else:
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")        

How to make it so that if the reason was not specified, then Отсутствует was not written at the end, and if the reason was specified, then this was entered into the database and the reason was shown in the chat. Help me plz.

sick birch
#

isn't that the same question @toxic thicket asked?

slate swan
#

._.

#

he wanted to help

sick birch
#

Doesn't look like it

#

I'm not sure what's going on here - why are 2 people asking for help on the same exact thing?

slate swan
#

Right now

stone beacon
#

That's a very good question

sick birch
#

Indeed it is

cloud dawn
#

Combined effort

brave forge
#

who knows if it's ok to use from discord.ext import menu ?

brave forge
#

@slate swan
I see you're Russian

#

@slate swan
don't throw Russian letters here at all, here they have a bad effect on people.

brave forge
#

how to make the message "hello word" deleted after clicking on any of the reactions?

feral lichen
#

why is this saying BotBase.add_cog was never awaited ```py
bot.add_cog(Greetings(bot))

feral lichen
#

sends an error

torn sail
#

You may be looking at docs for 1.7.3

#

Load them in the setup_hook

feral lichen
#

??

#

i got it to work before perfectly fine idk what happened

torn sail
#

Subclass commands.Bot and define an async function named setup_hook and do stuff there

#

It was a recent change

keen mural
#

For my python bot, the timed mute commands i have tried all do not work, and I don't understand the methods used so I can't like do anything :/
Does anyone have a code I can look at or can help me at all?
basically i just need to understand how to get my code to understand time then min/sec/hour/day, then await that time period then do the action (for example giveaway or mute cmd)
smth like .gcreate 1min test prize or .gcreate 1 min prize here!
.mute @keen mural 1m bad or .mute @keen mural 1 min bad!!

feral lichen
#

because most likely and no one will send open code for a mute command

#

i dont mind helping you since i do have a timed mute command

keen mural
#

(keep in mind this is prob ugly since i have no idea what im doing)

#

im just tryna get different time variables that the person states in the command then make it sleep for that long basically

#

also i prob messed up that code a lot

feral lichen
#

where are you implementing the time? like the int

#

oh

keen mural
#

idk what int means tbh 🥶
I could only make it work in seconds without any min sec hour etc things

feral lichen
#

int means integer, other known as a number.

keen mural
feral lichen
#

did you make the code?

keen mural
#

like .gcreate 40min test

keen mural
feral lichen
#

ah

keen mural
#

which u can prob tell 😂

feral lichen
#

yea mix code will not work lmfao

keen mural
#

its more like taking things i know and using it but i dont know what i am doing here

feral lichen
#

holdup

#

well heres some help that arent python docs

cloud dawn
keen mural
feral lichen
#

holdup i asked you to send mute thingy and you sent giveaway code?

keen mural
#

its the same code

feral lichen
#

huh

cloud dawn
slate swan
#

hello

keen mural
slate swan
#

any idea on how to pinpoint latitude and longitude on a map using python ?

brave forge
#

Who wants to learn the best programming language for the English - speaking population ??

cloud dawn
feral lichen
keen mural
#

my first advanced cmd attempt

brave forge
#

@heady sluice @cloud dawnI have found the perfect programming language for you

keen mural
#

but if i put (time) doesnt say the field is like unfulfilled when i do the cmd

cloud dawn
feral lichen
#

you need to put ctx, member: discord.Member, time, reason

#

if you want to use that you can but dont have to

keen mural
feral lichen
#

idk if i would want to use complex discord.py from a beginner level

keen mural
#

time is an argument in that

cloud dawn
#

Wizguy's method is a pretty solid one for beginners.

feral lichen
#

ig so

#

but from the basically i mixed other peoples code around into one thats really beginner

keen mural
#

blahblahblah = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "mo":18144000, "y":31536000}
blah = int(time[:-1]) * blahblahblah[time[-1]]
what would the blahblah be

#

💀

feral lichen
#

just a var

keen mural
#

so if i had
async def gcreate(ctx, args,*,prize=None):

feral lichen
#

why are you using args

keen mural
#

idk man idk what im doing

#

async def gcreate(ctx, time,*,prize=None):

#

is that better

feral lichen
#

well im not gonna spoonfeed much more but you need a member in commands arg, and blah is used to convert essentially. One last tip is use await.asyncio.sleep(desctime) when dont want muted anymore but gl

keen mural
#

ok ill try lol

#

thx for helping

midnight gorge
#

it works but doesn't create a channel

#

but it mentions the channel

keen mural
#

huh

midnight gorge
#

🤷

#

really weird...

#

it works only thing it doesn't make the channel

#

but somehow it mentions the channel

feral lichen
#

wtf

#

thats odd

feral lichen
#

or whatever it is

#

i dont see like it actually being made

midnight gorge
#

channel = await interaction.guild.create_text_channel(name=f"{interaction.user.name}-{interaction.user.discriminator}")

#

is it that?

feral lichen
#

yea but you have to create it

#

channel is just a variable im pretty sure just like that 💀

midnight gorge
#

so if do await interaction.guild.create_text_channel(name=f"{interaction.user.name}-{interaction.user.discriminator}")

#

Or

#

i think it was like that on v1

feral lichen
#

idk man but you have to 'activate' the var lol

midnight gorge
#

ok

feral lichen
#

idk if that makes sense

feral lichen
#

pretty sure to set prms you just find the channel name

midnight gorge
#

i fixed it

#

thank you

#

also

#

Can it be done on a cog?

torn sail
#

pretty much everything will be the same in a cog

wispy solstice
#

Did the timeout added for discordpy?

torn sail
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the
given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to
use this...
wispy solstice
#

For some reason I didn't find it in docs but thanks

keen mural
#

oh

#

unhashable type: slice

jade tartan
#

My cogs is not being loaded

#
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

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

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

How do i fix this?

#

This is the file i want it to load

sly hamlet
#

How can I send more than one message with a command in 2.0

fading marlin
fading marlin
sly hamlet
#

Yes

jade tartan
#

Version

fading marlin
# sly hamlet Yes

don't think you can, however I've not experimented enough with slash commands so I'm not so sure

fading marlin
sick birch
sly hamlet
sick birch
#

Ah you're using slash commands

#

You should be able to get the channel and use channel.send() then

jade tartan
sly hamlet
fading marlin
#

or discord.__version__, either one works

cloud dawn
#

pip show discord.py

jade tartan
#

1.7.3 is my py version

jade tartan
fading marlin
#

are you getting any errors when trying to load them?

jade tartan
#

raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: extension is a required argument that is missing.

#

Yes

#

I mean i want it to where when the code runs all the extension gets loaded

timber tendon
#

dude in my server muted my bot because it stopped working, I keep unmuting it but it still thinks it's muted

#

how tf do I fix this

fading marlin
fading marlin
cloud dawn
#

Well what does that return?

cloud dawn
#

And what is this?

sly hamlet
cloud dawn
#

!d discord.ClientUser.created_at

unkempt canyonBOT
#

property created_at```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
cloud dawn
#

returns datetime.datetime

timber tendon
cloud dawn
#

It returns a datetime object.

#

!d datetime.datetime

unkempt canyonBOT
#

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
iron sorrel
#

time travel

cloud dawn
#

!d datetime.datetime.timestamp

unkempt canyonBOT
#

datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").

Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.

For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:

```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
```   New in version 3.3.

Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
iron sorrel
#

did you know duck, you can send

fading marlin
iron sorrel
#

!e import time; print(time.time())

unkempt canyonBOT
#

@iron sorrel :white_check_mark: Your eval job has completed with return code 0.

1651621174.6953475
iron sorrel
#

<t:1651621174>

#

timestamps in discord :0

cloud dawn
#

So bot.user.created_at.???

iron sorrel
#

<t:1651621200:R>

#

relative timestamps?

wide thunder
#

can u suggest me a good discord api library that has slash cmds + a cheap hosting

sick birch
#

And I'd suggest discord.py which has been the de-facto

jade tartan
wide thunder
jade tartan
#

It just says my bot is online

wide thunder
#

i mean suggest me a cheap hosting

wide thunder
#

for python

timber tendon
fading marlin
iron sorrel
#

but what do you mean cheap hosting

wide thunder
#

alr

timber tendon
wide thunder
#

thanks

sly hamlet
iron sorrel
#

member does not have channel

keen mural
#

hey

#

@vocal girder

sly hamlet
iron sorrel
iron sorrel
sly hamlet
#

I have a giveaway command but it sends multiple messages in one command though

iron sorrel
#

show ur code maybe someone will have an idea

sly hamlet
supple thorn
sly hamlet
#

None of them are getting sent multiple times it's just you can't use the reply feature which is what you use when sending the message multiple times

hushed galleon
#

after the first response you get a followup webhook you can use to send multiple messages

#

e.g. ```py
await interaction.response.send_message('hello world!')

any messages afterwards...

await interaction.followup.send('hello once more!', ephemeral=True)```

torn sail
#

Followup will be same ephemeral as response

sly hamlet
#

If interaction.author does not exist what do I use instead?

torn sail
sly hamlet
#

Ok thx

sly hamlet
slate swan
#

i.e disnake has aliases for it so it can be author and user

sly hamlet
slate swan
#

which error?

foggy sand
#

Is it possible to make a discord bot that I text in dms to it then it sends an image to a channel?

foggy sand
#

Kk.

#

I tried but it won’t work

#

client.on("message", message => {
message.author.send("Please send a screenshot");
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {});
console.log(collector)
collector.on('collect', message => {
if (message.attachments.size > 0) {

    message.channel.send("You successfully sent a screenshot")
    console.log(`Collected ${message.content}`)
    client.channels.get(`628607857662623745`).send(message.content);

} else if (message.attachments.size < 0) {
    message.channel.send("you did not");

}   

})

supple thorn
#

This is a python server

foggy sand
#

Oh forgot this is python sorry

foggy sand
#

Oh thanks

supple thorn
#

Ask here

sly hamlet
torn sail
#

!d discord.ext.commands.TextChannelConverter.convert

unkempt canyonBOT
#

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

The method to override to do conversion logic.

If an error is found while converting, it is recommended to
raise a [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will
properly propagate to the error handlers.
torn sail
#

You can do this await commands.TextChannelConverter().convert(ctx, “some arg here”)

maiden fable
#

You know

#

U can simply do channel: discord.TextChannel

sly hamlet
sly hamlet
zenith basin
#

How would I achive something like this

slate swan
#

also guilds.join scope

civic flower
#
@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ["It is certain.",
    "It is decidedly so.",
    "Without a doubt.",
    "Yes - definitely.",
    "You may rely on it.",
    "As I see it, yes.",
    "Most likely.",
    "Outlook good.",
    "Yes.",
    "Signs point to yes.",
    "Reply hazy, try again.",
    "Ask again later.",
    "Better not tell you now.",
    "Cannot predict now.",
    "Concentrate and ask again.",
    "Don't count on it.",
    "My reply is no.",
    "My sources say no.",
    "Outlook not so good.",
    "Very doubtful."]
    
    await ctx.send(f'**Question:** {question}\n**Answer:** {random.choice(responses)}')

how would I make this send a different message if the user did not input a value for question

hushed galleon
fading marlin
civic flower
fallow thorn
#

ight

sly hamlet
hushed galleon
# civic flower ```py @client.command(aliases=['8ball']) async def _8ball(ctx, *, question): ...

you could handle the MissingRequiredArgument exception using a command error handler: ```py
@bot.command()
async def my_command(ctx, arg):
await ctx.send(f'you passed {arg}!')

@my_command.error
async def my_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'please pass the parameter: {error.param.name}')
# error.param.name would give the name of the missing argument, i.e. "arg"
else:
# some other error happened that we need to print
raise error``` if its going to be a common response for many commands then a global error handler would be more suitable which you can read more about in the docs: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#error-handling

slate swan
#

Is there any way to align my embed fields, although they're all inline?

keen mural
keen mural
regal pulsar
slate swan
#

if you just tried running the bot you have to wait a while for it to update.

#

take there word for it. I'm not 100% sure

regal pulsar
#

also i dont think the error handler is the problem, check traceback

keen mural
fading marlin
#

commands.Bot already has its own tree, don't use both Client and Bot

regal pulsar
#

no i meant @keen mural

regal pulsar
keen mural
#

you think thats a problem?

regal pulsar
#

no as long as its just one

#

does the error happen at runtime

sly hamlet
regal pulsar
#

or when you run the mute command

keen mural
#

when i try to start

#

doesnt start

regal pulsar
keen mural
#

is this the problem?

regal pulsar
#

something that happens at runtime

#

nah thats fine

keen mural
#

ok

#

is it smth about isinstance

#

reposting it

fading marlin
#

you're probably doing something like this right?

import discord
from discord.ext import commands
bot = commands.Bot(...)
app_commands = discord.app_commands.CommandTree(bot)
hot cobalt
#

The traceback will tell you where the issue is

regal pulsar
#

isinstance just checks if the first argument is an instance of the second

hot cobalt
#

So perhaps have a look at that

keen mural
regal pulsar
#

oh

keen mural
#

idk what most recent call last means

hot cobalt
#

Seems like mute.error() expects an arg

regal pulsar
#

no wonder

#

remove the brackets

#

its just @mute.error

keen mural
#

youtube tutorial did me dirty 😭

regal pulsar
#

lol

keen mural
#

thanks so much now my bot will hopefully no longer get banned from too many errors

hot cobalt
#

Your error handling is a little weird

#

You're returning in every condition for some reason, rather than using elif's

fading marlin
#

yeah, as I said, bot already has it's own tree, so you can just do bot.tree. That'll be your new tree var

#

!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.
keen mural
#

ik its like a different if

hot cobalt
#

An elif will run if all conditions above it are False and its condition is True

regal pulsar
#

never used it

keen mural
#

oh

regal pulsar
#

not according to my cs teacher this year though 💀

hot cobalt
#

So you should be doing ```py
if isinstance(...):
...
elif isinstance(...):
...
else:
...

keen mural
#

thats helpful 😢

hot cobalt
#

And don't return in every condition since it would be redundant if you use elif

fading marlin
# regal pulsar what is bot.tree

it's kinda like discord.app_commands.CommandTree, but instead of using discord.Client, you use commands.Bot and you don't pass your bot var to the CommandTree

regal pulsar
#

what kind of tutorial were you watching lol

keen mural
#

it all makes sense now bigbrain

keen mural
regal pulsar
#

lol

#

read the docs

#

very helpful

keen mural
#

docs?

hot cobalt
#

There aren't many discord.py resources that are any good, which is another reason why it's really not a beginner friendly lib

undone tulip
#

how to fix?

regal pulsar
#

i learnt it from just the docs

hot cobalt
#

Yeah, but beginners don't know how to read docs 👀

keen mural
fading marlin
regal pulsar
#

i basically learnt how to read docs from that

undone tulip
hot cobalt
#

You've got self as an arg for some reason

#

This isn't in a class

regal pulsar
#

the guy in the vid was probably using cogs

keen mural
#

yeah idk why self was in there

regal pulsar
keen mural
#

doesnt self make the bot like recognize itself or something

hot cobalt
#

Chances are whatever you were watching defined the function in a class

hot cobalt
regal pulsar
undone tulip
regal pulsar
#

it represents the instance

torn sail
keen mural
#

yes i understand Thump_upsad

#

if i wanna add more examples of each one would i have to do the seconds to it too

#

i dont even know what im asking ill be right back and test

regal pulsar
#

lemme find my old mute command

#

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

regal pulsar
supple thorn
regal pulsar
supple thorn
#

🗿

regal pulsar
#

💀

keen mural
#

this was what i was talking about, adding some things but it dont work

#

im guessing cuz the code on the last line?

#

smth about the -1

torn sail
#

well -1 gets the last character in the string so only s, m, h, w and d would work

keen mural
slate swan
#

How can I display the bots avatar in the embed title?

keen mural
#

idk 💀

slate swan
#

no theres a built in way, I just forgot how

keen mural
torn sail
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style
chaining.
torn sail
#

icon_url

keen mural
#

that never works ong

keen mural
torn sail
slate swan
torn sail
#

you could use a regex

torn sail
slate swan
torn sail
slate swan
#

How can I add space between my embed footer?

keen mural
#

wdym

slate swan
#

basically a new line

keen mural
#

\n

slate swan
#

doesn't work

keen mural
#

footer is one line only

#

if thats what ur talking about

slate swan
#

embed stuff
footer is here

#

I want it to be like

#

embed stuff

footer is here

keen mural
#

maybe

#

use add field

slate swan
#

then the text wont be small like the footer.

keen mural
#

?

#

¯_(ツ)_/¯

slate swan
#

dont provide invalid help lmao

keen mural
#

try \n then an invisible character or smth idk

keen mural
supple thorn
slate swan
keen mural
#

If i was doing

  mutetime = int(time[:-1]) * validation[time[-1]]```
how would i add longer validations?
slate swan
#

Can you not bold footer text?

regal pulsar
unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style
chaining.
keen mural
#

u cant mention ppl either

supple thorn
regal pulsar
slate swan
#

how so

regal pulsar
#

** **

supple thorn
supple thorn
slate swan
regal pulsar
#

oh

hushed galleon
#

footer doesnt support any markdown

supple thorn
#

Really?

regal pulsar
#

maybe you cant 💀

keen mural
#

If i was doing

  mutetime = int(time[:-1]) * validation[time[-1]]```
how would i add longer validations?
supple thorn
keen mural
#

instead of just s

#

might as well copy and paste the entire command

supple thorn
keen mural
#

-1 thingy

#

so if it was longed

#

there would still be text instead of just numbers

#

and that messes it up to my understanding

slate swan
#

is there any way I could add more space between my embed fields and footer?

regal pulsar
#

validation = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "seconds":1}

slate swan
#

Hi

keen mural
#

but the second line of code only subtracts 1 letter

regal pulsar
#

hey

slate swan
#

What's the problem

keen mural
#

or whatever

slate swan
keen mural
# slate swan What's the problem

If i was doing

  mutetime = int(time[:-1]) * validation[time[-1]]```
how would i add longer validations?

like secs seconds etc
instead of just s
slate swan
#

Show code

keen mural
slate swan
#

wait nvm Im dumb

slate swan
#

Wait

#

U mean alias?

keen mural
#

not alias for the cmd

regal pulsar
#

no

#

its for his dict

keen mural
#

its a mute command and that determines the time

slate swan
#

Ye alias for dict

keen mural
#

i mean

slate swan
#

so u can use s sec sond

keen mural
#

how do i do that

slate swan
#
embed.add_field(name="``help``", value="sends this help message\n\n", inline=True)
embed.set_footer(text="Contact y9su#8009 for further help or if you find any bugs")

this isnt adding the newlines

#

Try adding a text or emoji at last

#

After n

hushed galleon
#

that error line seems unusual but its hard to tell without the full traceback, however it may be related to incorrectly using the @bot.tree.command decorator in your group rather than the generic @app_commands.command deco that Group looks for

keen mural
#

invisible emoji

slate swan
#

Ye something like that

keen mural
#

anyway sparky how do i add aliases

slate swan
#

Wait

hushed galleon
#

ah okay

slate swan
#

I'll send code

keen mural
slate swan
#

um try a list maybe

keen mural
#

hmm ok

#

like s = [
'sec',
'second'
]

#

or something

regal pulsar
#
async def parse_time(time: str, function=None, next_function=None, parsekey: str=None):
    import asyncio

    if parsekey in time:
        time = time.replace(parsekey, "")
        time = int(time)
        await function
        await asyncio.sleep(time)
        await next_function()
#

try this

hushed galleon
#

oh can you paste the full traceback then?

regal pulsar
#

just do

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

regal pulsar
#
@bot.command()
async def mute(ctx, member, time):
    async def check1():
        role = discord.utils.get(ctx.guild.roles, name="muted")
        await member.add_roles(role)
    async def check2():
        role = discord.utils.get(ctx.guild.roles, name="muted")
        await member.remove_roles(role)
    await parse_time(time, function=check1, next_function=check2, parsekey="s")
#

@keen mural

slate swan
#

Bro

#

He dont mean that

regal pulsar
#

maybe i should try with decorators

slate swan
#

ig

hushed galleon
#

ohh you're missing the self parameter at the start of the function

regal pulsar
slate swan
#

then?

regal pulsar
#

he can use this instead

#
class ParsekeyNotInString(Exception):
    pass


class StringParseError(Exception):
    pass


async def parse_time(time: str, function=None, next_function=None, parsekey: str = None):
    import asyncio

    if parsekey in time:
        time = time.replace(parsekey, "")
        try:
            time = int(time)
        except ValueError:
            raise StringParseError("Resulting string after removing the parsekey was not an integer/float")
        await function
        await asyncio.sleep(time)
        await next_function()
    else:
        raise ParsekeyNotInString(f'The gives parsekey "{parsekey}" was not found in the given string "{time}"')
#

@slate swan

slate swan
regal pulsar
#

smart

#

wait what string parse error

#

that isnt defined

#

is it from an import

slate swan
keen mural
#

you think i can make this work?

regal pulsar
#

🤦‍♂️

#

i just saved like 100 lines of code with this

keen mural
#

could i make the code detect letters and subtract the amount of letters

sly hamlet
#
    async def start_loop():
        await self.api.start_loop()
        print("Post Count")

    async def main():
        asyncio.create_task(start_loop(bot))

    
    asyncio.run(main())``` ```py
RuntimeError: asyncio.run() cannot be called from a running event loop``` I seem to keep on getting this error and I can't exactly seem to figure out how to fix it can someone help?
sick birch
sly hamlet
#

nested?

sick birch
#

Yes - is your asyncio.run() top level?

#

Or is it nested within a class or method?

sick birch
sick birch
#

Ah, it's inside your class

#

asyncio.run() should be the main entry point to your code

regal pulsar
zenith basin
regal pulsar
#

iirc

sick birch
#

Also because access tokens expire and there's not much you can do about it

#

That's why they provide you with an expires_in field so you can anticipate its expiry and generate a new one using your refresh token

sly hamlet
#

So put it up at the top of the class outside of everything?

sick birch
#

It should also be in your main file, not in a cog

#

Don't think of asyncio.run() as a way to run any coro without awaiting it

#

Or a "get out of awaiting a coro free card"

zenith basin
sick birch
sly hamlet
#

Moving it to the main file just says it's not defined

sick birch
#

Or, whenever you need to use it, you can check if it's a valid access token, and if it's not, you can get a new one using the refresh token

sick birch
sly hamlet
#

It says main is not defined

#

When moving it to the main file

sick birch
#

Yeah, you need a main function

zenith basin
#

like this??

sick birch
#

Sure, if you get a non-200 status code that means it's an invalid code

sly hamlet
zenith basin
sick birch
#

Your main() function can look like this:

async def main():
  try:
    await bot.start()
  finally:
    # cleanup tasks here
asyncio.run(main())
sick birch
#

You'd need to figure out how to get that

zenith basin
#

mabye I could save and when I need it

sick birch
#

Yeah, that's a good idea

#

Take due precautions like you would

zenith basin
#

ya

#

will use hasing

sly hamlet
#

Do I just need to move everything in that one file over to the main file?

zenith basin
#

or encryption

sick birch
#

It's meant to kickstart your ENTIRE bot file, not just a task

sly hamlet
#

So from my understanding I need to move everything from my API file over to my main start file and use create task inside of my main function which starts my bot

sick birch
#

Not necessarily

#

You can start your tasks inside setup()

#

And remove your main() and asyncio.run(main())

sly hamlet
#

I'm just all get out confused right now

#
async def start_loop():
        await self.api.start_loop()
        print("Post Count")

    start_loop()``` this?
sly hamlet
sick birch
slate swan
#

Or use on_ready

spring flax
#

yes, there should be

sick birch
slate swan
#

uh why

sick birch
#

It's unpredictable, and can get called multiple times. It's also not guaranteed to be the first event called

#

That's why it's generally discouraged to do anything in on_ready

slate swan
#

Okay I'll remember it

civic flower
#
 async def status(self, ctx, member:discord.Member):
        print(member.status)
        if member.status == online:
            await ctx.send(f'{member} is online!')
        else:
            await ctx.send('You are not online.')

I am running into an issue where I want member.status to send a message only if it returns online, but I am not sure what to put after the member.status ==
I tried putting just online but it didnt work.

*edit: I was being dumb and didn't use the class. I resolved my issue by using discord.Status.online instead of just online. *

slate swan
#

!d discord.Member.status

unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
sly hamlet
slate swan
#

Wdym?

#

Show code

sly hamlet
#

You would have to read the entire conversation to see what I'm talking about

slate swan
#

U want a loop right

sly hamlet
#

yes

slate swan
#

Show code where r now

sly hamlet
#
async def start_loop():
        await self.api.start_loop()
        print("Post Count")

    async def setup(bot):
        cog = DiscordListsPosts(bot)
        await bot.add_cog(cog)
        await cog.start_loop()```
slate swan
#

Do u have a setup hook?

#

I mean

#

REMOVE start loop from start loop function

#

And put it in the setup

#

um

#

And

#

use tasks.loop

sly hamlet
sick birch
midnight gorge
#

what is guild splash?

sly hamlet
# sick birch In your `setup()` in your cog file
    async def start_loop():
        await self.api.setup()
        print("Post Count")


async def setup(bot):
    cog = DiscordListsPosts(bot)
    await bot.add_cog(cog)
    await cog.start_loop()
    await bot.add_cog(DiscordListsPost(bot))```
sly hamlet
sly hamlet
#

Anybody else know if I got this correct

stone beacon
#

No

dull terrace
#

i think my class attributes are getting too long froggy_chill

stone beacon
#

Just def setup(bot):
bot.add_cog()

#

Etc

zenith mural
#
@bot.slash_command(name = "serverinfo", description = "information about a server")
async def serverinfo(ctx: commands.Context):
    role_count = len(ctx.guild.roles)
    owner = await ctx.guild.fetch_member(ctx.guild.owner_id)

    embed = disnake.Embed(title=f"{ctx.guild.name}'s Info", timestamp=ctx.message.created_at, colour=0x00FF00)
    embed.add_field(name="Name", value=f"{ctx.guild.name}", inline=False)
    embed.add_field(name="Member Count", value=ctx.guild.member_count, inline=False)
    embed.add_field(name="Verification Level", value=str(ctx.guild.verification_level), inline=False)
    embed.add_field(name="Owner", value=f"{owner.name}#{owner.discriminator}", inline=False)
    embed.add_field(name="Number Of Roles", value=str(role_count), inline=False)

    await ctx.send(embed=embed)
``` im getting this error, can someone please help
heady sluice
sly hamlet
stone beacon
heady sluice
heady sluice
stone beacon
#

That's called before the bot is even loaded

#

Well damn

zenith mural
stone beacon
#

Imma look into that

sly hamlet
#

So what do I need to do?

heady sluice
#

I think discord.MessageInteraction

zenith mural
heady sluice
#

!d discord.MessageInteraction

unkempt canyonBOT
#

class discord.MessageInteraction```
Represents the interaction that a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is a response to.

New in version 2.0.

x == y Checks if two message interactions are equal.

x != y Checks if two message interactions are not equal.

hash(x) Returns the message interaction’s hash.
zenith mural
heady sluice
#

I hope so

sly hamlet
sly hamlet
#

how do i fix it?

heady sluice
#

remove it

#

you add the cog twice

sly hamlet
#
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
    await setup(self)
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 36, in setup
    cog = DiscordListsPosts(bot)
NameError: name 'DiscordListsPosts' is not defined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
    asyncio.run(main())
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
    await bot.load_extension('cogs.api')
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: NameError: name 'DiscordListsPosts' is not defined```
heady sluice
#

what's your cog called

sly hamlet
heady sluice
#

no you put an s at the end

#

😭

sly hamlet
#
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
    await setup(self)
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 33, in setup
    await cog.start_loop()
TypeError: start_loop() takes 0 positional arguments but 1 was given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
    asyncio.run(main())
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
    await bot.load_extension('cogs.api')
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: TypeError: start_loop() takes 0 positional arguments but 1 was given```
heady sluice
#

every method of a class needs self as an argument

#

you have to take self

slate swan
#

hi DeniaL

sly hamlet
#

so await self.bot.add_cog(cog)

heady sluice
heady sluice
#

bot.add_cog stays

sly hamlet
#

ok

heady sluice
#

async def start_loop(self):

sly hamlet
#

oooo ok

#
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
    await setup(self)
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 33, in setup
    await cog.start_loop()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 26, in start_loop
    await self.api.setup()
AttributeError: 'Client' object has no attribute 'setup'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
    asyncio.run(main())
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
    await bot.load_extension('cogs.api')
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: AttributeError: 'Client' object has no attribute 'setup'```
#

I did what sparky told me to do earlier on this one which is why I'm a bit confused when I read this one

heady sluice
#

I don't know what y'all mean by self.api

sly hamlet
#

Has to do with a library

heady sluice
#

and what do you want to setup on it

#

!discord.ext.commands.Cog.api

#

doesn't even exist?

paper sluice
#

(it doesn't)

heady sluice
#

(ok)

sly hamlet
paper sluice
#
        await self.api.setup()

self.api doesn't exist, what are you trying to do?

heady sluice
#

he defined it

#

but like how

#

what does discordlists look like

paper sluice
#

tf is discordlists

sly hamlet
heady sluice
#

na no way

paper sluice
sly hamlet
#

Don't know what that is

#

That's what I've been trying to refer to

heady sluice
#

sh I just got to school bye

paper sluice
sly hamlet
#

I was just doing what I was told to do

sly hamlet
paper sluice
#

i guess, run it and see

sly hamlet
#
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
    await setup(self)
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 33, in setup
    await cog.start_loop()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 26, in start_loop
    await self.api.start_loop()
  File 
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
    asyncio.run(main())
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
    await bot.load_extension('cogs.api')
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
cerulean ibex
#

Can someone help me I’m having a hard time figuring out on
“How to get notified when someone updates their GitHub, through webhook on my of my channels”

Just can’t find anywhere

sly hamlet
paper sluice
sly hamlet
paper sluice
sly hamlet
#

oop

paper sluice
#
        self.bot.loop.create_task(self.__loop(self.interval))

remove that

sly hamlet
#

So just remove await

#

??

paper sluice
#

ya

sly hamlet
#
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook``` ```py
async def start_loop(self):
        self.api.start_loop()
        print("Post Count")


async def setup(bot):
    cog = DiscordListsPost(bot)
    await bot.add_cog(cog)
    await cog.start_loop()```
paper sluice
#
def start_loop(self):
        self.api.start_loop()
        print("Post Count")


async def setup(bot):
    cog = DiscordListsPost(bot)
    await bot.add_cog(cog)
    cog.start_loop()

try this

sly hamlet
#
Extension 'cogs.api' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
paper sluice
#

nope.

sly hamlet
quaint epoch
#

👀

slate swan
#

What is your name for the coin toss game?

#

coin?

#

there are 2 answers true and false\

stiff gorge
#

wht should i import to use buttons ?

maiden fable
#

!d discord.ui.button

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
slate swan
#

um how can i get embed from msg object?

tough lance
#

!d discord.Message.embeds

unkempt canyonBOT
slate swan
tough lance
#

Np

warped mirage
#

guys i have a cog folder so everything was working fine until i added a leveling system its crashing and giving errors for quite a bit of my code

#

anyone has some time to help me fix after

strong vessel
#

how is it possible for a bot to have permission to read and send messages on a server but get the forbidden error on it when trying to send message? what permission do i need to check

#

right now i use message.channel.permissions_for(message.guild.me).read_messages and message.channel.permissions_for(message.guild.me).send_messages but somehow its not enough

spring flax
strong vessel
#

no embed

#

just text

spring flax
strong vessel
# spring flax send the full traceback
Ignoring exception in on_message
Traceback (most recent call last):
  File "bot_file.py", line 51, in on_message
    await message.channel.send(response)
  File "python3.7/site-packages/discord/abc.py", line 1067, in send
    message_reference=reference)
  File "python3.7/site-packages/discord/http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
slate swan
spring flax
#

message.embeds[0].title

tough lance
#

^

spring flax
#

!d discord.Embed.title

unkempt canyonBOT
#

The title of the embed.
This can be set during initialisation.
Can only be up to 256 characters.

slate swan
#

i tried printing items but it didnt print

spring flax
#

message.embeds returns a list of embeds, and indexing to 0 gets the first embed

#

for example:

slate swan
#

ohkay now i understand

spring flax
#

!e ```py
x = [1, 2, 3, 4]
print(x[0])

unkempt canyonBOT
#

@spring flax :white_check_mark: Your eval job has completed with return code 0.

1
slate swan
#

i thought it only return one embed

spring flax
slate swan
#

nvmd

strong vessel
# spring flax and the code?
async def on_message(message):
    if (message.channel.permissions_for(message.guild.me).read_messages and message.channel.permissions_for(message.guild.me).send_messages):
        response = "sample text"
        await message.channel.send(response)
#

i tried using a test bot, to check the behavior, and i wasn't able to replicate this forbidden error

#

i could only replicate the forbidden error by removing the permission check in my code

spring flax
strong vessel
#

i could but i don't want to process the message

spring flax
#

not sure tbh

strong vessel
#

ideally i could check for some permission instead

spring flax
#

is the traceback you posted the full one?

stiff gorge
#
Traceback (most recent call last):
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'Button' is not defined
strong vessel
spring flax
strong vessel
#

it's identical to what i would get if i didn't do the permission check for send message, then added the bot to some server channel where it could read the messages but not allowed to send messages

stiff gorge
loud junco
#

u cant

#

hmmm

strong vessel
loud junco
#

gg i forgot this

stiff gorge
#

sould i install any module for button ?

jade tartan
#
Traceback (most recent call last):
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\ticket.py", line 17, in createticket
    channel_id = int(format_args[0].strip('<').strip('>').replace('#', ''))
IndexError: list index out of range```
#
    def __init__(self, client):
        self.client = client

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def createticket(self, ctx, *args):
        format_args = list(args)

        guild_id = ctx.message.guild.id
        channel_id = int(format_args[0].strip('<').strip('>').replace('#', ''))
        title = ' '.join(format_args[1:])```
slate swan
stiff gorge
# slate swan dont, dpy 2.0 has built-in support for those
    @bot.command()
async def google(ctx):
  url = f"https://www.google.com"
  await ctx.send("Test",components=[Button(style=ButtonStyle.URL,
                                           label="Click Here", url=url)])

@bot.command()
async def google(ctx):
  url = f"https://www.google.com"
  await ctx.send("Test",components=[Button(style=ButtonStyle.URL,
                                           label="Click Here", url=url)])
placid skiff
spring flax
#
if isinstance(original_error, (commands.CommandNotFound, commands.CheckAnyFailure, disnake.HTTPException)):
  return

Even with this in my error handler, this error gets raised in terminal

disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.choices.5.name: This field is required
slate swan
placid skiff
#

uhm discord formatting

stiff gorge
#

ok

slate swan
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
loud junco
#

how to give role

placid skiff
#
@commands
async def test(ctx, *, message):
  await ctx.send(message)
slate swan
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to
use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list
of roles than the highest role of the member.
loud junco
#

but how do i give someone role

#

for example 757508305256972338

slate swan
loud junco
#

thanks

nimble plume
#

hi

#

im Newbie007

placid skiff
slate swan
#

...

loud junco
#

=.=

nimble plume
#

i have a down down menu and a list how can i add items in the down menu with list

loud junco
#

what on earth is this

#

what down down menu

vocal plover
#

dropdown I assume

nimble plume
slate swan
#

how to edit message?

nimble plume
loud junco
slate swan
nimble plume
#

pls help

#

i have a down down menu and a list how can i add items in the down menu with list

azure jackal
#

I'm trying to do something a little weird. I have a dictionary who's values are lists. Those lists are greater than 25 items long so I created a function that creates a new list and splits them up into 25 item long lists and adds them to a new dictionary. I want the user to use .menu, select a key from that new dictionary, and then send out buttons for every item in that key's value (which is a list). I think I have to use defers to accomplish this. Can anyone point to an example of something similar?

loud junco
#

i give up byebye

azure jackal
slate swan
#

how to edit message????

nimble plume
#

i have a down down menu and a list how can i add items in the down menu with list

loud junco
slate swan
nimble plume
#

help me pls i have a down down menu and a list how can i add items in the down menu with list

#

@loud junco

loud junco
#

what is down down menu bruh

nimble plume
nimble plume
loud junco
slate swan
#

how to edit message? at bot

nimble plume
azure jackal
nimble plume
#

MercyMoon is best

#

several people is bad he didnt help me

slate swan
#
help pls,how to edit message? at bot```
azure jackal
nimble plume
#

ok

loud junco
loud junco
#

@slate swan hope this helps u

nimble plume
#

no

loud junco
#

i googled it

nimble plume
#

msg = await ctx.send("hi")
await msg.edit("hello")

loud junco
#
channel = bot.get_channel(id_of_the_channel)
message = await channel.fetch_message(id_of_the_message)
await message.edit(content="the new content of the message")
``` @slate swan
nimble plume
#

channel = await bot.get_channel(id_of_the_channel).fetch_message(id_of_the_message).edit("hi")

loud junco
#

=.=

#

bruh