#discord-bots

1 messages Β· Page 189 of 1

gusty flax
#

u shld use a venv tho

obsidian kindle
gusty flax
#

u shld just use a venv

obsidian kindle
gusty flax
unkempt canyonBOT
#
Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
gusty flax
#

python3 -m venv env

obsidian kindle
#

nothing happned

hushed galleon
obsidian kindle
#

I mean it returned with nothing yet

#

let me try restarting

#

bot = commands.Bot(command_prefix='!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

#

what exactly do I have to do here

hushed galleon
#

^

obsidian kindle
shrewd fjord
#

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

hushed galleon
#

oh you've defined three different Bots in the same code...

shrewd fjord
#

U have 3 bot instance

obsidian kindle
#

NameError: name 'client' is not defined

shrewd fjord
#

Broooo

#

Just give code and let me help you xd

#

Remove all bot variable / instances

obsidian kindle
#

client is not defined

shrewd fjord
#

do you know how python works?

obsidian kindle
#

have removed bot

shrewd fjord
#

Um not being rude, if the answer is no, please consider learning it
.. and how Python works

shrewd fjord
obsidian kindle
shrewd fjord
#

Now try running the code

#

This wont give error except keep_alive

obsidian kindle
shrewd fjord
#

Huh?

obsidian kindle
slate swan
#

hello

shrewd fjord
obsidian kindle
#

the recent one I had sent

shrewd fjord
#

You already have defined bot instance

slate swan
#

@shrewd fjord can you help me

#

grid = [['πŸ’£' for j in range(5) in range(5)]]

shrewd fjord
obsidian kindle
slate swan
#

typeerror: 'bool' object is not interble

slate swan
slate swan
maiden pecan
#

how do i fix this

line 22, in <module>
    bot = commands.Bot(command_prefix=prefix, self_bot=True)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
shrewd fjord
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.

shrewd fjord
#

@naive briar is there any rules for self bots?

hushed galleon
#

yeah why is there a self_bot=True argument there?

obsidian kindle
slate swan
#

grid = [['πŸ’£' for j in range(5) in range(5)]]

typeerror: 'bool' object is not interble

#

@shrewd fjord

#

how to fix this

shrewd fjord
slate swan
#

u need the full thing?

shrewd fjord
#

There is no such bool objects i see on ur code

slate swan
#

@bot.slash_command()
@commands.has_role("Urzan")
async def ownermines(ctx, round_id:str):
if checker2(round_id) == False:
await ctx.send("This Round ID is Fake")
elif checker2(round_id) ==True:
encoded_round_id = base64.b64encode(round_id.encode())
hashed_round_id = hashlib.sha256(encoded_round_id).hexdigest()
binary_hashed_round_id = bin(int(hashed_round_id, 16))[2:]
grid = [['πŸ’£' for j in range(5) in range(5)]]
safe_spots = [0, 10, 20]
for spot in safe_spots:
row = spot // 5
col = spot % 5
if spot % 2 == 0:
safe_spot = int(binary_hashed_round_id[spot:spot + 5], 2) % 4
else:
safe_spot = binary_hashed_round_id[spot:spot + 5].count('1') % 5
grid[row][col + safe_spot] = '⭐'
grid_string = "\n".join([" ".join(row) for row in grid])
embed = discord.Embed(color=0x8bdbff)
embed.add_field(name="πŸ”Ž Owner Prediction",
value=f"{grid_string}")
await ctx.send(embed=embed)

slate swan
#

said that

shrewd fjord
maiden pecan
shrewd fjord
#

!traceback

unkempt canyonBOT
#

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.

slate swan
#

Ignoring exception in command ownermines:
Traceback (most recent call last):
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 310, in ownermines
grid = [['πŸ’£' for j in range(5) in range(5)]]
TypeError: 'bool' object is not iterable

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

Traceback (most recent call last):
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'bool' object is not iterable

#

@shrewd fjord

hushed galleon
shrewd fjord
hushed galleon
#

no

shrewd fjord
#

Demn

shrewd fjord
velvet compass
#

Its also very much against Discord's ToS, and they will obliterate your account

shrewd fjord
#

Yeppp

#

They can take over :)

obsidian kindle
#

in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.

#

this is what I got after running

slate swan
#

so what should i do

slate swan
#

@shrewd fjord

#

@shrewd fjord

shrewd fjord
slate swan
#

@shrewd fjord SyntaxError: invalid character 'πŸ’£' (U+1F4A3)

#

lol

obsidian kindle
shrewd fjord
#

do :bomb:

slate swan
#

k

shrewd fjord
obsidian kindle
shrewd fjord
#

!traceback

unkempt canyonBOT
#

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.

obsidian kindle
#

line 1348, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.

shrewd fjord
#

Oh wait

obsidian kindle
#

line 1348 doesnt exist

shrewd fjord
#

Yes line 1348

#

...

obsidian kindle
#

?

shrewd fjord
#

It isn't the full error then

obsidian kindle
#

it is

shrewd fjord
white citrus
#

Can someone help me please

#

I am waiting since 2 days

shrewd fjord
#

What's the matter

#

Maybe u r editing the embed before the action is taken?

obsidian kindle
# shrewd fjord It isn't the full error then

Traceback (most recent call last):
File line 287, in <module>
@client.command()
^^^^^^^^^^^^^^^^
File, line 1513, in decorator
self.add_command(result)
File bot.py", line 245, in add_command
super().add_command(command)
File, line 1348, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.

slate swan
unkempt canyonBOT
#

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.

white citrus
shrewd fjord
obsidian kindle
#

the help command

obsidian kindle
#

nothing looks wrong with that

shrewd fjord
obsidian kindle
shrewd fjord
#

just use the client

#

client=commands.Bot(command_prefix="$", intents=intents, help_command=None)

obsidian kindle
#

btw why not use .all()

shrewd fjord
static holly
#

hello, can you help me to resolve this error please?

slate swan
slate swan
static holly
gusty flax
#

What’s the problem?

static holly
#

why is this message displayed?

#

ModuleNotFoundError: No module named 'cogcmd'

obsidian kindle
#

Is there a way we can run a code for a discord bot froever

#

even when we close the window

#

for free

slate swan
slate swan
static holly
#

thanks

obsidian kindle
#

is there not other way

#

without paying

static holly
obsidian kindle
#

or running it

vocal snow
# obsidian kindle without paying

If you're a student, you could get the Github Student Developer pack for free which will give you access to a few VPS services for free

#

and AWS, GCP and Oracle have free tiers

#

although many have expressed data and privacy concerns for all of these

static holly
# slate swan what

PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot> & C:/Users/Mathieu/AppData/Local/Programs/Python/Python311/python.exe "e:/SSD externe/Python/Code/Projets/DevBot/DiscordBot/main.py" Traceback (most recent call last): File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 4, in <module> from cogcmd.cog_cmd import liste_commandes File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module> from liste_bjr import reponse_description_bjr ModuleNotFoundError: No module named 'liste_bjr' PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot>

obsidian kindle
static holly
#

anyone?

vocal snow
vocal snow
#

not sure what you mean by a subfolder, but you're probably looking for relative imports

static holly
#

look my arborescence

vocal snow
#
from .liste_bjr import ...
static holly
vocal snow
#

no, you said you were importing it in one of the package's modules

static holly
vagrant raft
#

!eval
While True:
{
print ("gg bot")
}

vocal snow
unkempt canyonBOT
#

@vagrant raft :x: Your 3.10 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     While True:
003 |           ^^^^
004 | SyntaxError: invalid syntax
static holly
#

and now i have a same error in my main file, before this, the reero is in cogcmd file

vocal snow
#

what's the error?

static holly
#
Traceback (most recent call last):
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 3, in <module>
    from cogcmd import cog_cmd, cog_info, monde, automsg
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
    from liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'liste_bjr'
PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot> 
#

ModuleNotFoundError: No module named 'liste_bjr'

vagrant raft
#

!eval
def fib(n):

a, b = 0, 1
  while a < n:
     print(a, end=' ')
     a, b = b, a+b
 print()

fib(1000)

unkempt canyonBOT
#

@vagrant raft :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     >     a, b = 0, 1
003 |     ^
004 | IndentationError: expected an indented block after function definition on line 1
vocal snow
vagrant raft
#

!eval
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)

unkempt canyonBOT
#

@vagrant raft :x: Your 3.10 eval job has completed with return code 1.

001 |   File "<string>", line 3
002 |     while a < n:
003 | IndentationError: unexpected indent
vocal snow
#

it's a module of the package; ```py
from cogcmd.listebjr import ...

vocal snow
vocal snow
#

error?

static holly
#

is not defined

vocal snow
#

what is not defined

static holly
#

your code

vocal snow
#

send the traceback man

static holly
#

I think it's not very clear I'll start from the beginning

in my main.py file i have this code:

import discord
from discord.ext import commands
from cogcmd import cog_cmd, cog_info, monde, automsg
import os
from dotenv import load_dotenv

and in my cog_cmd.py file i have this code:

import discord
from discord.ext import commands
import random
import os
from dotenv import load_dotenv
import dataclasses
from liste_bsr import reponse_description_bsr
from gage import liste_gage
import asyncio

if i start the bot i have this error in main.py

Traceback (most recent call last):
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 3, in <module>
    from cogcmd import cog_cmd, cog_info, monde, automsg
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
    from liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'liste_bjr'
PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot> 
maiden fable
#

nice

#

Good work Zef, gg

vocal snow
#

see where it's actually being raised

static holly
vocal snow
#

ok i give up

#

@maiden fable you are better at this

maiden fable
#

!traceback learning how to read and understand a traceback is very helpful in ironing out errors and bugs

unkempt canyonBOT
#

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.

maiden fable
vocal snow
#

its a module inside the cogcmd package

vocal snow
maiden fable
#

He is trying local imports?

static holly
maiden fable
#

If that doesn't work, then idk what else would
Me and Python imports are not the best friends

static holly
#

Import "codcmd.liste_bsr" could not be resolved

maiden fable
#

That is being shown in the IDE

#

Try running it directly without debugging via the command prompt

static holly
#

its cogcmd.liste_bsr

maiden fable
#

Okay yea that then just change it
Sorry I misread it

static holly
#

dont worry

#

i try it to run and reply to you

#

dont work...

maiden fable
#

What is the error?

static holly
#

i have 2 error in 2 files

maiden fable
#

Paste the error pls

static holly
#

in cog_cmd.py

Traceback (most recent call last):
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
    from cogcmd.liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'cogcmd'
maiden fable
#

okay so in the main.py, add this line of code at the top:

import os
print(os.getcwd())
static holly
#

i allready imported os

maiden fable
#

then just add the print

static holly
#

print is empty

#

no print

maiden fable
#

What the
That is not possible

#

Paste the whole output of the script here

#

wait
Add that code above all the imports too bro

static holly
#
import discord
from discord.ext import commands
from cogcmd import cog_cmd, cog_info, monde, automsg
import os
print(os.getcwd())
from dotenv import load_dotenv
maiden fable
#

Above the discord imports too

#

move the os import to the top

#

and the print statement in the second line

static holly
#

E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 5, in <module>
from cogcmd import cog_cmd, cog_info, monde, automsg
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 9, in <module>
from gage import liste_gage
ModuleNotFoundError: No module named 'gage'

#

no print here...

maiden fable
#

E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot

#

There u go
That is what was printed

#

Hey the error changed!

#

now change the gage import also to cogcmd.gage

#

in cog_cmd.py

static holly
#

ok, now i have

Traceback (most recent call last):
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
    from cogcmd.liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'cogcmd'
maiden fable
#

uh

static holly
#

WTF, but cogcmd is the folder, no?

maiden fable
#

yea

#

that is the issue lol

static holly
#

what is that?

shrewd apex
#

whats gage?

maiden fable
#

try adding a period before cogcmd so it is .cogcmd

shrewd apex
#

πŸ‘€ weird naming

maiden fable
static holly
#

it does not make sense

maiden fable
maiden fable
static holly
maiden fable
#

I have another way but it is a hacky one and I don't want you to use that since I don't think anyone really likes that lol

maiden fable
shrewd apex
maiden fable
#

You are most welcome to help with local imports
I suck at those

shrewd apex
#

much more ez so u dont end up with init.py and relative directory issues

static holly
#

the dot carcter not work

shrewd apex
#

circular import as well

maiden fable
#

This is the file tree

shrewd apex
#

and error is in?

maiden fable
#

cog_cmd

shrewd apex
#

oh ok

#

why is there even an init.py in main directory?

shrewd apex
#

i can see an init.py in cogs folder so from .list_bjr import whatever should work

static holly
#

no, if i do that, the error moves to the main.py file

supple ridge
#

!e

a = ["1", "b", "c"]

for i in range (len(a)):
   if a[i] == 'b':
       a[i] == 'k'
print(a)
unkempt canyonBOT
#

@supple ridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

['1', 'b', 'c']
supple ridge
#

huuh weird

shrewd apex
static holly
#

same error

#

πŸ˜•

vocal snow
#

although find+replace does exist nowadays πŸ™

shrewd apex
vocal snow
#

are you using pro?

shrewd apex
#

yeah

vocal snow
#

i wanted to try it

#

from studetn dev pack

shrewd apex
#

and?

vocal snow
#

is it good

shrewd apex
#

yeah op

vocal snow
#

or should i not bother

static holly
#

so what am I supposed to do?

shrewd apex
#

people may say it takes ram but i feel its indexing is totally worth it

shrewd apex
static holly
# shrewd apex and whats that?

if i write this, i dont have error in cog_cmd.py

import discord
from discord.ext import commands
import random
import os
from dotenv import load_dotenv
import dataclasses
from liste_bjr import reponse_description_bjr
from liste_bsr import reponse_description_bsr
from gage import liste_gage
import asyncio
supple ridge
#

!e

a = ["1", "b", "c"]

for i in range (len(a)):
   if a[i] == 'b':
       a[i] = 'k'
print(a)
unkempt canyonBOT
#

@supple ridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

['1', 'k', 'c']
shrewd apex
#

also #bot-commands

supple ridge
#

yea sorry couldn't find it my bad

static holly
#

and if i run the code in main.py i have a traceback:

Traceback (most recent call last):
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 5, in <module>
    from cogcmd import cog_cmd, cog_info, monde, automsg
  File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
    from liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'liste_bjr'
shrewd apex
#

why are u even importing stuff from cogs every where

supple ridge
#

lmfao

static holly
shrewd apex
shrewd apex
static holly
#

yes

shrewd apex
#

in python u either import relative to current directory but u need an init.py or u use full paths to import relative to main directory

#

also importing in a loop ie importing files like a in b and b in a cause circular loop error

#

u might want to rearrange your imports

#

try not to import cog to cog or main.py to cog vice versa

#

make utility files and import wherever needed

static holly
#

@shrewd apex this is carrying what I thought of doing. these files contain lists of character strings, nothing else, no code

shrewd apex
#

why are they in cog folder then?

static holly
#

because this is where all my bot commands are

#

in the root path i have 2 images folders, .env, main file

#

all my code is in this folder

#

with separate files according to the types of commands I have to do, to arrange and classify the code, I think it's easier with cogs

#

I just want to throw my code in the trash...

white citrus
#

Can someone help me now please

gusty flax
#

@static holly what’s ur issue

slate swan
#

I can't get my bot to connect to the site with the proxy

rare echo
#

what are you trying to do?

slate swan
#

get the proxy's ip

#

I want the bot to connect to the site to be able to retrieve its IP address and if it is in Mexico it means that the proxy works

#

the code works without the proxy

#

its my main IP

static holly
#

i have this list of caracters

#

I would like to put this list in a file from my code but in the same directory so that the code is cleaner

#

I had created a "listgage.py" file and called it in my cog, but I had errors

#

I had 3 lists for 3 different orders in 3 different files

static holly
slate swan
#

I wrote the code, it only works on the "client" on the "bot" error, what should I do?

slate swan
static holly
slate swan
#

ca donne mon ip a moi

#

pas celle du proxy

static holly
#

la connexion est autorisΓ© ou non?

slate swan
#

oui

limber walrus
#

me no english

primal token
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

slate swan
#

mb

static holly
#

je vois écrit "le système distant a refusé la connexion réseau"

static holly
#

probleme with proxy?

slate swan
#

either the script either the site

#

but its weird

#

because i activated the proxy on my pc so im not in france but logged as the proxy locaiton 'chicago'

#

and it shows the proxy ip so it means the connection is allowed

#

but no when i try to log to the site thru the script i did

static holly
#

hmmmm

#

ask them if they don't have a problem with their api at first, then you will have the last solution

white citrus
static holly
#

its your code?

slate swan
#

yep

#

!s bot.wait_for

#

!p bot.wait_for

unkempt canyonBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

#
Command Help

!pep <pep_number>
Can also use: get_pep, p

Fetches information about a PEP and sends it to the channel.

static holly
#

@white citrus paste your code here

#

or open a ticket πŸ˜‰

white citrus
static holly
white citrus
#

@static holly

static holly
#

@white citrus do you have an error?

white citrus
#

No

static holly
#

yes, the role is not added...?

#

have you tried to print as the command goes, see if you see anything strange?@white citrus

white citrus
hushed galleon
#

it doesnt seem obvious if you're actually changing anything about status_embed

gusty flax
#

What’s the problemo?

hushed galleon
#

that doesnt change the fact that you only generated the embed once

#

as far as i can tell from that code, you compute the correct emojis once, and then just re-use it throughout your prompts without updating it to match the new status each time

white citrus
hushed galleon
#

create a new embed with fresh data...?

white citrus
#

This is the embed

#

This is one line

f"> Administrator Role {c.MajaCrossMark if admin_role is None else f'{c.MajaCheckMark} {nl} > {get_admin_role}'}\n\n"```
#

If i set the admin_role the else should triggeer at message.edit

hushed galleon
#

if i say, "You have 1 cake", and i give you another cake but say "You have 1 cake" again, do you see the problem? i didnt change my response, even though i really did give you another cake

#

you're not changing your status_embed after each question, so you're not changing the initial response

white citrus
#

So how can i change it?

hushed galleon
#

run the same code at the top after every question to make a new, up-to-date response

gusty flax
#

@white citrus what’s ur problem

hushed galleon
#

yknow all of this code, literally run it again, i dont know how to explain it any simpler, you have to create a new embed or update your existing one after every choice the user makes

#

it doesnt magically repeat itself to keep up with the choices the user makes, you need to manually update it so you have a new status to edit your message with

white citrus
#

That's the big mysterious question I'm asking myself

gusty flax
#

???

hushed galleon
#

!e doing the same analogy again: ```py
n_cakes = 2 # this would be your "status embed"

Here's sending a message with the status embed

print("You have", n_cakes, "cakes")

For each setup step the user has to do:

for _ in range(4):
# Get their answer
print("Would you like a cake? [yes]")

# Update your embed to reflect the choice that the user made
n_cakes += 1

# Edit your original message with the new status embed
print("You have", n_cakes, "cakes")```
unkempt canyonBOT
#

@hushed galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | You have 2 cakes
002 | Would you like a cake? [yes]
003 | You have 3 cakes
004 | Would you like a cake? [yes]
005 | You have 4 cakes
006 | Would you like a cake? [yes]
007 | You have 5 cakes
008 | Would you like a cake? [yes]
009 | You have 6 cakes
white citrus
#

I'll take the first one and edit it

                if admin_role is None:
                    
                    SetupAdminView = SetupAdminRoleSelect(inter)
                    reply = nextcord.Embed(title="Setup β€’ Activate Administrator Role", description=f"{c.MajaSettings} Please select a role.", colour=c.blurple)
                    await org.edit(embeds=[status_embed, reply], view=SetupAdminView, attachments=[])
                    SetupAdminView.message = org                                        
                    await SetupAdminView.wait()
                    
                    await org.edit(embed=status_embed, attachments=[])
                    await asyncio.sleep(2)
                       
                                        
                else:
                    await org.edit(embeds=[status_embed, embed_wait], attachments=[])
                    await asyncio.sleep(2)```
hushed galleon
#

make your embed generation into a function, and then call it after each selection to replace the current status embed

white citrus
#

So i quess

light violet
#

i am unable to send buttons through webhooks

#
beb=os.getenv("web")
  webhook = SyncWebhook.from_url(beb)
  button1 = Button(label="❄ OKAY", style=discord.ButtonStyle.link, url='https://google.com/')
  view=View()
  View.add_item(button1)
  webhook.send(embed=embed,view=view)```
hushed galleon
# hushed galleon make your embed generation into a function, and then call it after each selectio...

yet another example: ```py
async def get_status_embed():
async with aiosqlite.connect(...) as db:
query = "SELECT admin_role, moderator_role, supporter_role, ... FROM setup WHERE guild_id = ?"
c = await db.execute(query, guild_id)
row = await c.fetchone()
return discord.Embed(description=
f"Admin Role: {...}\n"
f"Moderator Role: {...}\n"
...
)

status_embed = await get_status_embed()
message = await ctx.send(embed=embed)

if admin_role is None:
... # ask user to provide admin role, update the database, then:
status_embed = await get_status_embed()
await message.edit(embed=status_embed)

Repeat above for every prompt```

hushed galleon
light violet
#

dyno logs uses butttons

#

in it's webhook msg

hushed galleon
#

omg you totally can thats cool

#

the discord docs says it'll only work for webhooks owned by the bot

#

oh and apparently SyncWebhook doesnt support the view= parameter

light violet
#

ok

light violet
hushed galleon
#

in context to the traceback you just deleted, discord.py only officially supports handling interactions through the gateway websocket
as such, you need to have a Client/Bot instance running on a separate thread in order to send webhook messages with views, and to receive interactions when people click on them

(see also Client.fetch_webhook(), and if you're making persistent message components Client.add_view() too)

light violet
#

?

hushed galleon
#

as in manually send a message with components on it? i guess sure, but my described approach can still work for discord.py

light violet
#

ok

finite forge
#

Hey, sorry fore the non code related question but does anyone know what these are?
The dark colour boxes containing all the information. Are they just embeds? They look different from your standard embeds imo.

distant python
#

is there a on_command_error equivalent for slash commands?

#

cant find anything in docs

finite forge
distant python
#

thats a code block

#

a feature of markdown

finite forge
#

Hmm. I’ll look into this further, thanks

#

Turns out they are just embeds after all… just without the colour lol

sick birch
#

!d discord.Colour.dark_theme

unkempt canyonBOT
#

classmethod dark_theme()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x36393F`. This will appear transparent on Discord’s dark theme.

New in version 1.5.
sick birch
#

If you change your client to light theme you'll be able to see it

finite forge
#

Ye, I figured out that they were embeds. I didn’t know about the theme so that’s definitely useful. Thanks!

left dew
sick birch
#

Sure

#

But personally I prefer using the discord.Colour object as it makes it more explicit what you're doing

left dew
#

icic

#

i didn’t actually realise that was a thing

sick birch
#

I will generally also create a utility method:

@staticmethod
def _build_dark_theme_embed(*args, **kwargs) -> discord.Embed:
  if "color" in args:
    raise ValueError("_build_dark_theme_embed does not take a `color` parameter")
  return discord.Embed(*args, **kwargs)
#

Though this is not strictly necessary

left dew
#

alright thanks

white citrus
smoky sinew
#

what are examples of some big open-source bots

#

i want to get inspiration for how to implement mine

rare echo
gusty flax
sick birch
unkempt canyonBOT
#

Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!

Projects to Contribute to
β€’ Sir Lancebot - our fun, beginner-friendly bot
β€’ Python - our utility & moderation bot
β€’ Site - resources, guides, and more

Where to start

  1. Read our contribution guide
  2. Chat with us in #dev-contrib if you're ready to jump in or have any questions
  3. Open an issue or ask to be assigned to an issue to work on
sick birch
#

Ours not not really "popular" per se, but still follow good practices and design principles

#

Especially @unkempt canyon

#

Be warned, though, the codebase is quite complex

smoky sinew
#

yeah i know of that one

#

i do really like the codebase

slate swan
#

hey @sick birch

#

is anyone there to assist me

sick birch
#

Ask your question

slate swan
#

ok hold on

fading marlin
#

TIL @unkempt canyon isn't made with dpy

pliant gulch
fading marlin
#

oh, pydis_core is a whole other library that wraps dpy lmaoducky_australia

hushed galleon
hushed galleon
timid spade
#

tf is that server icon 😭

frail rock
#

is anyone familiar with the scrapetube library?

#

I can't seem to get this youtube scraper module working

#

I've literally tried everything lol

#
def video_links():
  # channel = "UChozbOPP6uOJ2UkiTZy-sgQ"
  # try:
  #     scrape = scrapetube.get_channel(channel_id='channel')
  #     videos = scrape.videos
  #     return random.choice(list(videos))
  # except Exception as e:
  #     print(f"An error occurred: {e}")
  
  # videos = scrapetube.get_channel("UChozbOPP6uOJ2UkiTZy-sgQ")

  # for video in videos:
  #   print(video['videoId'])
  #   return random.choice(video)
  # channel_id = "UChozbOPP6uOJ2UkiTZy-sgQ"
  #   videos = scrapetube.get_channel(channel_id).videos
  #   return random.choice(list(videos))

# print(video_links())

  channel_id = "UChozbOPP6uOJ2UkiTZy-sgQ"
  videos = list(scrapetube.get_channel(channel_id).videos)
  return random.choice(videos)

#  for video in videos:
#  print(video['videoID'])

main.py where I call it

    if message.content.startswith('$video'):
        video = video_links()
        await message.channel.send(video)
#

I made a bunch of comments because none of that shit works and I am trying to figure it out and I might need to go back and use some of those code blocks.

smoky sinew
#

where should i load extensions now?

#

in on_ready?

sick birch
smoky sinew
#

got it

vocal snow
smoky sinew
lament mesa
#

you're probably running the bot twice

slate swan
#

or have process_commands in a listener

abstract owl
#

any alternative i can use for await in a def function to use asyncio.sleep?

naive briar
#

Why don't just make it async

lament mesa
#

!d asyncio.loop.run_until_complete

unkempt canyonBOT
#

loop.run_until_complete(future)```
Run until the *future* (an instance of [`Future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future "asyncio.Future")) has completed.

If the argument is a [coroutine object](https://docs.python.org/3/library/asyncio-task.html#coroutine) it is implicitly scheduled to run as a [`asyncio.Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task").

Return the Future’s result or raise its exception.
lament mesa
#

or you can use the not async time.sleep, but that will block other parts of your code

abstract owl
#

yea

upbeat gust
serene lark
#
Traceback (most recent call last):
  File "/Users/x/PycharmProjects/dispy-lin/main.py", line 40, in register_commands
    await bot.rest.set_application_commands(
  File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/impl/rest.py", line 3761, in set_application_commands
    response = await self._request(route, json=[command.build(self._entity_factory) for command in commands])
  File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/impl/rest.py", line 712, in _request
    await aio.first_completed(request_task, self._close_event.wait())
  File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/internal/aio.py", line 138, in first_completed
    await next(iterator)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py", line 571, in _wait_for_one
    return f.result()  # May raise f.exception().
  File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/impl/rest.py", line 852, in _perform_request
    raise await net.generate_error_response(response)
hikari.errors.ForbiddenError: Forbidden 403: (50001) 'Missing Access' for https://discord.com/api/v10/applications/1070247718506741800/guilds/934896901256515714/commands

I enabled the scopes bot and applications.command with these Intents Intents.GUILD_INTEGRATIONS | Intents.GUILD_MESSAGE_TYPING | Intents.GUILD_PRESENCES | Intents.GUILD_VOICE_STATES

Inside the Privileged Gateway Intents I only got presence enabled. Bot also has admin perms inside the test guild.

slate swan
#

cause it seems like you don't have access to the particular applications' commands

serene lark
#

I'm trying to add application command to a guild.

#

But it's giving me hard time.

#

I could share the code?

slate swan
#

use a command handler

#

!pip hikari-lightbulb

unkempt canyonBOT
slate swan
#

!pip hikari-crescent

unkempt canyonBOT
slate swan
#

!pip hikari-tanjun

unkempt canyonBOT
slate swan
serene lark
#

I know about lightbulb but I straight off copied this from their git so idk why it's not working.

slate swan
#

recheck the application.commands scope

#

remember that you need to kick and reinvite the bot if it was already in your server

serene lark
#

Well I did it from the start, I will try to use lightbulb.

#

Will take some time since I want to handle it properly lol

#

Do you have any examples or docs for extending the bot? Like separate into extensions.

slate swan
#

they are used for organisation of your code

abstract owl
#

hey it works in input, but when i try it using discord bot it sadly doesnt work am i doing smth wrong?

@client.command()
async def name(ctx, arg1, arg2):
    arg1 = arg1.capitalize()
    try:
        with open('names.txt', 'r') as f:
            name = f.read()
        name.replace(arg1, arg2)
        with open('names.txt', 'w') as f:
            f.write(name)
        await ctx.send('File is succesfully updated.')
    except:
        await ctx.send('Error occured.')β€Šβ€Š
distant python
#

is there a on_command_error equivalent for slash commands?

vale wing
#

But yes there are

cursive spindle
#
class WelcomeGoodByeEditButtos(discord.ui.View):
    def __init__(self, styles_list:list):
        self.styles_list = styles_list
        super().__init__(timeout=None)

    def test(self):
        print(self.styles_list)

Extension 'dashboard.mainDashboard' raised an error: TypeError: test() missing 1 required positional argument: 'self'
vocal snow
#

You're probably calling the method on the class instead of an instance of it

potent light
#

How can Steam's website have 3 fields to its embed? apparently they are not adding any meta-data for such things.

cursive spindle
distant python
cursive spindle
#

im calling it here

@discord.ui.button(label='Welcome Text Type',style=test(), custom_id='WelcomeGoodByeEditButtos3', row=1)
vocal snow
cursive spindle
#

styles_list is a list with discord styles

vocal snow
#

Yes, but the methods are created when the class is created, not when an instance is created

#

So you'll need to create the button in the _init_ or another place where you can actually access the list

#

Via the instance or otherwise

cursive spindle
#

becuase i have and other buttons

#

with not need to use a styles from list

slate swan
#

how would i make a change status command?

#

so i would run .status Testing!

vocal snow
#

Do you know how to make a command?

slate swan
#

yeah

vocal snow
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
vocal snow
#

You can call this method to change the status / activity

potent light
slate swan
potent light
potent light
vocal snow
naive briar
#

Sounds be right

potent light
vocal snow
#

An option is to set the style in the init instead of the decorator, which would require minimal work

#

Or use ui.Button and add it with View.add_item

potent light
#

Where is he using test()?

#

Also wait, style = test()?! style doesn't take a function as an argument, or does it?

naive briar
#

He's calling the function

#

So the function's result is passed into the arg

potent light
#

oh my bad, yeah that's correct

#

It should rather be return self.styles_list rather than print(self.styles_list) because in this case it returns None apparently

slate swan
potent light
slate swan
potent light
slate swan
naive briar
#

Put a : after function declaration

naive briar
#

And you need to call the change_presence from a bot instance

#

Also move it up an indent to make it inside the function

slate swan
naive briar
#

No, after the function declaration

def func(): # <---
    ...
vocal snow
#

Now would be a great time to read up on functions in python

slate swan
potent light
slate swan
#

So like that?

naive briar
#

Yeah

slate swan
vocal snow
#

And commands take a "ctx" parameter

slate swan
#

So is that it or do i have to add more stuff to make the command work?

potent light
#

what will your presence change to? you need to tell it what text to change into right,

white citrus
#

How can i get all subcommands in nextcord?

naive briar
#

!d discord.ext.commands.Bot.walk_commands

unkempt canyonBOT
#

for ... in walk_commands()```
An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned
white citrus
#

My bad

#

I mean application_command.subcommands

slate swan
#

i want to run a command so like !changestatus hello πŸ™‚

#

and it would change

shrewd fjord
#

Noice

#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
shrewd fjord
slate swan
#

Idk what else to do

potent light
# slate swan i want to run a command so like !changestatus hello πŸ™‚

hello is an argument, so you have to pass it in your command then use it in change_presence()
https://www.w3schools.com/python/gloss_python_function_arguments.asp#:~:text=Information can be passed into,separate them with a comma.

shrewd fjord
slate swan
#

can i not do that

#

so say like watching 5 tickets

naive briar
#

Just pass an argument then

shrewd fjord
potent light
slate swan
slate swan
#
import discord
from discord import app_commands

import traceback

TEST_GUILD = discord.Object(0)


class MyClient(discord.Client):
    def __init__(self) -> None:

        intents = discord.Intents.default()
        super().__init__(intents=intents)

        self.tree = app_commands.CommandTree(self)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')

    async def setup_hook(self) -> None:
        # Sync the application command with Discord.
        await self.tree.sync(guild=TEST_GUILD)


class Feedback(discord.ui.Modal, title='Feedback'):

    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your name here...',
    )

    feedback = discord.ui.TextInput(
        label='What do you think of this new feature?',
        style=discord.TextStyle.long,
        placeholder='Type your feedback here...',
        required=False,
        max_length=300,
    )

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

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        traceback.print_tb(error.__traceback__)


client = MyClient()


@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):

    await interaction.response.send_modal(Feedback())


client.run('token')

Dear please tell me. I took the code from the discord py git hub. does not start. didn't change anything.

vocal snow
#

you're passing an invalid token

#

go to your application's developer portal, and click "Regenerate" in the Bot section to get a new one

slate swan
#

It didn't help... The fact is that the bot starts up if you do it according to the instructions, but this particular section of the code is not...

vocal snow
#

client.run('token') <-- this 'token' has to be replaced with your actual bot token

#

did you do that?

slate swan
#

yes

vocal snow
#

and where did you get the bot token from?

slate swan
#

This is what I put in client.run('token')

vocal snow
#

ok cool

#

and what error are you getting now?

gentle nova
#

you put token between ' ' ?

slate swan
#

I understand correctly that this command generates a modal window through a slash?

bright wedge
slate swan
#
import discord
from discord import app_commands

import traceback

TEST_GUILD = discord.Object(0)


class MyClient(discord.Client):
    def __init__(self) -> None:

        intents = discord.Intents.default()
        super().__init__(intents=intents)

        self.tree = app_commands.CommandTree(self)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')

    async def setup_hook(self) -> None:
        # Sync the application command with Discord.
        await self.tree.sync(guild=TEST_GUILD)


class Feedback(discord.ui.Modal, title='Feedback'):

    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your name here...',
    )

    feedback = discord.ui.TextInput(
        label='What do you think of this new feature?',
        style=discord.TextStyle.long,
        placeholder='Type your feedback here...',
        required=False,
        max_length=300,
    )

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

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        traceback.print_tb(error.__traceback__)


client = MyClient()


@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):

    await interaction.response.send_modal(Feedback())


client.run('token')
#

this is the code from the git hub discord py just copied and did not change anything

#

Ok and what do you want us to do about that

#

πŸ˜‚

naive briar
# slate swan

You don't have the permission to register slash commands to that guild 🀷

#

That's just the minimum effort of reading the error

heavy belfry
#

how do i use bot.load_extension("")? i am using replit and when i put the file name in this error appears Traceback (most recent call last):

File "main.py", line 17, in <module>
bot.load_extension("random_commands.py")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.8/importlib/util.py", line 98, in find_spec
raise ModuleNotFoundError(
ModuleNotFoundError: path attribute not found on 'random_commands' while trying to find 'random_commands.py'

i have no idea how to find the path for replit files and have done some research and anything that worked for other people isnt working for me D:

naive briar
#

The same way you import other python file

#

From this folder/file.py to folder.file

#

Or if in the same directory, from file.py to just file

slate swan
#

Hi, I don't have any error code but either response from my bot when I do the command !feet

import discord
from discord.ext import commands
import aiohttp
from bs4 import BeautifulSoup
import re
import asyncio

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'
}
proxies = {
"https": "http://user: password@ip:port",
}

async def main():
    async with aiohttp.ClientSession() as session:
        url = "https://ipinfo.io/json/"
        async with session.get(url, proxy=proxies['https']) as resp:
            data = await resp.json()
            print (data['country'])
            print(data['ip'])
            print(data['region'])

asyncio.run(main())

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@client.event
async def on_ready():
    print('bot is online')

@client.command()
async def feet(ctx, name):
    name = name.replace(' ', '_')
    url = f"https://www.wikifeet.com/{name}"
    await ctx.send(f"URL : {url}")
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status == 200:
                soup = BeautifulSoup(await response.text(), "html.parser")
                images = soup.find_all("img")
                if images:
                    for image in images[:3]:
                        url = "https:" + image["src"]
                        if "image" in r.content_type:
                            await ctx.send(url)
                            async with session.get(url) as r:
                                if r.status == 200:
                                    await ctx.send(file=discord.File(await r.read(), filename='image.jpg'))
                                else:
                                    await ctx.send("Aucune image trouvΓ©e.")
                        else:
                            await ctx.send("Une erreur est survenue.")

client.run('token')
slate swan
#

Does anyone knows why?

heavy belfry
potent light
# slate swan how would i do that
@bot.command()
async def changestatus(ctx, new_presence: str):
  await change_presence(status = discord.CustomActivity(name = new_presence))```
This should work.
`new_presence: str`: is the argument we pass to the function.
`change_presence()`: takes `status` parameter to decide the status of the bot.
`status`: takes a `BaseActivity` object as an argument, in this case we'll create one with `discord.CustomActivity()` then pass it to `change_presence()`.
https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.change_presence
https://discordpy.readthedocs.io/en/latest/api.html#discord.BaseActivity
naive briar
potent light
potent light
slate swan
#

it block at await CTX.send("URL :", url)

#

it doesn't print the url

potent light
#

print(url)

potent light
#

@slate swan just above it.

shrewd apex
slate swan
#

infact there was no error just my proxy take too much time lol

brazen raft
#

There's no guild with ID 0

#

You need to use an actual guild's ID to sync your commands there

slate swan
mortal oak
#

where do i host my bot?

potent light
slate swan
#

no

#

still have an error somewhere

#

hello , my bot always shows members status as offline , but his one as online .. any solution ?

vocal snow
#

*presence intents

white citrus
#

How can i get all application subcommands in nextcord?

bright wedge
slate swan
slate swan
vocal snow
#

you're trying to send a message to the bot's own dms

#

and you need presence intents, not member intents

#

(if you just want the status+activities)

#

or both if you want all the data

vocal snow
slate swan
vocal snow
white citrus
vocal snow
white citrus
#

Yeah

vocal snow
vocal snow
#

what is this supposed to show

slate swan
vocal snow
slate swan
vocal snow
#

which includes the bot

#

hence your error

#

and mass dm is going to get you ratelimited

slate swan
vocal snow
#

it's not going to get rid of the

ClientUser has no attribute create_dm

slate swan
#

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

I don't understand why it print une erreur est survenue

slate swan
slate swan
#

Remove the last else so you can see what’s making it error

shrewd apex
#

coz response content_type is not image

#

print and check

#

its prolly json

slate swan
#

Oh yea

shrewd apex
#

also whats with the feet πŸ’€

novel prairie
#

File "main.py", line 9, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content how can i fix this?

shrewd apex
#

show code

novel prairie
#

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='z!', intents=intents)

#

this is the part that is saying that it has the problem

slate swan
#

There’s no message_content to intents I guess?

shrewd apex
#

prolly message ig no idea i forgot

#

lemme check docs

#

message_content does exist

#

u sure u have the correct library?

novel prairie
#

idk

shrewd apex
unkempt canyonBOT
shrewd apex
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

β€’ The message was sent by the client

β€’ The message was sent in direct messages

β€’ The message mentions the client

This applies to the following events...

novel prairie
shrewd apex
novel prairie
#

ok

#

i did ti

#

it*

#

so how do i fix this?

slate swan
novel prairie
#

do i need to import cog to use cogs?

desert cosmos
#

like what could be the problem, last time i used wavelink.Player to make a class of my own to pass in channel.connect() as we can only pass classes made with abc disnake.VoiceProtocol this time its showing the error TypeError: Type must meet VoiceProtocol abstract base class.

#

its been long since i logged into my bot prolly something with updates ?

slate swan
lament depotBOT
abstract owl
#

for example i have a file called test.json
with the following content:

{
"696969": "abc"
}

now the 696969 is the guild id and abc is the string i want it to send. What i wanna do is whenever a command is ran and if the guild id is in test.json it gets abc or whatever and sends it.

abstract owl
#

can you elaborate a bit?

gusty flax
#

store it as like ```py
whatever_dict = {
"696969": "abc"

#in ur callback
data = whatever_dict[interation.guild.id]
}```

abstract owl
#

with open('test.json') as f:
config = json.load(f)

abstract owl
gusty flax
gusty flax
abstract owl
gusty flax
#

what is ur code now

bright wedge
#

Do not use on message events to create commands.

#

You are defining the bot twice

#

It's not

#

Just spend some hours to learn the basics!

#

Do not select any language because you can find anything ready in Google πŸ˜„

stray carbon
serene lark
lament mesa
#

theres guild.fetch_member

lament mesa
#

wait nvm, you're using hikari

slate swan
#

or it should be fetch_guild_member, either of these

serene lark
slate swan
#

it;s in the hikari.impl.rest dir

serene lark
#

Hikari is fast πŸ‘€

slate swan
#

and cool :p

serene lark
slate swan
#

that's because dpy performs a large amount of cache operations before loading the actual bot

#

hikari is cache independent

serene lark
#

everyone liked that

slate swan
#

i like the banner and logging

serene lark
#

I was kind of lost like aren't there any fetch operations

#

But it makes sense to put it neatly at the rest api

#

Like it so far, right now I got extensions etc set up so time for docker compose and put it in an image.

serene lark
slate swan
serene lark
#
    if not member:
        member = await ctx.bot.rest.fetch_member(ctx.guild_id, user)
        if not member:
            await ctx.respond("That user is not in this server.")
            return
``` quickly used this but I'm most likely going to make a function for it.
slate swan
#

fetch_member will raise an error if member is not there

#
try: 
  member = await ctx.bot.rest.fetch_member(ctx.guild_id, user)
except hikari.HTTPError:
  respond("Not in server")
serene lark
#

I have to setup an error handler too... yes.

serene lark
#

I also hoped to typehint Member but it didn't like that lol

slate swan
#

the @option decorator does it all

#
@lightbulb.option("arg_name", ..., type=hikari.User)
@lightbulb.command("foo", "description", pass_options=True)
# pass_options = True will pass the option in function signature
@lightbulb.implements(...)
async def foo_callback(ctx, arg_name):
    ...
``` you can access the provided value using `arg_name` or `ctx.options.arg_name`
serene lark
#

Could Member be typehinted? Does it look up on cache or does it fetch as well?

slate swan
#

and yeah typehint can be used, but it wont help with anything related to data conversion

heady glacier
#

Hi i am new to discord bot
i tried watching a video online and tried to make a bot using the code(basic) in the video

serene lark
#

Hmm thanks for the info I will try some things out to make it easier.

heady glacier
#

when i run the code the bot is online but the issue is the bot does not respond to the user message

#

Just a sec i will share the code

#
import discord
import os

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

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


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

    if message.content.startswith('$hi'):
     await message.channel.send('hello')   
      
my_secret = os.environ['token']
client.run(my_secret)````
#

at first i was getting some error with Intents and tried searching it up online and someone suggested to make it default

slate swan
heady glacier
#

still same issue

#

ig i messed up with the bot settings

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

slate swan
heady glacier
#
import discord
import os

from discord import Intents
from discord.ext import commands

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


client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


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

    if message.content == "hi":
     await message.channel.send('hello')   
      
my_secret = os.environ['token']
client.run(my_secret)```
#

works now πŸ‘

slate swan
#

opened a theard 1 hour ago and still not getting help

#

snif

white citrus
#

How can i get the mention of a nextcord.SlashApplicationCommand.subcommand

#

Like </test:1>

steep wedge
#

is there any way of getting a user's status

#

as in do not disturb, online, idle, xd

sick birch
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.11)") instead.
slate swan
#

I created a script in python that retrieves images from a website and sends them to the discord server where the command was executed. However I have a problem. The script doesn't filter the images so it requests 3 images (because I have a limit of 3 images) in .svg and .gif only I would like the bot to request only images ending in .jpg.
I tried to filter with py if url.endswith(".jpg"):```` and at the top I defined URL like this: py
url = "https:" + image["src"]``` but it doesn't work. It always requests .gif and .svg images.

Here's my script : https://paste.pythondiscord.com/gipefofadi

elder niche
#

I need help with this.

#

I wrote a code for a discord bot

echo wasp
elder niche
#

I just started and heres my code:

#

import discord

bot = discord.Client()

@bot.event
async def on_ready():
print("BOT IS ONLINE")

bot.run("my token")

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.

elder niche
#

'''import discord

bot = discord.Client()

@bot.event
async def on_ready():
print("BOT IS ONLINE")

bot.run("my token")'''

#

it says in the terminal

echo wasp
#

bot = discord.Client()

@bot.event
async def on_ready():
    print("BOT IS ONLINE")



bot.run("my token")'```
elder niche
#
  File "c:\Users\leoja\Documents\bot\Event Basics.py", line 3, in <module>
    bot = discord.Client()
          ^^^^^^^^^^^^^^^^
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'```
unkempt canyonBOT
echo wasp
#

that is what your missing

elder niche
#

where do i put it

echo wasp
#

example intents = discord.Intents.default() bot = commands.Bot(command_prefix="!",intents=intents)

elder niche
#

like this?

#

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

@bot.event
async def on_ready():
    print("BOT IS ONLINE")



bot.run("*my token*")```
echo wasp
#

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)```
elder niche
#
  File "c:\Users\leoja\Documents\bot\Event Basics.py", line 4, in <module>
    bot = commands.Bot(command_prefix="!", intents=intents)
          ^^^^^^^^
NameError: name 'commands' is not defined```
echo wasp
#

from discord.ext import commands

normal reef
#

How do you go about accepting files from users?
I want to do some operations on the accepted file (say a txt file which i want to take data out of)

I searched around but I only see examples about the bot sending files

mortal oak
#

how would i possibly implement a text to speech command in my bot?

elder niche
#

how do i put it offline?

#

thx btw

steep wedge
#

or are they the same thing

echo wasp
elder niche
#

i ran the code, and i wanna edit it

echo wasp
elder niche
#

how does the bot send a message after a user prompts something?

elder niche
#

no, only python

echo wasp
slate swan
#

Using discord cogs, my terminal is blank? my on_ready() event isn't triggering?

#

my bot is running but none of my events or commands are triggering

slate swan
#

it was running before

sick birch
#

Can we see where you're loading cogs?

slate swan
#
import asyncio
import discord
from discord.ext import commands
import os
import json

f = open("config.json")
data = json.load(f)
TOKEN = data["TOKEN"]

intents = discord.Intents.all()

bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)

class MyBot(commands.Bot):
    async def setup_hook(self):
        pass

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

        await bot.start(TOKEN)

asyncio.run(main())
carmine sphinx
#

hi

#

my python pip command dosen't work

carmine sphinx
#

ok nvm it worked

#

idk how that been 1 year since I have this prob and now it work

#

wtf

sick birch
#

All of your cog loading logic should be moved into setup hook

#
async def setup_hook(self):
  for filename in os.listdir('./cogs'):
    ...
slate swan
#

bc I did that before and it never worked

#

maybe i messed up the loading

sick birch
#

This is how I usually set up my bots (highly simplified):

class MyBot(commands.Bot):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

  async def setup_hook(self):
    # setup stuff here

bot = MyBot(command_prefix=".", intents=intents, ...) # notice how this is MyBot and not commands.Bot

bot.run()
slate swan
sick birch
#

!pastebin your commands

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
#

its in a cog called kick.py

#
class Kick(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reason = None

@commands.command(aliases=['k', 'boot', 'remove'])
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member: discord.Member = None, *args, reason=None):
        author = ctx.author.mention
        if not member:
            if len(args) == 0:
                await ctx.send(f":no_entry_sign: {author} mention a valid member or provide a user ID")
            try:
                user_id = int(args[0])
                member = ctx.guild.get_member(user_id)
            except ValueError:
                await ctx.send(f":no_entry_sign: {author} provide a valid user ID")
            if not member:
                await ctx.send(f":no_entry_sign: {author} The provided user ID does not belong to a member in this server")
            reason = ' '.join(args[1:]) or reason
            await member.kick(reason=reason)
            await ctx.send(f":thumbsup: Successfully kicked **{member}**")
        else:
            self.reason = reason
            await member.kick(reason=reason)
            await ctx.send(f":thumbsup: Successfully kicked **{member}**")

async def setup(bot):
    await bot.add_cog(Kick(bot))
#

@sick birch

sick birch
#

Hm
Can you do a print statement inside your setup hook?

slate swan
sick birch
#

Nah just print like hello world or something inside the setup_hook

#
async def setup_hook(self):
  print("Setup hook was called")
slate swan
#

it didn't print anything

#
2023-02-01 20:27:54 INFO     discord.client logging in using static token
2023-02-01 20:27:55 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: XXXXXXXXXXXXXXXXXX).
2023-02-01 20:28:02 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "kick" is not found
#

@sick birch

sick birch
slate swan
sick birch
#

No, I'm asking can if I can see your main.py code

slate swan
# sick birch No, I'm asking can if I can see your `main.py` code
import discord
from discord.ext import commands
import os
import json

f = open("config.json")
data = json.load(f)
TOKEN = data["TOKEN"]

intents = discord.Intents.all()


class MyBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def setup_hook(self):
        for filename in os.listdir('./cogs'):
            if filename.endswith('py'):
                await bot.load_extension(f'cogs.{filename[:-3]}')
        print("main.py setup hook was called")


bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)

bot.run(TOKEN)
sick birch
#

You still have 2 different bot instances, that's why

slate swan
#

oh my god

slate swan
#

i forgot to change it

#

i just seen it ty

slate swan
#
import discord
from discord.ext import commands
import os
import json

f = open("config.json")
data = json.load(f)
TOKEN = data["TOKEN"]

intents = discord.Intents.all()


class MyBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

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


bot = MyBot(command_prefix=".", intents=intents, help_command=None)

bot.run(TOKEN)
sick birch
slate swan
#
2023-02-01 20:35:55 INFO     discord.client logging in using static token
2023-02-01 20:35:56 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID:).
2023-02-01 20:36:05 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "kick" is not found
sick birch
#

Also add back in the print statement like you had before

slate swan
#

alri

slate swan
# sick birch Also add back in the print statement like you had before
2023-02-01 20:38:20 INFO     discord.client logging in using static token
main.py setup hook was called
2023-02-01 20:38:21 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID:).
2023-02-01 20:38:31 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "kick" is not found
sick birch
#

Looks like you're probably on an older version of discord.py then

#

What editor are you using?

slate swan
#

mmm could be

#

im using pycharm

sick birch
#

I'm not familiar with Pycharm so you'll have to research how to update packages

slate swan
#

what version is it?

sick birch
#

You need to be on at least v2.0.0

slate swan
sick birch
#

Try printing discord.__version__ right underneath your bot = MyBot(...)

#

Oh i just realized your setup hook was called

slate swan
sick birch
#

Inside your Kick class, try this:

class Kick(commands.Cog):
  def __init__(...):
    print("Kick cog is being loaded...")
    ...
sick birch
#

Try one in the setup of kick.py

#
async def setup(bot):
  print("Setup was called")
  await bot.add_cog(Kick(bot))
sick birch
#

Well that's not good
Can we see your file structure?

slate swan
#

for my kick cog?

slate swan
tired pollen
slate swan
#
for filename in os.listdir('./cogs'):
tired pollen
#

you should put kick.py in cogs folder

#

Not moderation

slate swan
#

moderation is in the cogs folder

#

im trying to organise it

#

i don;t want utils mixed with moderation yk?

tired pollen
#

Its only load file that's end with py

#

Moderation is folder not an py file

slate swan
#

yeah I see that

#

how do I load it so that its organised?

#

all files in cogs is lowkey annoying

tired pollen
#

Just put your cogs file in cogs folder

slate swan
#

aight

tired pollen
#

That's all

tired pollen
sick birch
upper root
#

Hello I wanted to know? how do I do? to print what choice an user took when using a slash command
@app_commands.choices(store=[
discord.app_commands.Choice(name="A", value=x),
discord.app_commands.Choice(name="B", value=y),
discord.app_commands.Choice(name="C", value=z)
])
Here how do I know what choice the user took

#

How would I make an if statement wether the use took option A,B,C ?

slate swan
#

i think the variable store

torn sail
#

is there a way to set maximum length of text for an app comand parameter?

#

also does the description show up on app command groups?

vale wing
#

Idk dpy events

#

Uh oh nvm it's even more weird

#

!d discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").

The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.

To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command "discord.Interaction.command") should be used.
north kindle
#

Can my bot see who joined a voice channel?

smoky sinew
north kindle
#

Or can we like, listen for a join event without being in any voice channels?

smoky sinew
#

you can listen for it without being in the channel

north kindle
#

Join event being when a user joins a voice channel

smoky sinew
#

just use the on_voice_state_update event

#

and you need the voice states intent

north kindle
north kindle
smoky sinew
#

how do i make a slash command for the default help command?

pliant gulch
#

!d discord.VoiceChannel.members

unkempt canyonBOT
north kindle
smoky sinew
north kindle
#

yeah it is

slate swan
#

excuse me but does anyone knows how to apple for message intent and the steps to get it after getting a bot verified

sick birch
potent light
smoky sinew
#

that's not why

slate swan
#
@client.command(name='invite')
async def invite(ctx, invite_code):

    proxy = {
        'https': 'https://24.230.33.96:3128'
    }

    url = f'https://discord.com/api/invite/{invite_code}'
    response = requests.get(url, proxies=proxy)

    if response.status_code == 200:
        data = response.json()
        if data['type'] == 0:
            print (f"This Invite Is Valid | Status Code: {response.status_code}")
            return await ctx.send("This Invite Is VALID")
    else:
        print (f"This Invite Is INVALID | Status Code: {response.status_code}")
        return await ctx.send("This Invite Is INVALID")

I am trying to check if a discord invite is a valid invite or not, works up until my server IP gets rate limited. Wondering if theres a way to send requests through a proxy to prevent being rate limited?

meager chasm
#

!d discord.Client.fetch_invite

unkempt canyonBOT
#

await fetch_invite(url, *, with_counts=True, with_expiration=True, scheduled_event_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gets an [`Invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite "discord.Invite") from a discord.gg URL or ID.

Note

If the invite is for a guild you have not joined, the guild and channel attributes of the returned [`Invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite "discord.Invite") will be [`PartialInviteGuild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialInviteGuild "discord.PartialInviteGuild") and [`PartialInviteChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialInviteChannel "discord.PartialInviteChannel") respectively.
slate swan
#

@meager chasm it appears to be working nicely, would you happen to know if this method has a rate limit?

fast musk
#

Everything has rate limits. Don' know invites, but if you did want to use a GET request you can look in the headers it returns

#

he library will attempt to throttle you to avoid getting rate limited based on those

slate swan
#

it appears the fetch_invite method doesnt have a rate limit, thanks @meager chasm and @fast musk

fast musk
#

Apparently my 't' is going out haha

naive briar
#

Anything that has to make API call have rate limit

slate swan
#

I'm not sure I think json doesn't store images

brazen raft
#

You should be using aiohttp over requests. aiohttp comes with discord.py and it's asynchronous. requests doesn't come with discord.py and it's synchronous

naive briar
glad cradle
slate swan
#

but I can't send the image after found it?

naive briar
#

Just read the response bytes

#

Then wrap that bytes to BytesIO and use that on discord.File then send it

slate swan
#

alrdyy done

#

it scraped the logo lmao

#

I have to filter to scrape only .jpg

indigo pilot
#
Traceback (most recent call last):
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 934, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
KeyError: 'ticket'

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

Traceback (most recent call last):
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\jishaku\features\management.py", line 61, in jsk_load
    await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ticket.master' raised an error: KeyError: 'ticket'```
anyone know why cog isnt loading?
naive briar
indigo pilot
#

thats all

#

that shouldnt effect anything

slate swan
indigo pilot
slate swan
#
@client.command()
async def feet(ctx, name):
    name = name.replace(' ', '_')
    url = f"https://www.wikifeet.com/{name}"
    await ctx.send(f"URL : {url}")
    async with aiohttp.ClientSession() as session:
        async with session.get(url, proxy=proxies['https'], headers=headers)  as response:
            if response.status == 200:
                print(response.status)
                soup = BeautifulSoup(await response.text(), "html.parser")
                images = soup.find_all("img")
                if not images:
                    await ctx.send("There's no images")
                else:
                    print("There's images")
                    for image in images[:3]:
                        url = "https:" + image["src"]
                        print(url)
                        if mimetypes.guess_extension(response.headers["Content-Type"]) in [".jpg"]:
                            async with session.get(url, proxy=proxies['https'], headers=headers) as r:
                                if r.status == 200:
                                    file = discord.File(BytesIO(await r.read()), filename='image.jpg')
                                    await ctx.send(file=file)
                                else:
                                    await ctx.send(f"Status code : {r.status}")

                        else:
                            continue
#
if mimetypes.guess_extension(response.headers["Content-Type"]) in [".jpg"]:

This line doesn't work. It doesn't filter the extension file