#discord-bots

1 messages · Page 199 of 1

tacit horizon
#
@client.command()
async def d(ctx):
   attachment = ctx.message.attachments[0]
   await attachment.save(os.path.join(os.getcwd(), attachment.filename))

How to do that with slash commend

slate swan
#

but groups would work too?

torn sail
#

yes

torn sail
slate swan
#

I feel like that's more of a simple method though

torn sail
#
@app_commands.command()
async def command(interaction, attachment: discord.Attachment):
   ...
slate swan
#

cause you can just have everything chilling at the top

tacit horizon
#

how interaction send file

slate swan
#

don't just pass in interaction in your function

tacit horizon
#

what

#

await interaction.response.send_message(file=discord.File(output_path))

slate swan
tacit horizon
#

ya

slate swan
tacit horizon
slate swan
tacit horizon
#

ok i have to send_message then followup.send

torn sail
#

So yeah defer and use followup

tacit horizon
#

what defer

slate swan
#

i agree with the guy above me

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
#

who wants to help me make a bloxflip predictor dm me. I need good, pro python dev to help me

#

would mean the world if yall could help me out

#

just dm me

torn sail
slate swan
#

i got this output here:
Roll.find_brackets() takes 1 positional argument but 2 were given

#
def find_brackets(self, **args):
        total = list()
        if args.values() not in [start, end, mod, is_outside]:
            start = list()
            end = list()
            for num, i in enumerate (args):
                if "[" in i:
                    start.append(num)
                if "]" in i:
                    end.append(num)
            print(start, end)
            mod = 1
            is_outside = True
            self.find_brackets(start, end, mod, is_outside)
        else:
            for i in range (mod, start):
                if start[i] > end[i]:
                    total.append(self.find_brackets(start, end, i, False))
                elif start[i] < end[i]:
                    total.append(start[i], end[i])
                    del end[i], start[i]
                    if(is_outside == False):
                        break
        return total
slate swan
#

hey i have a short question im new and trying to figure out why this is shwoing

naive briar
#

What is showing

merry cliff
#

But usually they can be ignored

chilly dove
ionic garden
#

if i have a giant command (2000 lines)

#

is it appropriate to break it down into multiple functions and have the actual command pass in ctx to each of them one by one?

chilly dove
#

uh yes if its 2000 line please split it up

naive briar
#

A single command with 2000 lines!? 🙀

chilly dove
#

hope that command find a way to time travel or something with that many lines

ionic garden
#

it simulates

#

an entire adventure card game rpg

slate swan
naive briar
#

Don't name function the same as imported modules or anything really

slate swan
golden portal
slate swan
white citrus
#

how can i transfer something from one class to another

slate swan
hushed galleon
smoky sinew
#

i saw

humble gulch
#

Help me make a discord bot fuckers

upbeat otter
upbeat otter
#

!rule 1

unkempt canyonBOT
humble gulch
fresh ferry
smoky sinew
#

what's wrong with it

#

the bot won't run

#

you have a while true loop and you can't do that with async

#

the while true loop will never finish and your bot will never run

fresh ferry
#

File "C:\Users\Administrator\Desktop\main.py", line 86
global current_page
^^^^^^^^^^^^^^^^^^^
SyntaxError: name 'current_page' is used prior to global declaration

smoky sinew
#

you didn't define current_page either

#

do something like current_page = 0, but you shouldn't even really use globals they're bad practice

#

!globals

unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

upbeat otter
smoky sinew
#

sometimes we have lives beyond discord

sick birch
#

I feel called out

smoky sinew
#

people will eventually help, but you need to be patient and not rude

ionic garden
#

can views be in ephemeral messages

naive briar
#

Yes

slate swan
#

i made a discord bot that can automatically process cryptocurrency purchases

#

it supports bitcoin, ethereum and litecoin

#

i have no issues i just wanted to show it off

smoky sinew
#

crypto is nice

slate swan
#

the embed is basic

smoky sinew
#

orange for bitcoin etc

#

it would look way cleaner

#

also add a “cancel button” using a view that can cancel a transaction before the money is sent

slate swan
smoky sinew
#

while it’s still expecting it

slate swan
#

i was gonna use buttons or a modal but thats too much effort

#

maybe in the future i will

smoky sinew
#

not really

#

it’s kind of simple, i might do it tomorrow

slate swan
smoky sinew
#

it’s just 20 extra lines

slate swan
#

which requires research

#

all i know is how to make a dropdown

smoky sinew
#

makes sense

slate swan
#

i only made it because i had to manually review everyones purchases

#

now i dont need to worry about that

#

automatic + faster

smoky sinew
#

thats good

#

what are you selling

vale wing
#

@slate swan do you use some crypto exchange service API or something else

smoky sinew
#

i would use a crypto library personally

slate swan
vale wing
#

Cause ik bitcoin is just purchases linked into a blockchain but where the hell is that blockchain located

slate swan
#

the crypto exchange generates address for me and then tells me how many confirmations the transaction has

#

once it reaches the required confirmations, i get the crypto sent directly to me

#

if they purchase with btc -> i receive ltc
if they purchase with ltc -> i receive btc

smoky sinew
slate swan
#

idk if im right or wrong but i think the actual blockchain for making transactions etc is blockchain.com

slate swan
#

one hour of advertising is $0.10

smoky sinew
#

it’s not run by one website

slate swan
#

idk if im right or wrong

smoky sinew
#

anyone can run their own bitcoin node

#

why do u even use crypto then just use paypal or something

slate swan
#

???????

#

u dont need to know how it works

#

its useless information to me

smoky sinew
#

then whats the point

slate swan
#

wdym whats the point

#

crypto is easy

#

and i trust it way more than something like paypal

smoky sinew
slate swan
#

for making transactions

smoky sinew
smoky sinew
slate swan
#

what even is ur point

#

just to argue

smoky sinew
#

chill out

#

oh my god i was just asking a question

slate swan
#

in a rude way

smoky sinew
#

tone is hard to interpret over the internet

smoky sinew
#

you can’t know if it was rude or not because everyone sees it differently

slate swan
#

its quite clear what u meant

smoky sinew
#

yeah what’s wrong with that message

slate swan
#

is english not ur first language or something

smoky sinew
#

actually it’s not lmao

#

that’s kind of rude though

slate swan
#

u be rude i be rude

smoky sinew
#

please stop

slate swan
#

Don’t be rude to anyone kindly read #rules

smoky sinew
#

i wasn’t being rude, im genuinely tired and half asleep right now im not trying to start anything

slate swan
#

!ot also

unkempt canyonBOT
slate swan
vale wing
echo mural
#

5Haze

#

Where is your project bruh?

smoky sinew
vale wing
#

Ah so companies just run the nodes

smoky sinew
#

you should look it up, im not great at explaining it

slate swan
echo mural
smoky sinew
vale wing
#

!d range

unkempt canyonBOT
#

class range(stop)``````py

class range(start, stop[, step])```
The arguments to the range constructor must be integers (either built-in [`int`](https://docs.python.org/3/library/functions.html#int "int") or any object that implements the [`__index__()`](https://docs.python.org/3/reference/datamodel.html#object.__index__ "object.__index__") special method). If the *step* argument is omitted, it defaults to `1`. If the *start* argument is omitted, it defaults to `0`. If *step* is zero, [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.

For a positive *step*, the contents of a range `r` are determined by the formula `r[i] = start + step*i` where `i >= 0` and `r[i] < stop`.

For a negative *step*, the contents of the range are still determined by the formula `r[i] = start + step*i`, but the constraints are `i >= 0` and `r[i] > stop`.
slate swan
#

sort the list in reverse then send to discord bot

slate swan
vale wing
slate swan
echo mural
#

what kind of bot is it?

vale wing
#

In a less expensive way

vale wing
slate swan
echo mural
vale wing
vale wing
#

Or any sort of credentials that are needed to interact with exchange API

humble gulch
smoky sinew
vale wing
#

Or it just waits for purchases

slate swan
smoky sinew
smoky sinew
slate swan
vale wing
humble gulch
smoky sinew
slate swan
vale wing
slate swan
echo mural
slate swan
humble gulch
#

Ok I understood

echo mural
#

We're not robots and that's the prblm

#

mhm

humble gulch
#

Sorry if I disturbed u

#

Extreme sorry

echo mural
#

np

#

?

smoky sinew
vale wing
#

If there's no member that can help you maybe ask chatgpt

vale wing
vale wing
echo mural
#

bruh
I'm not able to hear anything on voice channel while using discord on browser, now can I fix my browser settings

slate swan
#

its a public crypto exchange that doesnt require any information or accounts

#

only takes a 0.5% fee too

#

all i need to do is create an order and give the buyer the address and it will handle it all for me

lofty aurora
#

So like I typed..
import discord
And it said ModuleNotFoundError: no module named 'discord '

lofty aurora
vocal snow
unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

vocal snow
#

install it like that ^

#

then run your script with the python command

lofty aurora
#

Alright!

hasty granite
#

Hi! I have this code ```py
class GeneralCM(commands.Cog):
def init(self, bot: commands.Bot) -> None:
self.bot = bot

    #adds all functions in this class to the context menu
    for func in [getattr(GeneralCM, func) for func in [func for func in GeneralCM.__dict__ if not func.startswith('__')]]:
        self.bot.tree.add_command(app_commands.ContextMenu(name=func.__name__, callback=func))```

I'm getting a TypeError: context menus cannot be defined inside a class error and the cause seems to be that when I am getting the function, it is not bound to the class, how can I fix that? when I add the function manually it works fine, but I want to automate it

Also the list comprehension does return all added functions correctly

naive briar
#

It's clearly telling you that context menus can't be defined/created in a class

smoky sinew
#

whats a context menu

naive briar
#

Message/user commands

smoky sinew
#

ahhh

#

right click commands

vale wing
unkempt canyonBOT
#

inspect.getmembers(object[, predicate])```
Return all the members of an object in a list of `(name, value)` pairs sorted by name. If the optional *predicate* argument—which will be called with the `value` object of each member—is supplied, only members for which the predicate returns a true value are included.

Note

[`getmembers()`](https://docs.python.org/3/library/inspect.html#inspect.getmembers "inspect.getmembers") will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass’ custom `__dir__()`.
unkempt mauve
#

how do I send a file through a bot? is it file=file?

hasty granite
vale wing
#

Is dpy really that dumb that it doesn't allow methods to be added as context menus

#

Disnake allows that

#

What do your functions look like

hasty granite
#

thanks though!

slate swan
hasty granite
slate swan
#

oh, makes sense

#

import discord
import sys
import subprocess

client = discord.Client()

@client.event
async def on_ready():
print(f"Logged in as {client.user}")

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

if str(message.channel) == channel and message.content.startswith("#python3"):
try :
run = subprocess.run(
["python3", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")

elif str(message.channel) == "python-interpreter" and message.content.startswith("#python2"):
try :
run = subprocess.run(
["python2", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")

if name == "main":
channel = sys.argv[2] # enter channel name you want to run bot
my_secret = sys.argv[1] # enter discord bot token
client.run(my_secret)

#

in this code i am getting error
client.init() missing keyword-only arguement : 'intents'

sacred scaffold
#

hi

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.

white citrus
#

How can i find an application subcommand with the subcommand name? Like /find subcommand test

slate swan
#

!intents

#

@white citrusi am still setting same error

#

TypeError: Client.init() missing 1 required keyword-only argument: 'intents'

#

please solve this error

#

File "/home/runner/discord-bot-that-run-Python-Program/discord-bot-that-run-python-programs.py", line 5, in <module>
client = discord.Client()
TypeError: Client.init() missing 1 required keyword-only argument: 'intents'

#

!index

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

!listindex

#

can anyone tell me how to fix list index out of range error

vale wing
#

!e

a = [8, 30, 567]
print(a[2])
print(a[3])```
unkempt canyonBOT
#

@vale wing :x: Your 3.11 eval job has completed with return code 1.

001 | 567
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 | IndexError: list index out of range
naive briar
#

I was also confused by the error when I first encountered it ducky_sphere

naive galleon
#

python is 0 indexed you do realise?

#

!e

a = [8, 30, 567]
print(a[1])
print(a[2])```
unkempt canyonBOT
#

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

001 | 30
002 | 567
slate swan
# vale wing It's pretty obvious why it occurs isn't it

import os
import os
import discord
import sys
import subprocess
from discord import Intents
from discord.ext import commands

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

client = discord.Client(command_prefix="!", intents=intents)

@client.event
async def on_ready():
print(f"Logged in as {client.user}")

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

if str(message.channel) == channel and message.content.startswith("#python3"):
try :
run = subprocess.run(
["python3", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")

elif str(message.channel) == "python-interpreter" and message.content.startswith("#python2"):
try :
run = subprocess.run(
["python2", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")

if name == "main":
channel = sys.argv[2]

enter channel name you want to run bot

my_secret = sys.argv[1]

enter discord bot token

client.run(my_secret)

#

can u solve in this

#

i m still getting that error

vale wing
#

This is not really how you should run the python code with discord bot unless you limit it to yourself-only

#

Imagine someone executing os.system("sudo rm -r /*") and that's where you say goodbye to your system

naive galleon
#

Bye bye vps or computer

#

os.remove("main.py") and bye bye your bot

#

You need to sanitise input

vale wing
#

They need to completely isolate environment, there are millions of ways people can bypass the "sanitation" with

#

Similar to python's snekbox

thin raft
#

can you make a TextInput required if another text input is x?

naive briar
#

Discord don't allow you to change it when during the time that the user is using the modal

thin raft
#

okok

#

ill use two separate modals then

light violet
#
@client.command(aliases=["wl"])
async def whitelist(ctx,*,opt,user:discord.Member):
  if ctx.author.id != ctx.guild.owner.id:
    await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description="You Are Not Authorized To Use This Command.",colour=0x2f3136))
    return
  
  if db[f"{ctx.guild.id}"] not in db.keys():
    if opt in ["add"]:
      db[f"{ctx.guild.id} a"] = {
      "gname": ctx.guild.name,
      "whitelisted" : [user.id],
      }
    elif opt in ["remove","rem"]:
      db[f"{ctx.guild.id} a"] = {
      "gname": ctx.guild.name,
      "whitelisted" : [],
      }
  else:
    if opt in ["add"]:
      if user.id in db[f"{ctx.guild.id} a"]["whitelisted"]:
        await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"User  {user.mention} Is Already In Whitelist.",colour=0x2f3136))
        return
      else:
        db[f"{ctx.guild.id} a"]["whitelisted"].append(user.id)
        await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"Added {user.mention} To Whitelist.",colour=0x2f3136) )     
    elif opt in ["remove","rem"]:
      if user.id not in db[f"{ctx.guild.id} a"]["whitelisted"]:
        await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"User  {user.mention} Is Already Not In Whitelist.",colour=0x2f3136))
        return
      else:
        db[f"{ctx.guild.id} a"]["whitelisted"].remove(user.id)
        await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"Removed {user.mention} From Whitelist.",colour=0x2f3136))

why is it missing an arguement when i type

wl add 12345678

#

Command raised an exception: TypeError: whitelist() missing 1 required keyword-only argument: 'user'

#

@vale wing

thin raft
#

How do you get a category?

light violet
#

what category

thin raft
light violet
#

how

thin raft
#

:|

slate swan
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
slate swan
#

use this

thin raft
tough lance
#

Yes

slate swan
#

a category is a channel, yes

light violet
#

why do i need to get a category

#

btw

thin raft
#

Should I type hint it to CategoryChannel right?

light violet
#

help me pls

tough lance
#

Ya it'll return a CategoryChannel object

light violet
#

.

tough lance
tough lance
#

Remove the aterisk?

slate swan
#

you should be using subcommands instead of taking an argument and checking what it was

light violet
#

how to make that

#

give example please

slate swan
#

!d discord.ext.commands.group

unkempt canyonBOT
#

@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

This is similar to the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.

Changed in version 1.1: The `cls` parameter can now be passed.
slate swan
#

i think there's example in the docs, 1 min

unkempt canyonBOT
#

examples/basic_bot.py lines 63 to 76

@bot.group()
async def cool(ctx):
    """Says if a user is cool.

    In reality this just checks if a subcommand is being invoked.
    """
    if ctx.invoked_subcommand is None:
        await ctx.send(f'No, {ctx.subcommand_passed} is not cool')


@cool.command(name='bot')
async def _bot(ctx):
    """Is the bot cool?"""
    await ctx.send('Yes, the bot is cool.')```
slate swan
#

here

light violet
#

ohk

#

thenks

slate swan
#

Hi, I was trying to make an embed as usual for my bot

score_embed = discord.Embed(title="Scoreboards", description= None)
        reaction_embed = discord.Embed(title="Grab your team role here!",
                                       description="Teams are randomized for balance.")

and further into the code,

  score_embed.add_field(name=role.name, value="0")

But for some reason it spits out this error:

    score_embed.add_field(name=role.name, value="0")
AttributeError: 'NoneType' object has no attribute 'name'

I have no idea why an already created embed is defaulting to None. Both pieces of code belong to the same command - start.

#

When I run the same file on Python itself, it returns this error:

NameError: name 'score_embed' is not defined

#

Both the definition and the code trying to add a field lie in the same scope

naive briar
#

Show the full code

#

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

Here's the entire code for the command start

#

This is old code written for previous d.py versions and I'm currently updating it, I've also checked the docs for any inconsistencies in version 2.0 but couldn't find any

proud apex
#

is it possible to make custom cooldown in slashes?

quick gust
twin nest
#

Is it possible to edit msg in peoples DM?

slate swan
#

i am getting this error pls tell me what is wrong with code

#

ImportError: cannot import name 'constants' from partially initialized module 'bot' (most likely due to a circular import) (/home/runner/bot-1/bot/bot.py)

radiant bough
#

Anybody got an idea for utility command?

naive briar
light violet
#
@client.event
async def on_ready():
  global guild
  guild = await client.fetch_guild(guildid)
  l.info(f"Watching {guild.name} {guild.member_count}")```

i am getting member count as None
#

@naive briar

slate swan
slate swan
unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

light violet
#

@slate swan ialr have discord.Intents.all()

#

Enabled in previous lines

slate swan
#

ah yes member info isnt available in fetched guilds

#

you'll have to use get

light violet
#

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

merry anvil
#

What is the problem?

#

from selenium import webdriver

driver= webdriver.Chrome()

url="https://www.hepsiburada.com/dyson"
driver.get(url)
my_element=driver.find_element("id","addToCart")
my_element.click()

#

ı runned this codes

slate swan
#

!e

def find_brackets(**args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total

print(find_brackets(2d6+[5*1d4]/1d3))

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 26
002 |     print(find_brackets(2d6+[5*1d4]/1d3))
003 |                         ^
004 | SyntaxError: invalid decimal literal
slate swan
#

!e

def find_brackets(**args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total

print(find_brackets("2d6+[5*1d4]/1d3"))

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 26, in <module>
003 | TypeError: find_brackets() takes 0 positional arguments but 1 was given
slate swan
#

!e

def find_brackets(**args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total

print(find_brackets([2d6],[[5],[1d4],[1d3]]))

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 26
002 |     print(find_brackets([2d6],[[5],[1d4],[1d3]]))
003 |                          ^
004 | SyntaxError: invalid decimal literal
slate swan
#

anyone up to help, from my discord bot i receive this error:

Roll.find_brackets() takes 1 positional argument but 2 were given

#

it don't even enter the function

def find_brackets(self, **args):
        total = list()
        if args.values() not in [start, end, mod, is_outside]:
            start = list()
            end = list()
            for num, i in enumerate (args):
                if "[" in i:
                    start.append(num)
                if "]" in i:
                    end.append(num)
            print(start, end)
            mod = 1
            is_outside = True
            total = self.find_brackets(start, end, mod, is_outside)
        else:
            for i in range (mod, start):
                if start[i] > end[i]:
                    total.append(self.find_brackets(start, end, i, False))
                elif start[i] < end[i]:
                    total.append(start[i], end[i])
                    del end[i], start[i]
                    if(is_outside == False):
                        break
        return total
#

pivot = self.find_brackets(args_result)

glad cradle
#

**args actually is **kwargs is this intended?

#

it should be *args

slate swan
#

args is just the name for kwargs

glad cradle
#

then you're calling it in the wrong way

glad cradle
#

**kwargs means that the function can take any keyword argument

your function is accepting self that is automatically passed by python and an indefinite numbers of kwargs, however you're passing a positional argument when calling the function, python is passing an argument too and here's the reason why you got the error

slate swan
#

guess when i use kwargs i need to change something

#

but what?

glad cradle
#

what's the type of args_result?

#

a tuple?

slate swan
#

pattern = re.compile(r"[+-*\/]")
args_result = pattern.split(args)

#

args = 2d6+[5*1d4]/1d3

#

or anything that input into this:

@commands.command(aliases = ['r', 'diceroll', 'dice_roll', 'dice'])
    async def roll(self, ctx, args):
glad cradle
#

so it's a list, isn't it?

slate swan
glad cradle
#

ok, I would make find_brackets accepting *args, you'll call it as self.find_brackets(*args_result)

#

args will be in your code a tuple, so you need to remove any inexistent method

slate swan
#

ok

#

accepting args...

#

uhmmm

glad cradle
#

you can't accept it as kwargs

slate swan
#

like this?

glad cradle
#

you could take it directly as list too

glad cradle
glad cradle
slate swan
#

will i need to change this too?

glad cradle
#

essentially you're just swapping from list to tuple and it's useless imho

glad cradle
slate swan
#

like this?

glad cradle
#

yeah but read the message that I wrote above

slate swan
#

guess i will need to remove .values() thing

#

remving the .values() thing i get this

#

well, i don't know how i will remove the inexistent methods

slate swan
#

i never messed with *args and **kwargs, so it's a new thing for me

low ledge
smoky sinew
slate swan
#

bit it all meant to not being in that

slate swan
slate swan
#

like, i'm planning to when it's just 1 arg it makes the first thing

#

else it just pass to the other thing

#

ops, i mean how many args is in the input

#

tat's what i'm trying to check

smoky sinew
slate swan
#

cus it printed 4 instead of just one

#

guess i need to gather the number of lists

#

like, if it just have 1

#

or i guess if there is 1 thing

#

or 4

#

i'm planning to [2, 4, 6, 8] being counted as 1

#

while 2, 4, 6, 8 being counted as 4

smoky sinew
#

that doesn't make sense

#

func(*[2, 4, 6, 8]) this is 4

#

func(*[[2, 4, 6, 8]]) this is 1

slate swan
#

whats the discord testers server link?

civic fractal
modern furnace
wooden lake
#

Helloo, I'm having problems with the token and wanted to ask if someone could help.. I get the error:
Client.run() missing 1 required positional argument: 'token'
But it isn't missing in my code.
My code in that line is:
client.run(discord_token)
And I have defined "client" and "discord_token" in another file and imported it correctly
I also get the same error when I put the token in directly.

naive umbra
clear elm
#

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

clear elm
#

how do i make it so only the author of the command can use the select menu?

dim cosmos
#

Read the docs

#

It'll help

bright wedge
clear elm
#

https://paste.pythondiscord.com/vimevojusi
error

  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 87, in training
    view = DropdownView(interaction.user)
TypeError: DropdownView.__init__() missing 1 required positional argument: 'author'

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

Traceback (most recent call last):
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'training' raised an exception: TypeError: DropdownView.__init__() missing 1 required positional argument: 'author'```
bright wedge
dim cosmos
bright wedge
#

Or only the author?

clear elm
bright wedge
#

That's why I suggest that.

clear elm
#

but i want onyl the uathor to use it

dim cosmos
#

He wants it only to be used

#

Everyone can see it but only the author can use it

bright wedge
#

Pass a argument in the view.

bright wedge
#

Pass the new argument(interaction.user) in the init of the view and then define it as self.author or self.whatever

winged bison
#
line 10, in <module>
    client.run('DiscordToken')
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
#

someone help please

#

i don't understand why i got this erorr

clear elm
#
class DropdownView(discord.ui.View):
    def __init__(self, author, bot, timeout=30):
        self.bot = bot
        super().__init__(timeout=timeout)

        self.add_item(Dropdown(self.bot))
        self.author = author

    async def interaction_check(self, interaction: discord.Interaction):
        return interaction.user.id == self.author.id```
bright wedge
winged bison
#
line 10, in <module>
    client.run('DiscordToken')
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
#

someone help

dim cosmos
winged bison
dim cosmos
#

Do you have the proper intents enabled

clear elm
winged bison
#

where i check that

dim cosmos
#

Why are you asking me

#

Developer portal

bright wedge
dim cosmos
#

Bot application info

#

Scroll down a bit you'll see intents

#

Make sure you enable the ones you're using

winged bison
#

Some Gateway Intents require approval if your bot is verified. If your bot is not verified, you can toggle those intents below to access them.

PRESENCE INTENT

clear elm
# bright wedge Seems ok, try it.
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 81, in training
TypeError: DropdownView.__init__() missing 1 required positional argument: 'bot'

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

Traceback (most recent call last):
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'training' raised an exception: TypeError: DropdownView.__init__() missing 1 required positional argument: 'bot'```
dim cosmos
#

Yeah

winged bison
dim cosmos
#

🤦‍♂️

smoky sinew
#

there is no bot argument

#

if there is you need to pass it

bright wedge
#

view (bot=define the bot,author= define the author).

smoky sinew
#

you only passed 2 or 3 arguments

winged bison
bright wedge
#

And idk why you are passing the bot as argument.

winged bison
#

help me instead

dim cosmos
#

Bro it's a simple button how can't you find it

winged bison
#

there isnt tho

dim cosmos
#

Oh my god

bright wedge
#

xD

winged bison
#

if that is what u mena

dim cosmos
bright wedge
dim cosmos
#

It's not rocket science

winged bison
winged bison
dim cosmos
#

Where do u have ur intents defined

clear elm
dim cosmos
#

In the code

winged bison
# dim cosmos In the code
Exception has occurred: ClientConnectorSSLError
Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)

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

  File "C:\Users\My.Name\import discord.py", line 10, in <module>
    client.run("DiscordToken")
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
winged bison
dim cosmos
#

Just show me the intents part

winged bison
# dim cosmos Just show me the intents part
import discord

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

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game(name="Watching my self get worked on"), status=discord.Status.online)

client.run("discordToken")
#

the whole script

dim cosmos
#

Did you enable all the intents

#

There's 3

winged bison
dim cosmos
#

Did you save changes

winged bison
#

yes

clear elm
dim cosmos
#

Idk reset ur token & restart

winged bison
bright wedge
winged bison
clear elm
#

just because im confused because i haven't done this before, doesn't mean that i don't understand basic python

wooden lake
#

I'm having problems with the discord token, I get this error:
Client.run() missing 1 required positional argument: 'token'
But it isn't missing in my code.
My code in that file is:

     if __name__ == '__main__':
        client.run(discord_token)```
And I have defined "client" and "discord_token" in another file
I also get the same error when I put the token in directly.
dim cosmos
bright wedge
dim cosmos
#

It's discord.Intents.all()

winged bison
dim cosmos
#

That should do it

winged bison
#

same error

#

oh i forgot to mention

#

i get an anti virus notification every time i do run it

#

if that maybe messes it up or something

dim cosmos
#

🤦‍♂️

winged bison
#

what did i do wrong now

bright wedge
#

don't be rude, it's not necessary after all.

winged bison
#

@dim cosmos

sacred vigil
# winged bison what did i do wrong now

asked chatgpt,
answer:
This error message suggests that there is a problem with the SSL/TLS handshake when the code is trying to connect to the Discord server using the aiohttp library. Specifically, the SSL/TLS handshake failed because of a SSLV3_ALERT_HANDSHAKE_FAILURE error.

This error could be caused by a number of things, including an incorrect SSL configuration, outdated SSL libraries, or network connectivity issues. Here are a few things you could try to resolve the issue:

Check your network connectivity: Make sure that your internet connection is stable and there are no firewall or network configuration issues that could be blocking the connection.

Update your SSL libraries: Make sure that your SSL libraries are up to date and there are no known vulnerabilities that could be causing the issue.

Check your SSL configuration: Ensure that your SSL configuration is correct and matches the server requirements. If possible, try to connect to the server using a different SSL version or cipher suite.

Try using a different library: If the problem persists, you could try using a different library to connect to the Discord server, such as the Requests library.

If none of these steps work, it might be worth contacting the Discord support team to see if they can provide any additional assistance.

clear elm
#

view DropdownView(bot=bot, author= author, interaction.user)

dim cosmos
winged bison
bright wedge
#

Pass the right arguments in your object.

winged bison
clear elm
#

File "main.py", line 80
view = DropdownView(bot=bot, author= author, interaction.user)
^
SyntaxError: positional argument follows keyword argument

winged bison
dim cosmos
bright wedge
#

author=author,<----

winged bison
clear elm
#

view = DropdownView(bot=bot,author=author,interaction.user)

bright wedge
#

author=interaction.user

clear elm
#

ohhh

bright wedge
#

...

dim cosmos
bright wedge
#

don't be rude, it's not necessary after all.

clear elm
dim cosmos
clear elm
#

is it possible to make it so the selectmenu disables after someone chooses an option

bright wedge
clear elm
#

how do i do that

dim cosmos
#

You disable it on interaction

winged bison
dim cosmos
#

Paste the error

clear elm
bright wedge
#

I mean you want to remove the select menu from the message or just make it not working?

dim cosmos
#

He wants to make it stop working

#

After the author selects an option

bright wedge
#

Let's see

clear elm
#

actually, ill remove the select

dim cosmos
#

Goodnight

bright wedge
dim cosmos
bright wedge
#

And define the view as None view=None

#

That will remove the view (the select menu in your case).

#

to have access to the view message you can use interaction.message

#

And do whatever you want (edit,delete,copy etc).

fiery cairn
#

Hi there, how do I fix this error?
main.py:18: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension("cogs." + f[:-3])
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

import os
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix = '/', intents=discord.Intents.all())


def load_cogs():
    """
    Pulls every .py file in the /cogs folder, and treats it like a cog.
    only cogs should be in the /cogs folder. 
    """

    for f in os.listdir("./cogs"):
        if f.endswith(".py"):
            bot.load_extension("cogs." + f[:-3])

def load_key_and_run():
    """
    Loads the first argument passed after 'python3 main.py',
    and treats it as a bot token.
    this allows you to run the bot by using:

    python3 main.py tokenGoesHere
    """
    bot.run("token")
if __name__ == "__main__":
    load_cogs()
    load_key_and_run()
clear elm
#

thanks

bright wedge
#

load_extension it's a coroutine so do await load_extensions.

fiery cairn
#

ok

#

await bot.load_extension("cogs." + f[:-3])

bright wedge
fiery cairn
#

oh

#

so like this? ```py
async def load_cogs():

for f in os.listdir("./cogs"):
    if f.endswith(".py"):
        await bot.load_extension("cogs." + f[:-3])
bright wedge
#

You will need the asyncio built-in module

#

For run the async function

fiery cairn
#

ok

fiery cairn
#

uuh SyntaxError: 'await' outside async function

bright wedge
#

import asyncio

asyncio.run(load_cogs())

fiery cairn
#

ok

fiery cairn
tacit storm
# fiery cairn ok

dont do asyncio.run with load_cogs, because you wont be able to run your actual bot that way.

instead in your load_key_and_run function, make that async, instead of bot.run use bot.start (since bot.run is sync and it'll block), and in your load_key_and_run function, do await load_cogs()

THEN, do asyncio.run(load_key_and_run())

fiery cairn
bright wedge
tacit storm
fiery cairn
#

works 🎉

#

tyyy

tacit storm
#

yeah ofc

bright wedge
fiery cairn
#

🤔 tho the slash commands aint updating

#

still old commands

tacit storm
#

do you use bot.sync anywhere?

fiery cairn
#

no

#
from discord.ext import commands
import discord

class PingCog(commands.Cog, name='Ping'):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(description='Check the latency of the bot.')
    async def ping_command(self, ctx):
        embed = discord.Embed(
            title="Pong :ping_pong:",
            description=f"Latency: `{round(self.bot.latency * 1000)}ms`",
            color=0x0000ff
        )
        await ctx.respond(embed=embed)

def setup(bot):
    bot.add_cog(PingCog(bot))```
#

this is code for my ping...

tacit storm
#

oh you're not using actual discord.py you're using some fork

fiery cairn
#

lol

bright wedge
#

?

tacit storm
# fiery cairn lol

i don't know then sorry, best you can do is ask in the server for the fork you're using so they can give better help since they obv know the fork better than most here

fiery cairn
#

idek i used someone's bot to start off and build another bot on top of it

fiery cairn
tacit storm
fiery cairn
#

How am I using a fork tho

bright wedge
#

Your cog file is wrong

tacit storm
#

i can tell because commands.slash_command that doesn't exist in actual discord.py

bright wedge
#

Btw

fiery cairn
#

wut

bright wedge
#

Your cog file is from old version

bright wedge
fiery cairn
#

ok

white citrus
#

How can i find an application subcommand with the subcommand name? Like /find subcommand test

fiery cairn
#

Is there somewhere like a basic pre-written discord.py bot with a ping and test slash command so that I can base myself off of that?

pale zenith
#

the example that was just posted above...?

#

it has example slash commands, with a bunch of comments too explaining what each does and how think

fiery cairn
#

oh ok sowwy

alpine cove
#

lol

odd lagoon
#

whats wrong with my code??

tacit storm
slate swan
#

and try to use the unicode instead of the emoji directly whenever possible

#

!charinfo 💰

unkempt canyonBOT
slate swan
# smoky sinew it's the same thing

it is the same thing but the encoding of the emoji might differ with the platform and might cause encoding error while doing operations like printing and stuff, while using the Unicode directly makes it completely safe

ionic garden
#

i want to dynamically add some buttons to a view, but i have some decorator buttons that i want to stay at the bottom
how would i do this?

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

This function returns the class instance to allow for fluent-style chaining.
ionic garden
#

yeah ik

smoky sinew
#

maybe add the other buttons dynamically too

ionic garden
#

so i have a buncha add_items in __init__

smoky sinew
#

actually

ionic garden
#

oh that's an idea

hushed galleon
#

iirc you just give your buttons the highest row number of 4 and it'll stay on the bottom

ionic garden
#

oh 4 is the highest row number? lol

slate swan
#

yes

#

because you can have only 5 rows

smoky sinew
#

0 to 4

ionic garden
#

so i have a view that can hold multiple values

#

like at the end of a game you've win, lose, or draw

#

should this be a string or enum

clear elm
#

i want to make a number go up +1 everytime the command is used

#

for example

#

i used ?warn (user)

#

the case number would be 1

#

and i used it again and it'd keep going up

#

how would i do that

ionic garden
#

you'd need a database for that

#
    @ui.button(label="Toggle Map", row=1, style=discord.ButtonStyle.blurple)
    async def toggle_map(self, i: discord.Interaction, button: ui.Button):
        if i.message.attachments:
            i.message.attachments = []
            await i.response.send_message("Map hidden", ephemeral=True)
        else:
            i.message.attachments = [self.loc_img]
            await i.response.send_message("Map shown", ephemeral=True)
```how do i make this do what i want it to do?
wanton mortar
ionic garden
#

ok now it gives this lmao

wanton mortar
#

Your file is empty

ionic garden
#

idk how to show you that it definitely isn't

wanton mortar
#

Can you send the code where you make the File

ionic garden
#
            file = None
            if show_map:
                file = discord.File(
                    mark_location("hometown_map", *u.HTOWN[pos]["coordinate"]),
                    filename="hometown_map.png"
                )

            view = Decision(a, file, choices)
            await adventure_msg.edit(embed=embed, attachments=[file], view=view)
            await view.wait()
#

mark_location returns an io.BytesIO object

wanton mortar
#

Did you close the byteIO object?

ionic garden
#

i don't believe so

#

well, turns out i had to add this line:

            self.loc_img.fp.seek(0)
```for some godforsaken reason
wanton mortar
#

Hmmm, it should be open for it work afaik

wanton mortar
#

You were probably reading from the file or writing into it and went to the end of the BytesIO() when you put it into the File()

smoky sinew
ionic garden
#

how do i have a button send a modal

clear elm
smoky sinew
smoky sinew
ionic garden
#

nice

clear elm
ionic garden
#

what db do you have

slate swan
smoky sinew
clear elm
#

?

smoky sinew
#

there are multiple databases that exist

#

and we can't read your mind and figure out which one you use

heavy forge
#

idk what to do to fix it

glad cradle
heavy forge
glad cradle
#

same problem

shell oasis
#

greetings pythonistas,
I am aware that you register slash commands on your bot using the discord.app_commands module but for some reason, the slash command does not appear for me. tried resetting the client and the bot

quick gust
#

what's the best way to add an alias to a command that's inside a group? example: .reminders as an alias to .reminder list

pale zenith
pale zenith
unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
shell oasis
#

oh?

heavy forge
pale zenith
glad cradle
pale zenith
# shell oasis oh?

Yep. Every time you add or remove a command, edit a name or description of a parameter, change an annotation or change anything that shows up to the user in the discord UI you need to sync.

I recommend you have a prefix command to manually sync since changing anything in the callback (inside async def) doesnt require to sync, and the sync endpoint is quite rate limitey, so syncing on startup is highly discouraged imo.

pale zenith
#

Yay!

proud apex
#
      try:
        with open('commands/factories and etc/enterprises.txt') as f:
          company = json.load(f)
        
        await interaction.response.send_message(f"{company[number]}", ephemeral=True)
      except Exception as e:
        print(e)

enterprises.txt

{
    "1": "завода",
    "2": "чтото"
}

the console displays "1" and the command does not work, how to fix it?

quick gust
low sinew
heavy forge
low sinew
#

How

heavy forge
heavy forge
low sinew
#

Sorry, but i dont use Python

#

Am sk coder

bright wedge
heavy forge
naive briar
#

Read the error

#

category is none

radiant bough
#

doc for events in d.py?

radiant bough
#

Oh hi sarth, we meet again :D

radiant bough
#

btw if a channel gets created why would on_channel_update send 3-4 embeds of giving update about Channel?

slate swan
radiant bough
slate swan
#

TextChannel
VoiceChannel
CategoryChannel
StageChannel
ForumChannel
channel can be either of these types

#

look into attributes of them

radiant bough
slate swan
white citrus
#
                try:
                    fcommand = nextcord.utils.get(interaction.client.get_all_application_commands(), name=module)
                    print("1 try")
                    print(fcommand)
                    
                except:
                    try:
                        cmd = self.bot.get_application_command_from_signature(module.split()[0], nextcord.ApplicationCommandType.chat_input, guild_id=interaction.guild.id)
                        fcommand = cmd.children.get(module.splt()[1])
                        print(cmd)
                        print(fcommand)
                        print("2 try")
                        
                    except:
                        fcommand = None```
#

He doesnt find the subcommand with the name

robust fulcrum
#

Hi all
I want to make a utility module for discord.py
Do anyone have idea on what should I make

sullen roost
#

how do i send a file as a link in discord embed?

upbeat otter
#

you want to send a link to a file?

radiant bough
slate swan
#

yes

upbeat otter
radiant bough
#

mhm k

white citrus
slate swan
sullen roost
robust fulcrum
sullen roost
#

but when am sending it in a embed

#

its showing discord.file(object)

#

and not the link to download it

upbeat otter
#

you have to use discord.File for sending documents/whatever/images

sullen roost
#

yep

upbeat otter
#

can I see the code?

#

where you're doing this

sullen roost
#

yea sure

upbeat otter
sullen roost
# upbeat otter where you're doing this
file = discord.File(filename="files/data.json")
        embed = discord.Embed()
        embed.description = f"Here is your file: [Click File to dwnload]({file})"
        await ctx.send(embed=embed)```
slate swan
#

bot = cOMmaNDS.bOT too

upbeat otter
#

!d discord.File

unkempt canyonBOT
#

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

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
robust fulcrum
upbeat otter
upbeat otter
slate swan
young dagger
#
Traceback (most recent call last):
  File "/home/discordbot/modmail/bot.py", line 24, in <module>
    from emoji import UNICODE_EMOJI
ImportError: cannot import name 'UNICODE_EMOJI' from 'emoji' (/home/discordbot/.local/lib/python3.9/site-packages/emoji/__init__.py)```
radiant bough
slate swan
slate swan
radiant bough
slate swan
#

yep

#

you'll have to manually check each attribute

#

something like this

slate swan
robust fulcrum
slate swan
#

yea

robust fulcrum
#

I was thinking to make a roles manager

#

Chatgpt suggested me

robust fulcrum
slate swan
#

automod already supports that

#

why would someone use a third party one

radiant bough
slate swan
#

!e ```py
long_string = "a" * 100000
_1200chars = long_string[:1200]
print(len(_1200chars))

unkempt canyonBOT
#

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

1200
slate swan
quick gust
#

I don't think I fully understand

slate swan
#

oh

#

wait, you're asking asking for something else

#

you can just create a new command ig and invoke the command you want

#
@bot.command()
async def reminders(ctx, *args):
    command = bot.get_command("reminder list")
    await command(ctx, *args)
white citrus
regal hinge
#

!return

unkempt canyonBOT
#

Return Statement

A value created inside a function can't be used outside of it unless you return it.

Consider the following function:

def square(n):
    return n * n

If we wanted to store 5 squared in a variable called x, we would do:
x = square(5). x would now equal 25.

Common Mistakes

>>> def square(n):
...     n * n  # calculates then throws away, returns None
...
>>> x = square(5)
>>> print(x)
None
>>> def square(n):
...     print(n * n)  # calculates and prints, then throws away and returns None
...
>>> x = square(5)
25
>>> print(x)
None

Things to note
print() and return do not accomplish the same thing. print() will show the value, and then it will be gone.
• A function will return None if it ends without a return statement.
• When you want to print a value from a function, it's best to return the value and print the function call instead, like print(square(5)).

regal hinge
#

!class

unkempt canyonBOT
#

Classes

Classes are used to create objects that have specific behavior.

Every object in python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.

Here is an example class:

class Foo:
    def __init__(self, somedata):
        self.my_attrib = somedata

    def show(self):
        print(self.my_attrib)

To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.

bar = Foo('data')
bar.show()

We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.

merry anvil
#

!find element

slate swan
#

can someone help me with my bot i get the error cannot reshape array of size 32 into shape 5, 5

#
@bot.command(name="minesv3")
async def minesV4(ctx, server_hash: str):
    # Preprocessing of server hash to obtain the game grid
    game_grid = []
    for i in range(0, len(server_hash), 2):
        game_grid.append(int(server_hash[i:i+2], 16))
    game_grid = np.array(game_grid).reshape(5, 5)
    
    # Use the trained model to predict the unknown spots
    prediction = self.model.predict(game_grid.reshape(1, -1))
    prediction = np.reshape(prediction).reshape(5, 5)
    
    # Convert predictions to symbols
    symbols = []
    for row in prediction:
        symbols_row = []
        for spot in row:
            if spot == 1:
                symbols_row.append(":white_check_mark:")
            else:
                symbols_row.append(":x:")
        symbols.append(symbols_row)
    
    # Create an accuracy score for the prediction
    accuracy = np.sum(prediction == game_grid) / 25 * 100
    
    # Create the embed for the prediction
    embed = discord.Embed(title="Bloxflip Predictor", color=0x00ff00)
    embed.add_field(name="Prediction", value="\n".join(" ".join(row) for row in symbols), inline=False)
    embed.add_field(name="Accuracy", value=f"{accuracy:.2f}%", inline=False)
    await ctx.send(embed=embed)```
naive briar
#

Of course it can't

regal hinge
#

!list

slate swan
slate swan
#

!e

print("Hello world")
unkempt canyonBOT
#

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

Hello world
slate swan
#

holy shit

#

🤯

#

Ignoring exception in view <DeveloperView timeout=None children=4> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Удалить персонажа' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\githab\BOT\cogs\developer\developer.py", line 65, in SQL_button
SQL = cursor.execute("""DELETE FROM discord.users WHERE (user_id = '567107484850847744');""")
File "C:\Python310\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\Python310\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\Python310\lib\site-packages\pymysql\connections.py", line 547, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "C:\Python310\lib\site-packages\pymysql\connections.py", line 793, in _execute_command
raise err.InterfaceError(0, "")
pymysql.err.InterfaceError: (0, '')

Dear, good evening. Please tell me what the problem may be. The team works every other time. Sometimes it deletes without question, sometimes it gives an error. why is that?

    @discord.ui.button(label="Удалить персонажа", custom_id="Developer-4", style=discord.ButtonStyle.primary) 
    async def SQL_button(self, button, interaction):
        if interaction.user.id != 567107484850847744:
            await interaction.response.send_message('Размечтался', ephemeral=True)
        else:
            with connection.cursor() as cursor:
                
                SQL = cursor.execute("""DELETE FROM `discord`.`users` WHERE (`user_id` = '567107484850847744');""")
                SQL = cursor.fetchone()
                connection.commit()
                print("Удалено")

graceful ermine
#

hey so I'm trying to make some sort of GPT bot and this is what happens when it takes too long to respond

How could I fix this?

#

I'm using the openai API

#
@bot.slash_command(name="imagine", description="Give you a response with the prompt")
async def imagine(interaction: discord.Interaction, prompt: str):

    openai.api_key = ""

    response = openai.Image.create(
        prompt="a white siamese cat",
        n=1,
        size="1024x1024"
        )
    image_url = response['data'][0]['url']


    embed = discord.Embed(
        title="Here you go!",
        description=f"{image_url}",
        timestamp=datetime.datetime.now(),
    )
    embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)

    try:
        await interaction.send(embed=embed)
    except:
        openai.APIError
        
        ```
austere vale
#

where can i hire someone to help me code a discord bot?

graceful ermine
smoky sinew
#

it takes a long time to send a request to openai and get a result back

graceful ermine
smoky sinew
#

also, that's not how try/except works, it's:

try:
    # code that runs
except openai.APIError:
    # code that runs if there was an api error
#

there's also else/finally

graceful ermine
#

okay!

#

@smoky sinew so it would be py await defer(ai_message)

naive briar
#

No, what lib is that

graceful ermine
#

oh shit nvm

steel mango
#

I'm trying to make a geoguessr bot using the geoguessr api but the bot isn't receiving a challengeid

#

This is what I've done

graceful ermine
#
        await interaction.defer(embed=embed, thinking=True)
#

I don't how to defer stuff

ionic garden
#

how do i perform input validation in a modal?

naive briar
#

You have to check after the user submitted

graceful ermine
#

its not a function?

#

do I need to import something

ionic garden
naive briar
ionic garden
naive briar
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 |   File "<string>", line 2, in func
004 | Exception: owo
graceful ermine
#

so like this?

#
await interaction.defer(embed=embed)```
naive briar
#

No

graceful ermine
#

your saying this is correct?

ionic garden
naive briar
#

defer don't take embed arg

ionic garden
graceful ermine
naive briar
ionic garden
#

including for modal submissions

graceful ermine
#

it still does not work @ionic garden

#
await interaction.defer(AI_Message, thinking = True)```
ionic garden
#

bro just call it w/ no arguments

graceful ermine
ionic garden
#

well you just called it with arguments, so...

naive briar
#

You need to call it before doing any heavy operation

#

And with no arguments

smoky sinew
graceful ermine
#

So I don't understand, do I put py interaction.defer()

before any code?

slate swan
#

Can someon ehelp me i keep getting “cannot reshape array of size 32 into shape 5, 5

#
@bot.command(name="minesv3")
async def minesV4(ctx, server_hash: str):
    # Preprocessing of server hash to obtain the game grid
    game_grid = []
    for i in range(0, len(server_hash), 2):
        game_grid.append(int(server_hash[i:i+2], 16))
    game_grid = np.array(game_grid).reshape(5, 5)
    
    # Use the trained model to predict the unknown spots
    prediction = self.model.predict(game_grid.reshape(1, -1))
    prediction = np.reshape(prediction).reshape(5, 5)
    
    # Convert predictions to symbols
    symbols = []
    for row in prediction:
        symbols_row = []
        for spot in row:
            if spot == 1:
                symbols_row.append(":white_check_mark:")
            else:
                symbols_row.append(":x:")
        symbols.append(symbols_row)
    
    # Create an accuracy score for the prediction
    accuracy = np.sum(prediction == game_grid) / 25 * 100
    
    # Create the embed for the prediction
    embed = discord.Embed(title="Bloxflip Predictor", color=0x00ff00)
    embed.add_field(name="Prediction", value="\n".join(" ".join(row) for row in symbols), inline=False)
    embed.add_field(name="Accuracy", value=f"{accuracy:.2f}%", inline=False)
    await ctx.send(embed=embed)```
smoky sinew
naive briar
#

Why are you trying to reshape it to that anyway

slate swan
naive briar
#

And this doesn't seem like discord bots things

slate swan
#

it is

naive briar
slate swan
#

bruh so what do i do

naive briar
#

Because NumPy can't

slate swan
#

than what should i do

#

what do i do

naive briar
#

I don't know what to tell you at this point

slate swan
#

bruh

graceful ermine
#
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        temperature=0,
        max_tokens=4000,
        top_p=1,
        frequency_penalty=1,
        presence_penalty=1,
        stop=["Human:", "AI:"]
    )

    AI_Message = response['choices'][0]['text']

    embed = discord.Embed(
        title="Here you go!",
        description=f"{AI_Message}",
        timestamp=datetime.datetime.now(),
    )
    embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)


    try:
        await interaction.response.defer(AI_Message, Thinking=False)
    except:
        openai.APIError```
naive briar
#

I just said call it before doing any heavy operation

#

And with no arguments

#

Then respond to the interaction later

graceful ermine
naive briar
#

Call it at the top of the function

ionic garden
#

defer first, then do all your code

naive briar
#

Before anything else

ionic garden
#

also why are you still calling it w/ arguments

graceful ermine
ionic garden
graceful ermine
#

it's been five min is this a bad thing?

#

my bot is doing this?

#

for the past 3 min

ionic garden
ionic garden
naive briar
naive briar
ionic garden
slate swan
#
class PageView(nextcord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.current_page = 1

    def create_embed(self):
        if self.current_page == 1:
            description = "This is page 1"
        elif self.current_page == 2:
            description = "This is page 2"
        else:
            description = "This page does not exist"
        embed = nextcord.Embed(title=f"Page {self.current_page}", description=description)
        return embed

    @nextcord.ui.button(label="◀️", style=nextcord.ButtonStyle.grey, disabled=True)
    async def prev_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        if self.current_page > 1:
            self.current_page -= 1
            await interaction.message.edit(embed=self.create_embed(), view=self)
        if self.current_page == 1:
            button.style = nextcord.ButtonStyle.grey
            button.disabled = True
        else:
            button.style = nextcord.ButtonStyle.blurple
            button.disabled = False

    @nextcord.ui.button(label="▶️", style=nextcord.ButtonStyle.blurple, disabled=False)
    async def next_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        if self.current_page < 2:
            self.current_page += 1
        await interaction.message.edit(embed=self.create_embed(), view=self)

        if self.current_page <= 1:
            button.style = nextcord.ButtonStyle.grey
            button.disabled = True
        else:
            button.style = nextcord.ButtonStyle.blurple
            button.disabled = False




@bot.slash_command(name="hello2", description="Test command")
async def hello2(interaction: nextcord.Interaction):
    view = PageView()
    await interaction.response.send_message(embed=view.create_embed(), view=view)```


The forward button works but the backwards disabled
smoky sinew
#

interesting way to create a paginator

slate swan
#

lol

#

so i did it wrong

smoky sinew
#

no

slate swan
#

oh

smoky sinew
#

i meant the create_embed function

#

i don't know anything about nextcord though

slate swan
#

oh

#

like its not rlly dif from dpy i think

smoky sinew
#

is backwards always disabled?

hushed galleon
#

afaik the fundamentals of views are basically still the same

slate swan
hushed galleon
#

imo you should combine the button checks into one method and then call it in both buttons

smoky sinew
#

yeah i did that in my paginator

slate swan
#

oh

smoky sinew
#

this is the one i wrote by the way

hushed galleon
#

e.g. ```py
self.next.disabled = index == 0

smoky sinew
#

did not know that

#

i edited it

hushed galleon
smoky sinew
#
async def start(self, ctx: commands.Context, *args, **kwargs) -> None:
    kwargs["embed"] = self.embeds[self.index]
    kwargs["view"] = self.paginated_view
    await ctx.send(*args, **kwargs)
    self.paginated_view.set_index(self.index)

async def start_with_interaction(self, interaction: discord.Interaction, *args, **kwargs) -> None:
    kwargs["embed"] = self.embeds[self.index]
    kwargs["view"] = self.paginated_view
    await interaction.response.send_message(*args, **kwargs)
    self.paginated_view.set_index(self.index)
#

any better way to do this

#

i should just let the user handle the sending of the message probably

slate swan
#

didnt notice, thankss

hushed galleon
unkempt canyonBOT
#

bot/utils/paging.py lines 246 to 253

async def start(self, channel: discord.abc.Messageable | discord.Interaction, ephemeral=True):
    await self.show_page(self.current_source.current_index)
    if isinstance(channel, discord.Interaction):
        kwargs = self._get_message_kwargs(initial_response=True)
        await channel.response.send_message(ephemeral=ephemeral, **kwargs)
        self.message = await channel.original_response()
    else:
        self.message = await channel.send(**self._get_message_kwargs())```
smoky sinew
#

oh i see

#

is discord.abc.Messageable | discord.Interaction equivalent to Union[Messageable, Interaction]?

#

what is the difference

hushed galleon
#

the pipe operator was introduced in 3.10 as an equivalent to Union
(or rather, 3.10 added support for using the pipe operator to declare union types)

smoky sinew
#

i see

#

it would also be nice to let users edit an existing message with a paginated view

#

maybe i'll create a method like get_starting_embed and get_view

shy abyss
#

where would I start with creating a dicsord bot?

#

also I'm not super active on this server so if anyone has an answer please ping me

smoky sinew
shy abyss
#

thanks

#

ill make sure to check it out

smoky sinew
quick gust
tired notch
#

im trying to create a soldier game and to attack people i want them to be able to send multiple types and amounts of soldiers for example 100 riflemen 10 snipers 5 bombers. whats the best way to get that in one command?

smoky sinew
tired notch
#

slash

fair magnet
#

how can i make it that a dc bot responds in a dm to the command

smoky sinew
#

i guess make a bunch of arguments, for message commands i would use FlagConverter

#

e.g. !attack --riflemen=100

smoky sinew
tired notch
smoky sinew
tired notch
#

so does it just let you specify what type of parameter a user puts into a slash?

smoky sinew
#

yeah

#

those are all of the parameter types supported by the discord api

#

i would just have a bunch of optional arguments for each possible soldier type

#

that default to 0

tired notch
#

amount:

smoky sinew
#

like Riflemen: 0

tired notch
#

amount: discord.AppCommandOptionType.integer
?

smoky sinew
#

you can just do riflemen: int = 0 i think

tired notch
#

whats appcommadoptiontype for

smoky sinew
#

that's just what discord.py uses to represent the option type

#

sorry i'm not very good at explaining

tired notch
#

so they both work?

#

int and discord.appcommandoptiontype.integer?

smoky sinew
#

i haven't tested the second one

slate swan
#

Hey, I've just moved my bot out of a testing server into the real server but one of it's features isn't working. It was working completely fine before so idk y it isn't now, when I was testing the bot I used a separate bot but then combined it with another bot when it was done so maybe it could be something with that. The issue is that on_member_update isn't working.

#

Nothing prints when I give myself the 'Client' role


@client.event
async def on_member_update(before, after):
    print("1")
    if discord.utils.get(after.roles, name='Client') and not discord.utils.get(before.roles, name='Client'):
        print("2")
        category = discord.utils.get(after.guild.categories, name='Reviews')
        print("3")
        channel = await category.create_text_channel(f"review-{after.name}")
        print("4")
        await channel.set_permissions(after, view_channel=True, send_messages=False)
        print("5")
smoky sinew
#

do you have the members intent enabled? @slate swan

slate swan
#

No

#

thats the issue

#

thanks

graceful ermine
#

How do I make my slash commands sync into my discord server?

#

and what does this means?

#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\nextcord\client.py", line 512, in _run_event
    await coro(*args, **kwargs)
  File "C:\Python310\lib\site-packages\nextcord\client.py", line 2482, in on_connect
    await self.sync_application_commands(
  File "C:\Python310\lib\site-packages\nextcord\client.py", line 2296, in sync_application_commands
    await self._connection.sync_application_commands(
  File "C:\Python310\lib\site-packages\nextcord\state.py", line 829, in sync_application_commands
    await self.register_new_application_commands(data=data, guild_id=guild_id)
  File "C:\Python310\lib\site-packages\nextcord\state.py", line 1036, in register_new_application_commands
    await self.register_application_command(app_cmd, guild_id)
  File "C:\Python310\lib\site-packages\nextcord\state.py", line 1071, in register_application_command
    raise e
  File "C:\Python310\lib\site-packages\nextcord\state.py", line 1067, in register_application_command
    raw_response = await self.http.upsert_global_command(self.application_id, payload)
  File "C:\Python310\lib\site-packages\nextcord\http.py", line 393, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.0.name: Command name is invalid```
unkempt canyonBOT
#

Hey @graceful ermine!

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

graceful ermine
#

bot = commands.Bot(command_prefix='*', case_insensitive=True, intents=intents)



@bot.slash_command(name="Ban", description="Bans a user")
async def ban(interacton: nextcord.Interaction, member: nextcord.Member, Reason):
    
    
    
    member.ban(Reason=Reason)
    
    interacton.send(f"I have banned {member.mention} for {Reason}")
    
    
    
    
    
    
@bot.slash_command(name="Avatar", description="Shows a avatar of a user")
async def Avatar(interacton: nextcord.Interaction, member: nextcord.Member): 
    

    
    Embed = nextcord.Embed(title=f"{member.mention} pfp!")
    Embed.set_thumbnail(url=member.avatar)
    
    interacton.send(Embed=Embed)
    
    
    
@bot.slash_command(name="Joke", description="I will tell you a joke!")
async def Joke(interaction: nextcord.Interaction):
    
    some_joke = [
        "What happens when you slap Dwayne johnson in the butt, You hit rock bottom.",
        "What did the left butt cheek say to the right butt cheeks, If we stick together we can stop all this shit!",
        "What happened to the poo that was shaped like an anchor? It got stuck on the bottom.",
        "What do you call a zombie’s butt? A dead end.",
        "What do you call a Frenchman shoving a baguette up your butt? A pain in the ass.",
        "What do you call a pirate woman with an amazing butt? She was thicc with 7 C’s.",
        "What do you call someone who wedged a philosophy book between their butt cheeks? Now, they have a wisecrack in any situation.",
        "What does a 9-volt battery have in common with a girl’s butth*le? You know you shouldn’t, but sooner or later you’re gonna give it a lick.",
        "What do you say when you submit a patent for a gold-plated butt plug, but some engineers at BMW beat you to it? Guess they are already making overpriced toys for assholes."
        
    ]
    interaction.followup.send(random.choice(some_joke))
    
    
    

slate swan
#

i'm planning to count the occurance of "[" and "]" in this but seems to not working:

for num, i in enumerate (args[0]):
                if "[" in i:
                    pj = i.find("[")
                    print(pj)
                    pj = [i for _ in range(0, pj)]
                    start.append(pj)
                if "]" in i:
                    pj = i.find("[")
                    pj = [i for _ in range(0, pj)]
                    end.append(pj)
#

when i print pj it brings 0 instead of 2 in it

#

i'm using this input:

[2d6, [[5, 1d4], 1d3, 4d8], 2d5]
#
def find_brackets(self, *args):
        total = list()
        if len(args) == 1:
            start = list()
            end = list()
            for num, i in enumerate (args[0]):
                if "[" in i:
                    pj = i.find("[")
                    print(pj)
                    pj = [i for _ in range(0, pj)]
                    start.append(pj)
                if "]" in i:
                    pj = i.find("[")
                    pj = [i for _ in range(0, pj)]
                    end.append(pj)
            mod = 0
            is_outside = True
            print(start, end, mod, is_outside)
            total = self.find_brackets(start, end, mod, is_outside)
        else:
            start, end, mod, is_outside = args
            for i in range (mod, len(start)):
                if start[i] >= end[i]:
                    total.append(self.find_brackets(start, end, i, False))
                elif start[i] < end[i]:
                    total.append([start[i], end[i]])
                    del end[i], start[i]
                    if(is_outside == False):
                        break
            total = total[0]
        return total
slate swan
#

that's the output i'm receiving:

0
[[]] [[]] 0 True
graceful ermine
slate swan
#

line 26, in load
await bot.load_extension(f"cogs.{filename[:-3]}")
^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'load_extension'

#

i dont really know why.
i am using 2.1.0

#

code:```py
from discord import Intents
from discord.app_commands import commands
from dotenv import load_dotenv

intents = Intents.default()

bot = discord.Client(
intents=intents,
debug_guilds=[1069881952460603462] # hier server id einfügen
)

@bot.event
async def on_ready():
print(f"{bot.user} ist online")

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

async def main():
await load()
await bot.start("my token ")
asyncio.run(main())

vocal snow
slate swan
#

which information do i need to provide more?