#discord-bots

1 messages · Page 367 of 1

slate swan
mild token
viscid hornet
#

ok thats it

latent pier
latent pier
#

Axo's Slow brain has processing issues

viscid hornet
mild token
#

you guys enjoy : ))

viscid hornet
wild coral
#

hihi, im new here and i want to learn python but i dont know where to start. i taught myself LuaU (Roblox Studio) but i'm getting a bit bored of it and i wanna extend my knowledge. if anyone sees this message, how'd you learn python? maybe i could learn the way you did

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.

wild coral
viscid hornet
#

i learnt mine in a shoddy way by learning it backwards

viscid hornet
# wild coral wdym?

well i wanted to get into coding by coding a discord bot since i used the platform quite frequently

#

but to learn a discord bot, you obviously have to know python

#

i didnt know python but i still carried on with the library

#

so the way you’re supposed to do it is:
learn python > learn the library > make a discord bot

#

i did:
make a discord bot > learn the library > learn python

wild coral
#

LMAO

#

was it slower the way you did it tho?

slim bloom
#

@viscid hornet you are the best for help 66

viscid hornet
#

it was terribly inefficient and i would definitely do it another way

#

use the resources page — its very useful

wild coral
#

gotcha, but yet, i don't know where to click on the resources page 😭 too many buttons

#

my stupid brain cant understand which button to click

golden portal
#

focus on fundamentals first, then OOP, then concurrency, those are big concepts you need to learn and discord.py uses heavily

golden portal
wild coral
latent pier
#

Inshort learn everything of basic Python upto OOP concept

wild coral
golden portal
#

pretty much just the core of python, syntax, variables, control flow, etc

#

should be smooth sailing if you've already learnt other programming language

golden portal
#

yes

wild coral
#

gotcha

#

let me take a closer look

latent pier
#

Check the before you begin part from this page

Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!

wild coral
wild coral
latent pier
#

More better you understand language more easier for you to work with library (dpy)

upbeat otter
#

Did I just read pycord

latent pier
latent pier
wild coral
#

so just learn the basics of python itself, then learn dpy

latent pier
#

Yes

golden portal
#

technically not just the basic, Object Oriented Programming (OOP) is a huge concept, i wouldn't call those basic

latent pier
#

Classes
Inheritance
Etc

latent pier
#

Could be little overwhelming as a beginner but it's easy af once you understood everything properly

slim bloom
wild coral
#

i see

#

i believe the tutorial i'm using will cover OOP, but if not, i'll just either search it up or ask here again

golden portal
viscid hornet
viscid hornet
golden portal
viscid hornet
#

idk i just booted up vscode, wrote a print(“hello world”) in js, cried when i found out about the syntax and then gave up

wanton current
#

js syntax aint even bad

latent pier
viscid hornet
#

as in using the js language

viscid hornet
viscid hornet
#

wtf do you mean equality is ===

latent pier
latent pier
#

Teach me after you understand

#

I accept you as my Sensei

wanton current
#

there's both == and === but this isnt the channel for it

viscid hornet
golden portal
#

similar to is and == in python

latent pier
#

=== means if type and value both are similar

golden portal
#

I see I guess I forgot about implicit cast js have

latent pier
#

Wtf you mean NaN or undefined just give me None

naive briar
#

That's their equivalent

wanton current
#

wb null

naive briar
#

Ah, right

mental idol
#

when i try to turn the bot on it says errno 2 and ill looked it up and i get it sorted

#

cant get it sorted*

viscid hornet
mental idol
viscid hornet
#

well there you go

mental idol
#

I have tried everything and cant get it working

viscid hornet
#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

viscid hornet
#

!traceback - this is the most important

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

mental idol
#

What do i type for that?

viscid hornet
mental idol
#

What is that?

viscid hornet
#

a traceback?

mental idol
#

I just started learning, what is that?

viscid hornet
mental idol
#

!traceback errno 2

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

viscid hornet
slate swan
#

axo stab

viscid hornet
#

send us whats in your terminal

#

also are you doing this? py try: ... except Exception as e: print(e)

viscid hornet
mental idol
wanton current
mental idol
#

its the name the file

#

its the name of the file*

viscid hornet
#

are you in vscode?

slate swan
mental idol
viscid hornet
#

you're in your user folder on the terminal

mental idol
#

thats what happens when i press play

wanton current
#

check that out

mental idol
#

So that is what i need to put in?

intents = discord.Intents.default()
client = discord.Client(intents=intents)

wanton current
#

are you using commands?

mental idol
#

the box is the bot token

viscid hornet
unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

wanton current
#

then you need to add the message content intent like so:

intents = discord.Intents.default()
intents.message_content = True

bot =commands.Bot(intents=intents)
mental idol
wanton current
#

wdym

slate swan
wanton current
mental idol
#

alright

viscid hornet
slate swan
wanton current
#

ray skywalker

mental idol
#

like that?

wanton current
#

You still need to do bot.command() and bot.event accordingly.

wanton current
#

Intents just tells Discord what additional information that you want to receive.

viscid hornet
#

@intents.command() is new - ive never seen that

mental idol
wanton current
#

client = commands.Bot(command_prefix="!", intents=intents) and remove the bot = ... line

viscid hornet
wanton current
slate swan
mental idol
#

oh

#

something happened

#

but the bot isnt online

viscid hornet
viscid hornet
blazing beacon
slate swan
wanton current
viscid hornet
wanton current
#

it used to be just "Hello, World! (now in rust)" in plain text

viscid hornet
#

fuck js man i forgot a semicolon

blazing beacon
# wanton current what if i do

how does it work, it seems annoying to have to paste it there all the time, so im assuming it just takes ur clipboard and sends it there right?

mental idol
slate swan
wanton current
wanton current
#

at least with a specific program

blazing beacon
#

gyat keeping?

mental idol
#

its said this then i think tons of error

wanton current
#

what are the errors?

blazing beacon
#

send the errors

viscid hornet
unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

wanton current
viscid hornet
wanton current
#

my condolences

mental idol
blazing beacon
#

your token is in that

wanton current
#

censors everything except token

blazing beacon
#

please do reset it asap

mental idol
#

done

wanton current
#

there should be more

mental idol
wanton current
#

that's fine

mental idol
#

nvm

wanton current
#

that's just info

mental idol
#

thats the rest

viscid hornet
#

also always send the full error, otherwise we cant help you

#

!code - and do it like this - very useful

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

mental idol
#

oh wait one secon

#

the bot is online now

#

i enabled all the intents

blazing beacon
#

noice 👍

crisp glacier
slim bloom
craggy anvil
#

how do i code my shi to do like, for every token tht it says doesn't have default pfp it puts in newtokens.txt

fast osprey
#

What do you mean by token

craggy anvil
# fast osprey What do you mean by token

like my discord token but i have alot of alts, and i put tokens from all alts i got and it goes line by line in tokens.txt and it checks each token with discord public api and if avatar is default(i coded this part already) it should js continue to next token but if it's not default it pastes that token in newtokens.txt (didnt' code this idk how)

fast osprey
#

You should not be using user tokens in automation. That is very strictly against TOS

fast osprey
#

For bots.

#

not user tokens

craggy anvil
#

i am not using in bad purposes it's my tokens all

#

then js lemme format my question better

fast osprey
#

Nobody cares if it's a "bad" purpose

#

this is against TOS

craggy anvil
#

how do i code my shi to do like, for every apple tht it says has worm inside of it it puts in newtokens.txt if doesn't have worm then it continues to next apple in apples.txt

fast osprey
#

So you're just trying to obscure the fact you're violating TOS

craggy anvil
#

nope

#

that's what i need to code

#

i am not aiming at tokens anymore i js wanna know how do i make code paste the value in .txt file in that directory

fast osprey
#

So in the last 2 minutes, you have decided you want to do the exact same thing but for an entirely different purpose

#

Disgustingly manipulative, we're not stupid

craggy anvil
#

no mate i am telling you, i didn't ask because of the part which is against tos, i didn't know it and i am sorry i wont do it but i still have more projects that have same thing to do to fill the .txt file but idk how to code it to put in txt file

velvet compass
craggy anvil
pale zenith
viscid hornet
pale zenith
#

Great emoji isn't it

viscid hornet
#

also leo go to sleep

#

its 1am

blazing beacon
#

youre on it axo

#

on the thin ice.

viscid hornet
viscid hornet
blazing beacon
#

gyatxo

viscid hornet
blazing beacon
#

SHUTUTP im not that old

viscid hornet
slim bloom
slim bloom
#

@viscid hornet ```py
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, aiohttp, random, time, datetime

color_lace = discord.Color.from_rgb(60, 161, 224)

class Automeme(commands.Cog):
def init(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
time.sleep(1)
self.auto_meme.start()

@tasks.loop(minutes=1)
async def auto_meme(self):
    try:
        cursor = self.database.cursor()
        cursor.execute("SELECT guild_id, channel_id FROM automeme")
        results = cursor.fetchall()

        for guild_id, channel_id in results:
            guild = self.bot.get_guild(guild_id)
            if guild:
                channel = guild.get_channel(channel_id)
                if channel:
                    webhooks = await channel.webhooks()
                    webhook = webhooks[0] if webhooks else await channel.create_webhook(name=self.bot.user.name)

                    async with aiohttp.ClientSession() as session:
                        async with session.get(f"https://reddit.apiwant.xyz/api/reddit/MemesESP") as response:
                            if response.status == 200:
                                data = await response.json()
                                post = data["data"]["post"]
                                meme_url = post["mediaURL"]

                                embed = discord.Embed(color=color_lace)
                                embed.set_image(url=meme_url)
                                embed.set_footer(text=f"{self.bot.user.name} | automeme | {datetime.datetime.now().strftime('%H:%M')}", icon_url=self.bot.user.avatar.url)

                                view = discord.ui.View()
                                view.add_item(discord.ui.Button(style=discord.ButtonStyle.secondary, label="Invítame", url=f"https://discord.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=70368744177663&scope=bot+applications.commands"))

                                await webhook.send(embed=embed, view=view, username=self.bot.user.name, avatar_url=self.bot.user.avatar.url)

    except Exception as e:
        print(f"Error: {e}")``` recommendations?
viscid hornet
#

nope

slim bloom
#

looks*

viscid hornet
#

yes

slim bloom
#

alr

blazing beacon
viscid hornet
viscid hornet
#

god damn it

latent pier
blazing beacon
#

mods ban him

latent pier
slim bloom
#

what is rule 11

#

😠

latent pier
slim bloom
latent pier
#

Bruh

viscid hornet
unkempt canyonBOT
#

:x: Invalid rule indices: 11

viscid hornet
#

fanks for that

latent pier
slim bloom
viscid hornet
#

never print your exceptions

latent pier
#

Forward them on your mail?

viscid hornet
latent pier
viscid hornet
#

either that or py import traceback msg = traceback.format_exc() await ctx.send(f"'''py\n{msg}\n'''")

viscid hornet
#

hes taking an exception and then doing nothing with it, other than stripping away literally everything to let him handle the exception manually

latent pier
slim bloom
viscid hornet
# latent pier

yeah thats valid because at least the traceback is outputted somewhere

#

piss

latent pier
#

Dumb

viscid hornet
#

🤫

latent pier
#

Screenshoted

slim bloom
#

what

viscid hornet
#

me sleep now

viscid hornet
#

send em or raise em

latent pier
#

!e

value = "10" 
try:
    value = int(value)
except Exception as e:
    print(e) 
unkempt canyonBOT
#

@latent pier :warning: Your 3.12 eval job has completed with return code 0.

[No output]
viscid hornet
#

😂

latent pier
#

!e

value = "ok" 
try:
    value = int(value)
except Exception as e:
    print(e) 
unkempt canyonBOT
#

@latent pier :white_check_mark: Your 3.12 eval job has completed with return code 0.

invalid literal for int() with base 10: 'ok'
slim bloom
latent pier
viscid hornet
#

goonfight 👋

latent pier
slim bloom
#

!e

value = "10" 
try:
    value = int(value)
except Exception as e:
    print(e) 
unkempt canyonBOT
#

@slim bloom :warning: Your 3.12 eval job has completed with return code 0.

[No output]
slim bloom
#

!e

value = "x" 
try:
    value = int(value)
except Exception as e:
    print(e) 
unkempt canyonBOT
#

@slim bloom :white_check_mark: Your 3.12 eval job has completed with return code 0.

invalid literal for int() with base 10: 'x'
latent pier
#

!e

value = "10" 
try:
    value = int(value)
    print(value, type(value))
except Exception as e:
    print(e) 
  ```
unkempt canyonBOT
#

@latent pier :white_check_mark: Your 3.12 eval job has completed with return code 0.

10 <class 'int'>
vapid parcel
#

What request can I do with OAuth2, to see what guilds my bot are in? This is for dashboard reasons.

naive briar
#

You can see what guilds your bot is in without it

vapid parcel
#

I am making a dashboard, aka not in python, which I would need to do OAuth2 to do it.

shrewd apex
#

few other ways are probably running a webserver along with your discord bot with endpoints to do what you want

vapid parcel
shrewd apex
#

dont use a db, make a similar end point on your bot side which gives the list of guilds etc and then fetch it using a get request

vapid parcel
#

How could I do that?

shrewd apex
vapid parcel
shrewd apex
#

you would need a common data point

  • one is a database (and db access shared between bot and dashboard)
  • webserver on bot side or seperately using the bot token to get crucial bot info
  • using the bot token in your website side to get the data
vapid parcel
shrewd apex
#

is it possible to have a discord option autocomplete based of on another

pale zenith
shrewd apex
#

aight cool ty

latent pier
#

I want a converter which takes discord.Member or ctx.message.reference.author or both as a argument if both are present there

viscid hornet
latent pier
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

timber dragon
#

What do you need help with?

latent pier
timber dragon
#

Ooh wait

latent pier
#

It should take either one of them or both if both are given and it should be a required argument not optional

timber dragon
#

That's not really possible since converters aren't called for optional args

#

Yeah you'll have to do it in the command

#

Maybe write a helper function for it

latent pier
#
@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
    await ctx.send(f'Hello {to.mention} 👋')

I found this example somewhere close to what i want

timber dragon
#

Oo I didn't think about that

#

Genius

latent pier
#

I can do

ctx.message.reference.author if ctx.message.reference else ...
timber dragon
#

I was thinking default=lambda ctx: ctx.message.reference and ctx.message.reference.resolved and ctx.message.reference.resolved.author

latent pier
#

What's resolved for?

timber dragon
#

MessageReference doesn't have an author attr

#

You need to get it from the message

#

.resolved returns the message if in cache

Edit: Correction, the api optionally returns it
MessageReference.cached_message is from dpy

latent pier
#

Wait a minute

#

Yeah understood

#

How about we change it and remove default?

#

Like for example

latent pier
#

It should respond with yours and @lament depot's id

timber dragon
#

Get the replied message from ctx.message.reference... in the command

latent pier
#

I tried 🤣
But the only problem is if i don't pass user with command it'll throw missing argument callback

timber dragon
#

Make it optional then

latent pier
#

And if i put it to optional and there's no message reference, there's no way i can raise missing argument

timber dragon
#

member: discord.Member | None = None

#

Correct

#

You can send a message from the command instead

latent pier
#

Yeah i guess that's the last option

timber dragon
#

Any reason you don't want the default thing?

latent pier
timber dragon
#

Yes

latent pier
#

Yeah I think i should use this

#

There's these too btw

@bot.command()
async def bar(ctx, cool_value: SomeType = commands.parameter(converter=MyVeryCoolConverter)):
    cool_value.foo  # no error (hurray)
class SomeType:
    foo: int

class MyVeryCoolConverter(commands.Converter[SomeType]):
    ...  # implementation left as an exercise for the reader

@bot.command()
async def bar(ctx, cool_value: MyVeryCoolConverter):
    cool_value.foo  # type checker warns MyVeryCoolConverter has no value foo (uh-oh)
timber dragon
#

You can use typing.Annotated there

#

arg: Annotated[SomeType, MyConverter]

#

But using param for it is completely fine too

latent pier
#

Ahh

#

Got it I'm gonna go try something

mental idol
unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

mental idol
#

!code @kick.error async def kick_error(ctx.error): if isintance(error, command.MissingPermissions): await ctx.send("You do not have permission to kick this person")

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

mental idol
#

why is there a red line under the bracket? iv closed the bracket on the other side

shrewd apex
#

ctx, error

#

also its isinstance

mental idol
#

alright thanks

#

it says invalid permissions

drifting arrow
#

Is there a way to log every time a command is used without having to do it manually for each command?

shrewd apex
mental idol
#

i have given the bot administer but it still isnt working

shrewd apex
mental idol
#

k

#

that bit?

shrewd apex
#

yes

mental idol
#

alright

#

the bot is working now

#

thanks

shrewd apex
#

then either of the ones i sent above

drifting arrow
#

Ty

mental idol
#

What is wrong with this code? cos there is a error and i cant find it

naive briar
#

What's the error then?

shrewd apex
#

nothing called avatar_url

naive briar
#

Ah, right

#

Too lazy to look seriously

shrewd apex
#

mhm they should state the traceback 💀

mental idol
shrewd apex
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

mental idol
#

!traceback@client.command() async def embed(ctx): embed = discord.Embed(title="dog", url="https://www.google.co.uk", description="We love dogs!", color=0xE9BD19) embed.set_author(name=ctx.author.display_name, url="https://www.youtube.com/@ArmyforLyfe", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed)

#

i just removed url and its working

shrewd apex
#

its ctx.author.display_avatar

latent pier
shrewd apex
#

avatar_url?

latent pier
#

that i doubt

shrewd apex
#

isnt that depreceated now?

latent pier
#

.avatar would work

#

.avatar.url

shrewd apex
#

yeah .avatar works but u would have None if there is no avatar

#

display_avatar would give u the default avatar in this case

latent pier
#

.avatar
.display_avatar
.default_avatar

timber dragon
#

.display_avatar = guild_avatar or .avatar or .default_avatar

timber dragon
mental idol
#

how can i fix this? the brackets are red

#

it thinks the brackets werent closed but they are

timber dragon
#

check the code above

#

also hover over it, it will (sometimes) tell you exactly what's wrong

mental idol
#

that is what it says

timber dragon
#

ah then it's above

#

could send the full code if you want us to check

mental idol
timber dragon
#

oh im blind lol

#

name= <- missing

mental idol
#

alright

#

thanks there isnt any errors now

timber dragon
#

np

slim bloom
#

@timber dragon

#

How can I get a user's banner in a slash command?

timber dragon
#

!d discord.User.banner

unkempt canyonBOT
#

property banner```
Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
timber dragon
#

make sure to read the note

limpid tapir
#

Hello !
I get this error all the time, reinstalled py-cord, no other libraries

from discord.ui import TextInput

ImportError: cannot import name 'TextInput' from 'discord.ui'

#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

timber dragon
mental idol
#

how do i install os?

slate swan
#

its a part of standard library

#

you don't have to install it

mental idol
#

alright, i dont get how to use apikeys

#

so i can use cogs

slim bloom
#

alr

slim bloom
#
Error: 'NoneType' object has no attribute 'url'```
#

banner user

#
embed.set_image(url=user.banner.url)```
timber dragon
#

the messge you replied had nothing to do with you

slim bloom
timber dragon
timber dragon
#

fetch_user takes an user id

slim bloom
# timber dragon fetch_user takes an user id
import discord
from discord.ext import commands
from discord import app_commands

color_lace = discord.Color.from_rgb(60, 161, 224)

class Banner(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @app_commands.command(name="banner", description="Muestra el banner de una persona")
    @app_commands.describe(user="el usuario a mostrar")
    async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
        try:
            user = user or interaction.user
            user = await self.bot.fetch_user(user.id)

            embed = discord.Embed(color=color_lace)
            embed.set_image(url=user.banner.url)
            await interaction.response.send_message(embed=embed)

        except Exception as e:
            await interaction.response.send_message(f"Error: {e}", ephemeral=True)

async def setup(bot):
    await bot.add_cog(Banner(bot))```
slim bloom
timber dragon
#

you should check whether user.banner isn't None

timber dragon
slim bloom
slim bloom
#

The mistake was that I had forgotten something so simple.

latent pier
slim bloom
#

good

latent pier
slim bloom
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset) for the avatar the user has.

If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar).
slim bloom
#

good

mossy jacinth
#

How is this possible to display this on a users profile in a server?

pale zenith
#

You can't say this stuff with a bot

latent oyster
#

who wants tohelp code a discord bot

vapid parcel
#

Would it be possible to run flask in a cog..?

#

Don't know much abt flask, kinda why I am asking.

eternal hound
#

what you guys think

#

Social credit

slim bloom
thin raft
eternal hound
#

well

#

to truthfully confess

#

i made it with chat gpt grumpchib

#

I KNOW

blazing beacon
#

for your punishment you shall be forced to write your next discord bot in rust

eternal hound
#

WHAT IS THAT??

#

i barely know the basics of python bro!

blazing beacon
#

mods cook him

eternal hound
#

a little of javascript and thats it

vapid parcel
eternal hound
#

pls no

eternal hound
vapid parcel
#

💀

#

Yeah someone cook this man 😭😭🙏🙏

blazing beacon
eternal hound
#

idk i think chatgpt already did it

#

i can paste the code here if you want

vapid parcel
blazing beacon
#

!resources here ya go, im not sure if you've seen it

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.

vapid parcel
#

He did not.

blazing beacon
#

🦾

vapid parcel
blazing beacon
#

thread it i guess

eternal hound
#

i didnt have space

blazing beacon
#

like how you used to run flask + bot on replit

vapid parcel
#

I have it threaded, but would I be able to put it in a cog or nah?

eternal hound
#

i removed the last part

vapid parcel
#

Uses json

eternal hound
#

tf is that

vapid parcel
eternal hound
#

brother..

vapid parcel
#

I give up 😭🙏

eternal hound
#

sorry im new

blazing beacon
#

its okay, we're all here to learn

eternal hound
#

indeed

vapid parcel
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

eternal hound
#

oh uh

blazing beacon
#

if you're really new to python and programming in general i think you should check out the resources link python sent

eternal hound
#

okay i guess

vapid parcel
#

I truly recommend like

blazing beacon
#

good luck!

eternal hound
#

everything looks to complicated!

vapid parcel
#
#

These are 2 good links, or use what the other person said.

eternal hound
vapid parcel
vapid parcel
eternal hound
#

indeed however classes and objects are hard

vapid parcel
#

I just recommend the 2 I sent. Because I am a visual learner and an interactive learner. So it's easier for me to learn from those 2 websites. But if you are better verbal, then do reading ig.

eternal hound
#

nahh, visual better for me

vapid parcel
#

🤷

#

@viscid hornet

vapid parcel
eternal hound
#

i say yes

vapid parcel
#

💀

#

@eternal hound if you can answer what a cog is, then I'll believe you 😁

vapid parcel
eternal hound
#

cog hmmm, cog, cognitive old gland

vapid parcel
#

💀

#

It's just a class.

eternal hound
#

i know, i was testing you

vapid parcel
#

Yeah fs

#

Type shit I be doing

#

Yes

blazing beacon
#

smh no rust

vapid parcel
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

eternal hound
#

OFC

vapid parcel
#

XD

#

The deletion is real

eternal hound
#

however my proposal was purely out of a hypothetical situation

vapid parcel
#

Yeah ofc

#

Who would ever attempt to hack a bank after learning all of that? 😁

blazing beacon
#

you become the bank

vapid parcel
#

You are the money

eternal hound
#

hmm i wonder who 🤫

vapid parcel
#

You are the code

#

You are 1 with the code

eternal hound
#

yeah here where i live you get like 40 to 60 k euro

slim bloom
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

eternal hound
#

per year

vapid parcel
#

You are 1 and 0s

vapid parcel
eternal hound
#

bro uses internet explorer

slim bloom
vapid parcel
#

Bros def on the first computer

eternal hound
#

what is rule 11?

vapid parcel
#

Check yourself 😁

eternal hound
#

i did just nw

blazing beacon
eternal hound
#

i have important question about coding, what is the easiest and fastest language i can learn? programming wise

eternal hound
#

really?

vapid parcel
#

Yes

eternal hound
#

its not like a ancient programming language made back in the 80s or something?

vapid parcel
#

It's the easiest language out there...

slim bloom
#

@vapid parcel

eternal hound
#

i heard assembly is easy

vapid parcel
vapid parcel
slim bloom
#

I have a question: how would I organize the cogs of my bot well?

eternal hound
#

HTML NO

#

i tried it hell nawh

vapid parcel
slim bloom
vapid parcel
#

No, show me how u load them?

#

Like the way u load them

slim bloom
#
async def load_cogs():
    for filename in os.listdir("src/cogs"):
        if filename.endswith(".py"):
            try:
                await bot.load_extension(f"src.cogs.{filename[:-3]}")
                print(Fore.LIGHTWHITE_EX + f"Cog valido: {filename[:-3]}")
            except Exception as e:
                print(Fore.LIGHTBLACK_EX + f"Cog error: {filename[:-3]}: {e}")```
vapid parcel
#

Also, cogs should have more than just 1 commands, recommend making cogs a category, not a section

vapid parcel
#

These are my cogs currently in my test bot

slim bloom
#

hahhaa

eternal hound
#

bacon bacon bacon bacon

vapid parcel
#

💀

vapid parcel
#

But seems good. I have 24 cogs. Which seems a lot imo but some are handlers for other cogs because I don't wanna make my other cogs messy

fast osprey
#

Friendly reminder that ide regions and control F exist

slim bloom
sick birch
#

this is inappropriate, please don't post stuff like this

slim bloom
sick birch
slim bloom
midnight oracle
#

How is the @discord.ext.tasks used in a Cog for a timer for example?

drifting arrow
#

Hey, is Interaction required for this function?

    async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[Choice[str]]:
        
        #Checks if the players list is populated. If not, populate it!
        if not self.players:
            self.players = await self.db.get_all_users_list()
        
        #Populates the choices the user will be able to select from.
        if current:
            choicelist = []
            for player in self.players:
                if current.lower() in player.lower():
                    choicelist.append(player)
                if len(choicelist) > 20:
                    break
            return [Choice(name=c, value=c) for c in choicelist]
        else: #Tells the users to start typing!
            default = ["Start typing a players name (preferably their in game name)"]
            return [Choice(name=d, value=d) for d in default]
#

I'm using discord choices, and this function will update the options based on what you type.

#

and I am unsure if I even need Interaction at all

#

🤔 maybe I do.

#

hhmm..

#

oh well. I'll leave this here and maybe a smart person can give me a solution or explain

#

or something :D

shrewd apex
drifting arrow
cloud dawn
drifting arrow
#

I like it the way it is tbh

#

It also works.

#

and unless your way is faster, it's fine how it is

#

Don't fuck with shit that already works, ya know?

cloud dawn
#

Yes indeed

cyan slate
#

Hey guys I am trying to make a gambling bot ( won't use irl money dw ) for my friends but I dont know how to import the code do I just run the python script and how do i get a discord bot token? Here is the code:

import discord
import random

client = discord.Client()

@client.event
async def on_ready():
print('Bot is ready')

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('!gamble'):
    result = spin_slot_machine()
    await message.channel.send(result)

def spin_slot_machine():
symbols = ['diamond', 'dirt']
spin_result = [random.choice(symbols) for _ in range(3)]
payout = calculate_payout(spin_result)
return f'Spin result: {" - ".join(spin_result)}\nPayout: {payout}'

def calculate_payout(spin_result):
if spin_result == ['diamond', 'diamond', 'diamond']:
# Adjust the odds as per your requirement (1/100)
if random.randint(1, 100) == 1:
return 'Jackpot! 2x payout'
if spin_result.count('diamond') == 2 and spin_result.count('dirt') == 1:
return 'No win'
return 'No win'

client.run('YOUR_TOKEN_HERE')

blissful crane
humble crow
#

where can I ask for help with a problem with a telegram bot?

#

I'm trying to create a telegram bot for a game with some of my friends, not being an expert in Python I tried to do everything with chat and some tutorials but I'm still having problems

https://pastebin.com/83KLaVYB

this is the code, the error it gives me now is

Traceback (most recent call last):

File "/home/ArgentAA/caccabot.py", line 2, in <module>

from telegram.ext import Updater, CommandHandler, Dispatcher

ImportError: cannot import name 'Dispatcher' from 'telegram.ext' (/home/ArgentAA/.local/lib/python3.10/site-packages/telegram/ext/init.py)

cyan slate
#

Thx and the code is good right?

upbeat otter
upbeat otter
cyan slate
#

Ty

shrewd apex
#

that would be fun but i dont have that much free time lol

#

a ton of stuff to cover

cloud dawn
shrewd apex
#

mhm

#

guides itself are easier to maintain lol

fast osprey
#

They're also just a superior format for information that isn't visual. You can't control f a video

#

And anything made by a single individual, no matter how good they are, is subject to their own biases or gaps of knowledge

cloud dawn
#

Yep, if you just want the code link a repo with a good readme for setup.

vapid parcel
#

What could I improve or add?

#

It shows unloaded cogs if there is any but none were unloaded.

slate swan
slim bloom
cloud dawn
vivid lynx
#

no one can win roast battle against me 😎

shrewd fjord
#

programer

#

well looks like you already lost, i better get going exit

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @pastel isle until <t:1715874444:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

The <@&831776746206265384> have been alerted for review.

slate swan
#

What commands should I make for a discord bot?

fast osprey
#

Find something you cannot do today on discord that you'd want to do, automate it

feral igloo
blissful crane
feral igloo
blissful crane
#

I see, well good luck

slim bloom
#

where do I ask for help for apis?

sick birch
#

wow, i was scrolled way up

final breach
#

Hello, I have a problem. I wrote this function and it works well, but the problem is:
Reactions are obtained, meaning 4 reactions, after which the function stops for a few seconds and then continues, which extends the duration of the function. Do you have any solution or another way to reach the same goal?
This function is intended to obtain the number of messages that a specific person interacted with via ID

async def get_unique_reacted_users_count(self, reports_channel: discord.TextChannel, start_date: datetime, end_date: datetime, player_id: str):
        reacted_users_count = {}
        
        async for message in reports_channel.history(limit=None, after=start_date, before=end_date, oldest_first=True):
            if len(message.reactions) == 0:
                continue
            async for user in message.reactions[0].users():
                print(f"User: {user.name} - ID: {user.id} - reaction: {message.reactions[0].emoji}")
                user_id = str(user.id)
                if user_id == player_id:
                    if user_id not in reacted_users_count:
                        reacted_users_count[user_id] = 0
                    reacted_users_count[user_id] += 1
                    break

        return reacted_users_count
#
User: raouftazi - ID: 1141478482325536859
Execution time: 0.3402230739593506 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.34035468101501465 seconds
User: raouftazi - ID: 1141478482325536859
Execution time: 0.4886913299560547 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.4888267517089844 seconds
User: raouftazi - ID: 1141478482325536859
Execution time: 0.62017822265625 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.6202952861785889 seconds
User: raouftazi - ID: 1141478482325536859
Execution time: 0.7492554187774658 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.7493700981140137 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.335648775100708 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.48604416847229 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.641549348831177 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.795395374298096 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.955857753753662 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.467280387878418 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.6337890625 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.767956733703613 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.917591333389282 seconds
User: tazidz - ID: 330475407675752460
Execution time: 11.071693658828735 seconds
User: tazidz - ID: 330475407675752460
Execution time: 15.617467164993286 seconds
User: tazidz - ID: 330475407675752460
Execution time: 15.776914596557617 seconds
User: tazidz - ID: 330475407675752460
Execution time: 15.920830726623535 seconds
User: tazidz - ID: 330475407675752460
Execution time: 16.078328371047974 seconds
vapid parcel
vapid parcel
hushed galleon
#

a more efficient option would be tracking reaction events for each user, but there's the risk of having inconsistent results if your bot goes down for a while

final breach
hushed galleon
#

er, i dont think discord has any endpoint for that

final breach
hushed galleon
#

you can certainly try to export a count of the reactions using the same endpoints (assuming it complies with developer policy and local laws), but ratelimits will still slow you down

feral igloo
#

This is pycord, when I submit the modal it comes up "Something went wrong"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.add_item(discord.ui.TextInput(label="How old are you?", placeholder="Enter your age"))
        self.add_item(discord.ui.TextInput(label="Describe yourself", style=discord.TextStyle.long, placeholder="Tell us about yourself"))

    async def callback(self, interaction: discord.Interaction):
        age = self.children[0].value
        description = self.children[1].value

        user_avatar_url = str(interaction.user.avatar_url)

        embed2 = discord.Embed(title="User Information", color=discord.Color.blue())
        embed2.add_field(name="Age: ", value=age, inline=False)
        embed2.add_field(name="About you", value=description, inline=False)
        embed2.set_thumbnail(url=user_avatar_url)

        introductions = 1240752107846504549
        target_channel = bot.get_channel(introductions)
        await target_channel.send(embed=embed2)
        await interaction.response.send_message("Thank you for introducing yourself!", ephemeral=True)```
wanton current
#

any errors?

shrewd apex
#

other than that the channel might be None

#

u can override on_error for the modal and print out any exceptions to prevent it being surpressed

vivid slate
#

how can i add a chat filter into my discord bot

feral igloo
#

This is what I get, but visual studio gives no errors 😦

shrewd apex
patent hull
#

or use instead Client|Bot.get_partial_messageable

#

so you don't rely on the cache if you only send a message to that channel

slate swan
fast osprey
drifting arrow
eternal hound
#

stupid bot

tranquil horizon
#

For create bot

upbeat otter
#

wdym

tranquil horizon
#

?

fast osprey
#

¿

dusk ermine
#

'Member' object has no attribute 'timeout_until'

Can I resolved?

tranquil horizon
#

What i do?

wanton current
#

!tag intents

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

latent pier
fast osprey
#

Make sure to only enable the intents you need.

immediate next example uses Intents.all()

wanton current
#

"do as i say, not as i do" moment

shrewd apex
#

hmm yeah iirc i was doing a bunch of examples which needed message content and members intents so i just reused some bits of code

#

hmm yeah that can be changed to just enable message_content

shrewd apex
#

ty 🙏

fast osprey
#

Happy to offer thoughts. To be honest, us support folks in dpy have been burned time and time again by people making guides in isolation, then we have to pick up the pieces. We have a comprehensive user guide in the works but it's been delayed severely. This is the tradeoff between quality and getting many eyes on content vs velocity in getting it out

shrewd apex
#

aight cool feel free to dm me or ping me here regarding this 😄

slim bloom
#

code: ```py
banners = []
for guild in self.bot.guilds:
members = [member for member in guild.members if not member.bot]
banners.extend(members)

                        random_banner = random.choice(banners)
                        banner = await self.bot.fetch_user(random_banner.id)
                        banner_url = banner.banner.url```
wanton current
#

that's code

slim bloom
#

error: py Error: 'NoneType' object has no attribute 'url'

slim bloom
wanton current
#

are you sure the user has a banner?

slim bloom
wanton current
#

check if they have a banner before adding them to the list

slim bloom
#

how

wanton current
#

Or you'd probably have to check when you fetch, nvm

slim bloom
#

ok :v

twilit grotto
wanton current
#

You can only get banner information through fetching the user though docs

twilit grotto
#

ah shit

slate swan
#

When someone talk about when should you use a json file as a database vs. using a database?

lyric solar
#

is someone awake

#

how do i make my bot usable everywhere

#

i already did the connection i think i have to add some code tho

slate swan
lyric solar
#

hold on lemme show u

lyric solar
slate swan
slim bloom
#

How can I add options within a slash command?

lyric solar
#

how do i make a thread and add a user to it in d.py?

fast osprey
#

In a forum or a regular text channel?

sick birch
lyric solar
lyric solar
unkempt canyonBOT
#
The discord.py `on_message` event

Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.

Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:

@bot.listen()
async def on_message(message):
    ...  # do stuff here

# Or...

@bot.listen('on_message')
async def message_listener(message):
    ...  # do stuff here

You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.

If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.

lyric solar
#

thank you!

hushed galleon
lament depotBOT
hushed galleon
#

!d discord.app_commands.user_install

unkempt canyonBOT
#

@discord.app_commands.user_install(func=None)```
A decorator that indicates this command should be installed for users.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.

Examples...
lyric solar
#

what can i do with this

fast osprey
#

As a warning, things on the master branch and not on a stable release are NOT supported, and not considered stable. You will not get library support on them, and they are not guaranteed to not change before release

lyric solar
#

so i need the master branch discord

#

and not the stable build

#

oh wait you mean threads right?

hushed galleon
#

not sure of its exact usage because ive never bothered to try it, but afaik you would first enable user installs in the dashboard, mark commands with one of those decorators, sync them, and then users can authorize the app so only they can see those commands

#

nah threads are stable, user installs are not

lyric solar
#

so i can just do this?

hushed galleon
#

https://github.com/Rapptz/discord.py

To install the development version, do the following:

$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[voice]

or the oneliner, pip install git+https://github.com/Rapptz/discord.py

lyric solar
#

thank you

#

do i uninstall stable branch first

hushed galleon
#

pip already treats it as a different version of discord.py, so thats automatic

lyric solar
#

am i doing it right 😭

hushed galleon
#

its a bit awkward that the docs shows func=None in the signature...

#

theres an example under it

lyric solar
#

oh

#

whoopsies

#

does this make the command only work in user installs or do they work in guilds too

#

oh wait this is cool lol

#
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)

im guessing this would work? @hushed galleon

#

do i have to wait on discord to do some things so that its properly synced

#

cuz i dont see it in dms or private channels 😔

#

oh wait

lyric solar
#

yes

lyric solar
#

if i do this:
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
it'll only work in guilds, it ignores dms and private_channels
@app_commands.user_install()
if i do this
it'll obviously only work for people who tried it themself, aka the weird feature
if i try doing this
@app_commands.guild_install()
@app_commands.user_install()
only guild install would work

#

idk how to do both of them

#

i want it to work in dms, group chats and guilds

#

im gonna try @app_commands.allowed_installs(guilds=True, users=True)

#

ok update:
it works in every guild however not private channels or whatever

#

the current decorators that i have rn is

@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)

its insanely buggy for no reason 😔

slate swan
#

if I send an embed though a slash command, why would an imgur thumbnail not load? is that a permissions thing?

upbeat otter
midnight oracle
slate swan
#

i have my images in a db, but i even tried hardcoding it to see if it's the method of the url or something

#

im guessing its the png format or something

slate swan
#

I am setting up my first discord bot and I want to keep my token secret. I checked the pinned messages and the link is broken, but I understand that I can save it to a .env file. Can someone link me further help on this issue?

#

Nevermind, I was able to reference this page on StackOverflow after lots of searching. https://stackoverflow.com/questions/63530888/how-would-i-go-about-creating-an-env-file-for-my-discord-bot-token. I would still like to point out the pinned link in this channel for this information is still broken.

slate swan
#

Can anyone check and help if the code I wrote below is appropriate for the Discord.py library? I'm pretty new to this. I'm trying to understand how checks work so I can restrict a command to users with the staff role only.

def has_specific_role(role_id):
    async def predicate(ctx):
        member = ctx.guild.get_member(ctx.author.id)
        if member is not None:
            role = discord.utils.get(member.roles, id=role_id)
            return role is not None
        return False
    return commands.check(predicate)

@bot.tree.command(name="Hello", description="Say hello to the bot.")
@has_specific_role(role id here lmao)
async def slash_command(interaction: discord.Interaction):
    await interaction.response.send_message("Hi there! I'm SERENA, nice to meet you!")

Please ping me!

shrewd apex
unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).

New in version 2.0...
slate swan
shrewd apex
#

u can use that check directly in ur case

slate swan
#

ohhh okay thank you sm I will work on it rn!

chilly cloud
#

is it advised to use @command.has_permission(), or to check for their permissions in the code itself?

shrewd apex
#

this is for slash command check examples in docs

slate swan
shrewd apex
slate swan
#

it helps a TON!

shrewd apex
#

for check failures

#

that way if u have multiple commands behind a particular perm u dont need to check it in command code again and again

chilly cloud
shrewd apex
#

not each command a global error handler

chilly cloud
#

oh

#

OHH OKAY

#

tysm

clever spade
#
@client.command(name="purge")
async def purge(ctx, amount: int):
    role_id = 1240776442229424168  # Replace with your role ID

    if role_id not in [role.id for role in ctx.author.roles]:
        embed = discord.Embed(description="You do not have the required role to use this command.", color=discord.Color.red())
        await ctx.send(embed=embed, delete_after=5)
        return

    if amount <= 0:
        embed = discord.Embed(description="Please specify a positive number of messages to delete.", color=discord.Color.red())
        await ctx.send(embed=embed, delete_after=5)
        return

    def not_pinned(message):
        return not message.pinned

    try:
        deleted_messages = await ctx.channel.purge(limit=amount, check=not_pinned)
        embed = discord.Embed(
            title="Messages Purged",
            description=f"Successfully deleted {len(deleted_messages)} messages.",
            color=discord.Color.green()
        )
        await ctx.send(embed=embed, delete_after=10)
    except discord.Forbidden:
        embed = discord.Embed(description="I do not have permission to delete messages.", color=discord.Color.red())
        await ctx.send(embed=embed, delete_after=5)
    except discord.HTTPException as e:
        embed = discord.Embed(description=f"An error occurred: {e}", color=discord.Color.red())
        await ctx.send(embed=embed, delete_after=5)

Anyone know why this wont work

clever spade
blissful crane
#

Add some prints inside

clever spade
blissful crane
#

Where'd you put the prints and did they get printed?

wispy falcon
#

hello
why does this not work?

@Bot.event
async def on_message(message):
if 'hi' in message.content:
await message.send("sup")

it says:
AttributeError: 'Message' object has no attribute 'send'

and idk what else i should do

blissful crane
wispy falcon
#

nvm

midnight oracle
# slate swan im guessing its the png format or something

png shouldn't be a problem, Discord is equiped to handle the format, why don't you try to access the image locally? It's not a good practice but you can try downloading the image and trying to access it from your files to see if the issue is with the link or the image, which I think is the link

quick gust
#

Seems to be working for me

maiden leaf
#

Anyone has ideas for features/functions to make? I've done a lot but idk what next

slate swan
#

is it okay to use json file for things like economy for public and private discord bots?

fast osprey
#

You shouldn't be using a flat json file as a database of any sort

lyric solar
#

does anyone know how to make a bot user installable and able to be used in guilds (guild install) private channels (dms and group chats)?

severe sonnet
#

how do i compare if the author is frined with someone?

#

in my case the ping input

blissful crane
severe sonnet
#

i mean

#

in friend list

#

sorry the confusion

blissful crane
#

I just told you, you can't

severe sonnet
#

i see, not even if it's in friend list

blissful crane
#

Discord bots don't get that info (not even discord users get that info)

severe sonnet
#

i see

#

guess copying someone's macro code would be unviable

#

aka unpractical

#

due to this and also the security breach

slate swan
slate swan
severe sonnet
#

uhmm, don't it was suppose to be a property of Embed?

oblique wedge
#

do you have the image = "your image"?

severe sonnet
wanton current
#

This isn't how you set an image in the embed.

oblique wedge
#

in another file?

severe sonnet
#

nope

#

from URL

wanton current
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
oblique wedge
#

import discord

async def exe_image(image):
embed = discord.Embed()
embed.set_image(url=image)
return embed

#

@severe sonnet

#

this is an example how to do it

severe sonnet
#

yeah, oio made that once you sent me this

oblique wedge
#

ok

severe sonnet
#

guess that's all

oblique wedge
#

add this:

#

and tell me if thisa works

severe sonnet
#

yeah, and it worked, gotta test with macro

oblique wedge
#

okay !

slim bloom
#

error:

#
Cog error: general: Extension 'src.cogs.general' raised an error: NameError: name 'ui' is not defined```
#

code: ```py
import discord
from discord import ui

class Questionnaire(ui.Modal, title='Questionnaire Response'):
    name = ui.TextInput(label='Name')
    answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)```
cloud dawn
#

@slim bloom What package is this?

slim bloom
#

@timber dragon

#

code: ```py
banners = []
for guild in self.bot.guilds:
for member in guild.members:
if not member.bot:
user = await self.bot.fetch_user(member.id)
if user.banner:
banners.append(user.banner.url)

                        random_banner = random.choice(banners)
                        banner_url = random_banner
                        print(f"Banner: {banner_url}")```
#

Because it does not work?

timber dragon
#

ui is not defined

#

Make sure its imported before you use it or discord.ui... works too

timber dragon
#

Also you don't need to ping me or anyone for help

slim bloom
wanton current
#

@timber dragon

slim bloom
#

and sorry

snow coral
#

does the api have hybrid commands

for a prefix/slash command

#

so i dont have to do them seperately

scarlet tiger
snow coral
wanton current
snow coral
#

is there a max for buttons on a message

#

if so what is it

fast osprey
#

25

radiant bough
#

is it possible to make the dropdown menu persistent?

naive briar
#

Yes

radiant bough
naive briar
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
naive briar
#

Where you define it

oblique wedge
#

Do anyone know how to build a chat bot ?? [like ai]

round jetty
rugged shadow
#

if you wanna make an LLM from scratch it's gonna be very hard

serene lichen
#

Hey, I'm trying to make a Discord bot but in devloper portal discord I don't have anything to add a bot to my server

fast osprey
#

The portal lets you generate an invite link with the permissions you want to request (assuming you have Bot enabled on your application)

#

A server manager has to go to that link to invite the bot. You can't add it directly from the portal

#

If it's set to private, that has to be you

slate swan
#

How would I create a command that sends embedded message through a webhook? like .publish <content>

#

not asking to be spoonfeed just cant figure this out

fast osprey
#

Which part are you having trouble with?

slate swan
#

💀

fast osprey
#

Making a command?

slate swan
#

That does that yes

fast osprey
#

No, do you know how to make a command?

slate swan
fast osprey
#

Then that wouldn't be "all of it"

slate swan
#

hmmm

fast osprey
#

Do you know how to make a webhook on discord?

slate swan
#

Mhm

fast osprey
#

Do you know how to send a message to that webhook in code?

fast osprey
#

Which library are you using?

slate swan
#

at less not yet

slate swan
#

discordpy

fast osprey
#

!d discord.Webhook.from_url

unkempt canyonBOT
#

classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
fast osprey
#

You can use this to create a Webhook object from the url discord gives you. You can then call .send on that Webhook

slate swan
#

Ah i see

#

Thx

slim bloom
#

How could I add a modal to a button?

fast osprey
#

In the button's callback, you can respond to the interaction by sending a modal

timber dragon
#

Just await interaction.response.send_modal(MyModal())

river mason
#

Don't use that library if you have a single endpoint

#

requests will work fine

nova vessel
#

How can I send a user a form when they invoke a command?

scarlet tiger
nova vessel
scarlet tiger
slim bloom
#
class Report(discord.ui.Modal, title="Reporte"):
    description = discord.ui.TextInput(label="Describe tu reporte", style=discord.TextStyle.long, placeholder="Explica qué ha sucedido...", required=True, max_length=150)
    def __init__(self, message: discord.Message):
        super().__init__(title="Reporte")
        self.message = message

    async def on_submit(self, interaction: discord.Interaction):
        try:
            await interaction.response.send_message("Reporte recibido.", ephemeral=True)
            await self.message.delete()

        except Exception as e:
            await interaction.response.send_message(f"Error: {e}", ephemeral=True)```
#

Why doesn't it delete the reported message, in this case embed?

patent hull
#

try using instead delete_original_response

slim bloom
#

ok

slim bloom
hushed galleon
slim bloom
#

embed*

hushed galleon
#

and does any error message show up in your console?

hushed galleon
#

odd, if message.delete() failed then i would have expected the "Error: {e}" to fail and then result in a double traceback being logged, given that the interaction was already responded to

slim bloom
#
async def on_submit(self, interaction: discord.Interaction):
        try:
            await interaction.response.send_message("Reporte recibido.", ephemeral=True)
            await interaction.response.delete_original_response()

        except Exception as e:
            await interaction.response.send_message(f"Error: {e}", ephemeral=True)```
hushed galleon
#

assuming something is wrong with your console not showing errors, can you try deleting the message first and then sending any traceback to discord? e.g. py try: await self.message.delete() except: import traceback message = discord.utils.escape_markdown(traceback.format_exc()) await interaction.response.send_message(message, ephemeral=True) else: await interaction.response.send_message("Reporte recibido.", ephemeral=True)

#

although for dpy, it could also mean you haven't configured logging...

#

what code do you have to start your bot? minus the token

shrewd apex
hushed galleon
unkempt canyonBOT
#

discord/ui/modal.py line 166

_log.error('Ignoring exception in modal %r:', self, exc_info=error)```
shrewd apex
#

ic

slim bloom
#

:v

#

ok wait

shrewd apex
#

i usually have that on_error overriden for this makes debugging way easier

slim bloom
#

class Report(discord.ui.Modal, title="Reporte"):
    description = discord.ui.TextInput(label="Describe tu reporte", style=discord.TextStyle.long, placeholder="Explica qué ha sucedido...", required=True, min_length=10, max_length=150)
    def __init__(self, message: discord.Message):
        super().__init__()
        self.message = message

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message("Reporte recibido.", ephemeral=True)
        await interaction.response.delete_original_response()


    async def on_error(self, interaction: discord.Interaction, e: Exception = None):
        await interaction.response.send_message(f"Error: {e}", ephemeral=True)```
#

@shrewd apex

hushed galleon
slim bloom
#

tested

hushed galleon
#

as in no message appears?

slim bloom
#

no

hushed galleon
#

also, do you use await bot.start(...) instead of bot.run()? if so, you might not have logging configured

stone fractal
#

Who can teach me to create discord bot plz?

hushed galleon
# slim bloom yeah, bot start

can you call discord.utils.setup_logging() just before bot.start() then? and then write your modal without any error handling, e.g. py async def on_submit(self, interaction: discord.Interaction): await self.message.delete() await interaction.response.send_message("Reporte recibido.", ephemeral=True)

#

configuring logging should make the modal log error tracebacks to your console as normal

patent hull