#discord-bots

1 messages · Page 198 of 1

vale wing
#

!e ```py
import random
import re

DICE_PATTERN = re.compile(r"1d(\d+)")

def roll(user_input: str) -> list[int]:
maxvals = map(int, re.findall(DICE_PATTERN, user_input))
dicerolls = [random.randint(1, i) for i in maxvals]
return dicerolls

for ui in ("1d6+1d24", "1d28+1d49", "1d500+1d893+1d5+1d9"):
print(f"{ui}: {roll(ui)}")```

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1d6+1d24: [2, 19]
002 | 1d28+1d49: [22, 3]
003 | 1d500+1d893+1d5+1d9: [406, 237, 4, 3]
vale wing
#

@slate swan is this what you want

#
[random.randint(1, int(i)) for i in re.findall(DICE_PATTERN, user_input)]

You can even oneline that function to this

#

And yeah have a good workout

vital glacier
#

anyone that got any experience with humanizer?

vocal snow
slate swan
#

i'm planning to also use normal numbers to make operations

slate swan
#

i'm using the basics of programation i have

vale wing
#

That's simple regex and list comp

#

Pretty common things

slate swan
#

i need it more explained, i'm new to regex. it's like a clusterfrick for me

ionic garden
#

is there any way to call an interaction from code itself?

sick birch
#

You extract the main logic and extract it into its own function

#

Then you call that

#

Also good for TDD

ionic garden
#

what's tdd

slate swan
#

okay i'm starting to learn it

sick birch
unkempt canyonBOT
#

Regular expressions
Regular expressions (regex) are a tool for finding patterns in strings. The standard library's re module defines functions for using regex patterns.

Example
We can use regex to pull out all the numbers in a sentence:

>>> import re
>>> text = "On Oct 18 1963 a cat was launched aboard rocket #47"
>>> regex_pattern = r"[0-9]{1,3}"  # Matches 1-3 digits
>>> re.findall(regex_pattern, text)
['18', '196', '3', '47']  # Notice the year is cut off

See Also
The re docs - for functions that use regex
regex101.com - an interactive site for testing your regular expression

vale wing
#

So basically it extracts 38 from 1d38. \d+ in regex means "digit repeated one or more times"

#

There's lots of syntax and patterns might seem complicated (hence simple link regex is https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*), but once you get hang of it it is not that hard

slate swan
#

well, i'm gonna have a study now, i'm also planning to use the number before d since the first number represents how many times i'm rolling the same dice

vale wing
#

List comp is very common and easy

#

!list-comp

unkempt canyonBOT
#

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if clause:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

pseudo saffron
#

hey with this code it only prints me SequenceProxy(dict_values([])) even i get the guild

if data["hunger"] <= 0:
    server = await bot.fetch_guild(526180194810******)
    print(server.channels)```
civic fractal
#

server.channels is a sequence

#

you can just iterate through it normally for channel in server.channels or convert it to a list if you really felt like it list(server.channels)

civic fractal
#

then your bot doesn't have access to the channels in that guild

pseudo saffron
#

it has

pseudo saffron
civic fractal
#

It looks like fetch_guild will not update the channel list

#

you should do await guild.fetch_channels()

pseudo saffron
#

it workde thx

fair shuttle
#

any1 can help why its not working >

civic fractal
fair shuttle
#

this is the error i got

civic fractal
#

I assume you've read the error at least right?

fair shuttle
#

yeah i read it but i dont really understand lmao kinda new into this

civic fractal
#

it says "unexpected keyword argument 'name'"

#

and if you scroll up a bit it tells you that the error is caused on this line

#

the error is telling you that Embeds don't have names

#

did you mean to give it a title instead?

fair shuttle
#

yeah imma fix that

#

ty @civic fractal for dat little help it works now

slate swan
#

i'm planning to not use "1d" since the number before "d" is used for indicade number of rolls

#

that can happens a multiroll

vale wing
#

!e ```py
import random

user_input = [(2, 6), (5, 10)]
output = [[random.randint(1, maxval) for _ in range(count)] for count, maxval in user_input]
print(output)```

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

[[2, 3], [3, 5, 7, 3, 2]]
vale wing
#

This is not really a matrix cause it got no definable size

#

Just a list of lists

vital glacier
#

Anyone got an idea who this wouldn't remove the entry from the database:

await db.execute('DELETE FROM afk WHERE user_id = ? ',(message.author.id,))
#

It puts it into the database, just doesn't delete it

short silo
#

Error : Application command names must be unique.

But all command names are unique.

vital glacier
#

there might be an overlapping one

tawdry tendon
short silo
tawdry tendon
short silo
#
async def load(ctx: discord.Interaction,extension:str):    
    if(ctx.author.id in ADMINS):
        try:
            print(extension)
            bot.load_extension(f'{extension}')
            await bot.sync_commands()
            await ctx.response.send_message("Cog loaded.",ephemeral=True)
        except Exception as E:
            await ctx.response.send_message(E,ephemeral=True)
            raise E

....................................

class LANGUAGE_SELECTION(discord.ext.commands.Cog):
    def __init__(self,bot):
        self.bot=bot
    
    def auto():
        return LANGUAGES
    
    @bot.slash_command(guild=config.GUILD, description="Set your Translator Language.")   
    async def set_language(ctx: discord.Interaction,language: Option(input_type=str,description="Select a Language.",autocomplete=auto())):
        print(language)
        
  

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


#
Ignoring exception in command load:
Traceback (most recent call last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "e:\Python Projects\Translator\Cog_gathering.py", line 18, in load
    raise E
  File "e:\Python Projects\Translator\Cog_gathering.py", line 14, in load
    await bot.sync_commands()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 366, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1: Application command names must be unique
tawdry tendon
short silo
tawdry tendon
#

Do you mind me seeing the whole thing?

#

you can send it in dms so it isnt a mess

slate swan
#

a question, is it possible to make if elses in a for?

#

!list-comp

unkempt canyonBOT
#

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if clause:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

slate swan
#

!list-statement

#

the problem now is on my calculation thing

#

like, i'm planning to make the operator thing to calculate the arguments input to total

#

like 1d6[5]+2d5[2,3][8]+8 result into 21

#

maybe when i implement the input accept separance between () and [] i will need to make it recursive

#

and when i implement the stat system the {} thing being the identifier for stats

slate swan
#

idk what I did

#

but whenever I run my code this happens the bot doesn't work, it was working fine before idk

#

and when I go to discord the bot appears online

#

but again none of the commands run

sick birch
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
#

I forgot to import intents lol

smoky sinew
#

your method won't work lol

#

reinstalling python will always install it as python

#

not python3

slate swan
#

it installs it as python3.x for me

naive briar
unkempt canyonBOT
#

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

['b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']
fair shuttle
#

im curious to know but is there a googletranslate package w pyton?

#

like i want to make a translate command

fair shuttle
#

alrrr tyyy

#

i was not sure at all cuz the version seems old

slate swan
#

i mean things like this dont need an update as long as the base API doesnt make a breaking change

slate swan
#

thanks for the first information

#

you guys are making me adapt my basics of programmation to advance into python

#

with that i will learn wonder stuffs that i never knew

fading marlin
#

elifs aren't supported. You could chain if-else though, but that'll probably make your code look a lot messier and unreadable

"a" if n % 2 else "b" if n % 5 else "c"
slate swan
#

ty

#

now it will makes my code even cleaner

#
"a" if n % 2 else ("b" if n % 5 else "c")
``` for the sake of readability
smoky sinew
#

he already said it makes it look messier

#

don't just try to fit everything in one line

slate swan
#

the calculation thing

#

but good to know that the basics willl be still valid

smoky sinew
#

depends on what kind of datamining

#

messages?

#

then probably, you at least want some kind of privacy policy, don't do it without consent

abstract pewter
#

!e print(“amongus”)

steep marsh
#

I'm trying to create a 8ball slash command, and appereantly it doesn't work due to: "parameter 'question' is missing a type annotation in callback 'eightball.' "

@bot.tree.command(name="8ball", description="Checking with the bot's health.")

async def eightball(interaction:discord.Interaction, *, question):
 
  responses = [
      'It is certain.',
      'It is decidedly so.',
      'Without a doubt.',
      "I'm feeling well",
      'Yes - definitely.',
      'You may rely on it.',
      'As I see it yes.',
      'Most likely.',
      'Outlook good.',
      'Yes.',
      'Signs point to yes.',
      'Reply hazy, try again.',
      'Better not tell you now.',
      'Concentrate and ask again.',
      "Don't count on it.",
      'I cannot predict now.',
      'My reply is no.',
      'My sources say no.',
      'Outlook not so good.',
      'Very doubtfull.',
      'I am tired. *proceeds with sleeping*',
      'As I see it, yes.',
      'Yes.',
      'Positive',
      'From my point of view, yes',
      'Convinced.',
      'Most Likley.',
      'Chances High',
      'No.',
      'Negative.',
      'Not Convinced.',
      'Perhaps.',
      'Not Sure',
      'Mayby',
      'Im to lazy to predict.'
    ]
  await interaction.response.send_message(f":8ball: Question: {question}\n:8ball: Answer: {random.choice(responses)}", ephemeral=True)
viral stump
#

use " instead of ”

smoky sinew
abstract pewter
#

!e print(yoaiaj)

unkempt canyonBOT
#

@abstract pewter :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'yoaiaj' is not defined
smoky sinew
#

?

smoky sinew
#

no problem

abstract pewter
smoky sinew
#

alright

steep marsh
#

it's funny how it's always the one missing code that can mess up entirely for you

smoky sinew
#

and yeah @steep marsh errors do often work like that lol

steep marsh
#

tyty

vale wing
lean plank
#

anyone know how to decode these?[<function is_owner.<locals>.predicate at 0x7fa247167790>, <function has_permissions.<locals>.predicate at 0x7fa2471675e0>]

naive briar
#

Call the function

lean plank
#

what if im trying to get the permission inside of a help command, how would i do that?

pliant trail
#

does anyone know why this doesn't work? ```@bot.command()
async def help(ctx):
help_embed = discord.Embed(
title="Help Menu",
description="A list of available commands:",
color=discord.Color.blue()
)

help_embed.add_field(name="ex", value="ex", inline=False)
help_embed.add_field(name="ex", value="ex", inline=False)
help_embed.add_field(name="ex", value="ex", inline=False)

await ctx.send(embed=help_embed)```
naive briar
#

Which part of it, be specific

pliant trail
lean plank
lean plank
vale wing
smoky sinew
#

probably

smoky sinew
lean plank
#

i have other code at the top which filters the command_set etc, but here im trying to get the perms required for the command

unkempt mauve
#

aiohttp is having problem

lean plank
#

as in, administrator, ban perms etc

smoky sinew
#

where is the permission code though?

lean plank
#

i deleted it for now but it would go on around line 88

smoky sinew
#

what was it?

#

oh perms required

lean plank
#

yes

smoky sinew
#

sorry i'm stupid

lean plank
#

everytime i printed it, it'd output the function has_permissions.<locals>.predicate etcetc

lean plank
#

i see that but i'm trying to figure it out though, dont quite get it

naive briar
#

Send the error then

#

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

smoky sinew
#

it returns a list of callable checks

lean plank
smoky sinew
lean plank
#

how would i go around that?

smoky sinew
#

wdym??

#

which specific one? a command can have multiple checks

lean plank
#

to get the exact permission it needs so like Administrator, ban_members, the list only returns the functions

smoky sinew
#

probably something like

for check in command.checks:
    if check == commands.has_permissions:
        ...
vital glacier
#

@smoky sinew he's tryna make it so he has this^ on the help embed from the command. so if he does !ban it'll send the usage/help embed and then a field is Permissions with the matching permission needed for it

smoky sinew
#

i'm aware

vital glacier
#

alright just making sure

smoky sinew
#

i'm checking to see what it returns

lean plank
#

returns nothing 🤷

smoky sinew
#

no..

#

if it returned nothing, it would be Optional

#

but it's List[Callable[Context, bool]]

lean plank
smoky sinew
#

what does command.checks return then

lean plank
#

when i print that? with the s on commands or without

#

command.check: [<function is_owner.<locals>.predicate at 0x7fa247167790>, <function has_permissions.<locals>.predicate at 0x7fa2471675e0>]
commands.check: <function check at 0x7fa24c8a9700>

smoky sinew
#

huh

lean plank
#

if i print either of those those are the results

vale wing
#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
vale wing
#

@lean plank I doubt you can really get what permissions command needs to run with dpy. Maybe you can get all function decorators somehow and extract data from there, let me check

#

!d inspect.getsource seems like a possible way

unkempt canyonBOT
#

inspect.getsource(object)```
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised if the source code cannot be retrieved.

Changed in version 3.3: [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised instead of [`IOError`](https://docs.python.org/3/library/exceptions.html#IOError "IOError"), now an alias of the former.
steep marsh
#

I'm currently trying to make a "dad jokes" command, and when I run the command in my server the bot answers: 403.

May someone help me out?

@bot.tree.command(name="dadjokes", description="Jokes of what most dad's would say.")

async def dj(interaction:discord.Interaction):
    
    url = "https://parade.com/940979/kelseypelzer/best-dad-jokes/"
    
    async with request("GET", url, headers={}) as response:
        if response.status == 200:
            data = await response.json()
            await interaction.response.send_message(f"**{data['setup']}**\n\n||{data['punchline']}||")
        else:
            await interaction.response.send_message(f"{response.status}")
golden portal
steep marsh
#

ahh alright, thank you

golden portal
#

welcome

vital glacier
#

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot: return
        cursor = await self.bot.database.cursor()
        await cursor.execute('SELECT * FROM afk WHERE user_id = ?', (message.author.id,))
        data = await cursor.fetchall()
        timestamp = data[0][2]
        time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
        if data:
            await cursor.execute('DELETE FROM afk WHERE user_id = ?',(message.author.id,))
        else:
            return
        await self.bot.database.commit()
        await message.channel.send(f'Welcome back, you were away for **{time}**')
        if message.mentions:
            for mention in message.mentions:
                await cursor.execute('SELECT * FROM afk WHERE user_id = ?', (mention.id,))
                data = await cursor.fetchall()
                await message.channel.send(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')

Bot isn't sending message and not getting data from database if a person gets mentioned who is in the database.

#

No errors and no returns when printing/sending the data.

vale wing
vital glacier
#

on_message

#

so yes, it does

vale wing
#

There's some stuff

  1. Weird stuff, how are you trying to access data[0][2] and only check if data afterwards?
  2. This construction should be inversed
if data:
    ...
else:
    return

# to
if not data:
    return
...```
slate swan
#

Hello

naive briar
#

Cat

slate swan
vital glacier
#

Im getting the data from data = await cursor.fetchall()

#

And then I'm getting the timestamp from the database

#

Which is data[0][2]

vale wing
#

data is a list I presume?

vital glacier
#

It isn't empty

vale wing
#

Then why even check for it

vital glacier
#

What do you mean

#

I need to get the data from the table, dont it?

vale wing
#

Yes

vital glacier
#

That part works, it's the part with the mention.id that doesn't work

#

The first part isn't the problem

#

It's from here:

        if message.mentions:
            for mention in message.mentions:
                await cursor.execute('SELECT * FROM afk WHERE user_id = ?', (mention.id,))
                data = await cursor.fetchall()
                await message.channel.send(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')
#

That part doesn't work. The for loop works because it prints the mention if i do print(message.mentions)

vale wing
#

Maybe only send a message for first mention? Just for security reasons, if someone mention-spams your bot might start spamming in the channel

vital glacier
#

Wouldn't work

#

It'll only send the message if the entry is in the database

#

it's my AFK listener

vale wing
#

Yeah I know

vital glacier
#

so it's checking for people in the afk table

#

if they aren't in the table and they get mentioned, it wont send the message

vale wing
#

But still case when attacker pings specifically people with AFKs set is possible, potential security vulnerability

vital glacier
#

Not really

#

But that isn't the problem

#

Let's focus on the problem that I came here for instead of trying to solve other stuff that isn't needed

vale wing
vale wing
#

Actually would be better if you made a single query but sqlite probably can't do that

vital glacier
#

Also, the [0] is the row right?

vale wing
#

Yeah

vital glacier
#

so that would be [1] then

#

since I'm trying to get 1

vale wing
#

EXISTS returns 1 if the row exists, 0 if doesn't

vale wing
#

It's the value

vital glacier
#

Yeah i need the second value from the table

#

so for me it goes: user_id, status, timestamp

vale wing
#

I don't remember how correctly it's named in aiosqlite

vital glacier
#

and i need status

vale wing
#

Look at the query

vital glacier
#

Ah

#

I tried what you said, didn't work though

#

Still nothing

vale wing
#

It might be fetchrow instead of fetchone

quick gust
#

fetchone returns the first row afaik

#

fetchall returns all the rows

vale wing
quick gust
#

in aiosqlite itll probably return a list of tuples

#

I see

vital glacier
#

Still nothing

#

The way I did it should've worked because I've used it before

#

In my old on_message code it worked, but something else was broken and it was pretty messy code. hence why i'm rewriting it.

#

But it did send me the message and data etc.

#

This is the old code I used. The message.mentions stuff worked on that code.

vital glacier
quick gust
#

can u try printing what await db.fetchval("<query>") returns? Instead of await db.execute? I can't remember what it does but I remember that's a method

vital glacier
#

I'm sorry what

quick gust
vital glacier
#

Yeah I know

quick gust
#
for mention in message.mentions:
    print(await cursor.fetchval("YOUR QUERY HERE")) 
vital glacier
#

What is my query tho

#

I've never used query in aiosqlite

quick gust
#

SELECT...

vital glacier
#

oh, the select thing

#

right ok 1sec then

quick gust
#

yep that's called a query

vital glacier
#

Oh had no idea

quick gust
#

Now you know :)

quick gust
vital glacier
#

yeah it's not even letting put the fetchval in properly, it's erroring in the edi

#

ide*

#

Nevermind

quick gust
#

weird, the method doesn't exist then I guess that's my bad

vital glacier
#

Nothing is being sent from the fetchval query thing

#

Hence what makes it very odd

quick gust
#

strange

vital glacier
#

mhm

quick gust
#

sorry can't help you right now omw home

vital glacier
#

that's alright

#

just hoping someone can help me to fix this

#

because it's very odd why it isn't working

quick gust
#

are u sure you're not using a method on your cursor before this? You can only use it once

timid spade
#

i have been using this button every time i have to stop code
is there a better way in which you dont have to kill terminal?
i tried using the shortcut to stop code but didnt work

flat pier
#

there's also a handful of other ways to stop your running code depending on how you run it or if you use a process manager, etc, etc

timid spade
drifting wadi
#

Hey guys, how do I install Socks if I have already done pip install socks and it's still giving me error saying " module not found - socks "

rugged shadow
naive briar
peak acorn
#

Yes, discord.py, by far
I didn't even hear about what is "disnake"

slate swan
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

shrewd apex
rugged shadow
#

discord.py's slash command interface is more complex than disnake's

shrewd apex
#

discord.py has a bigger community more tutorial while disnake offers more modularity and feature wise its structured very nicely as well

#

con is u have to read everything from the docs and make it urself

#

use hikari if u wanna go next level

bright wedge
#

Take it as an example: if you don't know math you'll use the math library, if you know math you don't need the library. (The same goes for discord.py - disnake libraries).

naive briar
shrewd fjord
#

Sup guyz

naive umbra
#

98% of the dpy "tutorials" you see are outdated

#

relying on the docs is a pro

thin raft
slate swan
#

I use math library despite being proficient at it.

naive briar
#

Especially YouTube tutorials ducky_sus

naive umbra
#

some people learn better when they can get a visual representation of something, than just reading, i know for a fact that i do 🤷‍♂️

#

but i still use docs and src code

thin raft
#

maybe get better at reading?

naive umbra
vale wing
vale wing
#

In videos they should be explaining some stuff that might not be explained in docs/articles, but specifically for discord.py I have seen many showing discouraged practices which is a problem

naive umbra
# vale wing It's not about visual representation, it's about ready code 🤓 or people who pre...

yeah that can sometimes be seen by beginners too

i'll give an example, i'm currently taking the CCNA certificate, all the resources are written - it is extremely technical with many jargons. i started watching videos instead and it certainly helped me to better understand the theory

but this is quite unrelated to discord.py, i feel like anyone should learn the way they know they'll learn the best. docs and src codes are almost always up to date so it's the best resource someone can have access too, videos is a great alternative to beginners who have harder times understanding technically written documentation

vale wing
#

Extremely technical tutorials are created by experienced people with education, that's the difference from dpy

naive briar
#

🍿

vale wing
#

Popcorne

#

Nah I am not into argument, I totally agree with him

naive umbra
peak acorn
#

Meta question but: why can't we put reactions on messages in this specific channel?
It is possible on every other channels in "Topical Chat/Help" section so I don't get the logic.
It is also almost the only one to have slowdown mode activated.

#

Ok slow mode is configured for 5 seconds so it's fine, but I think it's useful to put reactions on messages like 👍 or 👎

naive umbra
peak acorn
#

Oh this channel is more active than the others?

peak acorn
naive briar
#

Earth

#

Aw

naive briar
velvet compass
naive briar
#

Hmmm, I guess I'm not active enough to notice

golden portal
#

ThinkO_O TIL

#

i guess a lot of ppl wants to dev discord bots

humble gulch
#

Can u give tutorial for making a bot in python? (I started python 3 days ago so please, I'm a noob)

slate swan
#

guys, i noticed that when an array have only intergets i can't use range

#

what do i use instead?

slate swan
#

i'm planning to use the number of indexes as a range for my while

#

like this:

                    #then it will be calculated the sum and subtraction
                    print("calculating rest")
                    if indice[cont-1] == "+":
                        sub_total = sub_total + store[count]
                    elif indice[cont-1] == "-":
                        sub_total = sub_total - store[count]
                    count = count+1
                indice.pop(all)
                store.pop(all)```
slate swan
#

can someone please help me with my bot i made some simple embed message commands but i have no idea how to combine my script with another
i want to make a command that when i type csc ltc [my litecoin adress] to send how much money it received and how much money it send

import requests

address = "typetheadresshereplsplsplspls"

api_url = f"https://api.blockcypher.com/v1/ltc/main/addrs/{address}/full"

response = requests.get(api_url)

txs = response.json()['txs']

total_received = 0
total_spent = 0

for tx in txs:
    for output in tx['outputs']:
        if output['addresses'] == [address]:
            total_received += output['value']
    for input in tx['inputs']:
        if input['addresses'] == [address]:
            total_spent += input['output_value']

# Print the results
print(f"Total received: {total_received / 1e8} LTC")
print(f"Total spent: {total_spent / 1e8} LTC")
#

i have this code and idk how to turn it into a command

silk bridge
#

Anyone can tell how to make a discord music bot plz

humble gulch
slate swan
#

guys, when i try this this error occours with me:
list index out of range

code:

for cont_ ,num in enumerate(store):
                    #first it will calculate the division thing
                    if indice[cont_-1] == "/":
                        print("calculating /")
                        sub_total = store[cont_-1] / num
                        del indice[cont_-1]
                        del store[cont_]
                        del store[cont_-1]
                        pivot = cont_-1
                        while indice[pivot] == "*":
                            sub_total = sub_total * store[pivot]
                            del indice[pivot]
                            del store[pivot]
                        pivot = cont_
                        while indice[pivot] == "*":
                            sub_total = sub_total * store[pivot]
                            del indice[pivot]
                            del store[pivot]
                        store.append(sub_total)
                        indice.append("+")
                        sub_total = 0
#

the code works until while

#

then when it reaches while the code gives me that output

vale wing
#

Oh no

#

Is this another thing

#

Or still that one with dices

#

@slate swan

slate swan
#

this is another thing

#

the dice are working

#

now i'm working on a function that calcultate the total

vale wing
#

Of dices?

slate swan
#

yep, first calculate division then multiplication then sum and subtraction

naive briar
#

It shouldn't be that huge yert

vale wing
#

Definitely

#

Yesterday we shortened down similar amount of code to one line

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
vale wing
#

@slate swan so input you have is a list of lists and you need to calculate what?

slate swan
#

i need to calculate the result of the dices into the total result
like 2d6[1][5][6]*1d5[4]/2 = 12

#

the sum and subtractio part is working

#

but the division seems problematic

vale wing
#

Uh what kind of formula you use

#

Dot product of sums of outcomes divided by two or something

slate swan
#

this:
sub_total = store[cont_-1] / num

#

like it gets the previous number and divide by the actual number

#

then it pops the both numbers and check if there is * in the previous expression from indice

#

if yes it multiplicate

#

but doesn't seems to work

#

it also do the same for next numberszx

#

*numbers

slate swan
vale wing
#

🧐

#

I have very little knowledge in probability theory, is it from there

naive briar
slate swan
harsh pier
#

can you not use elif?

steep marsh
thorny flint
#

Guys, I need some opinions!
Which of the discord py wrappers is best/do you use and why?
• disnake
discord.py
• NAFF
interactions.py
• nextcord
• hikari
• others?

daring locust
#

its the one i found

#

btw has anyone tried making a chess discord bot yet?

#

seems like a fun project

slate swan
#

I've not tried, could be much fun, there are a few out there already

ancient elk
#

What's the best approach to getting my discord bot to ping users at random times during the day

thorny flint
ancient elk
#

I've already got the pinging system down by users registering with a slash command but the scheduling is really tricky

slate swan
thorny flint
#

That's also the one I'm currently using.

daring locust
slate swan
#

chess960 bot 🙀

slate swan
slate swan
# thorny flint why?

it's much more low level than discord.py and other libraries, you have more control over the ecosystem
it also supports rest apps for applications like a bot dashboard or an API

thorny flint
slate swan
#

if you're gonna start with keeping your discord.py stuff in mind it will for sure be confusing

thorny flint
slate swan
#

their design is mostly inspired by discord.py and they are completely open about that lol

#

read their GitHub readme

#

Discord.py fork?
While this library shares features and some stylistic choices with discord.py, it is completely separate from them. We think discord.py is a fantastic library, but we disagree with the direction and design decisions that were made by it

quick gust
idle plume
#

Hey all, how can I store my bot token in a seperate file and pull it into bot.run

velvet compass
#

Take a look into .env (or dotenv) files to store environment variables

#

!pypi python-dotenv

unkempt canyonBOT
idle plume
thin raft
idle plume
#

yeah I mean a .env is also a file though im wondering why use that over a regular .py

#

im gonna ask bing

thin raft
#

not bing

#

its not an error

#

and it literally tells you

slate swan
#

Hey, I'm trying to make my button create a text channel like a ticket but am unsure how to create the channel in the class?

class OrderChannel(discord.ui.View):

    @discord.ui.button(label="Order Now!", style=discord.ButtonStyle.success)
    async def order(self, interaction: discord.Interaction, button:discord.ui.Button):
        await interaction.response.create_text_channel(interaction.author.name)
#
AttributeError: 'InteractionResponse' object has no attribute 'create_text_channel'
fading marlin
#

!d discord.Interaction.guild you need the guild object to create the channel, create_text_channel isn't a response method

unkempt canyonBOT
finite holly
#

Im using pycord. How i can use slash commands in cogs?

unkempt canyonBOT
finite holly
#

!slash

slate swan
white vale
young dagger
#

Should I use while to repeat a block of code if a certain condition is true?

#
        if len(queue) > 0 and len(current_players) < 10:
            while len(queue) > 0 and len(current_players) < 10:

                next_player = queue.popleft()  # Get the next player in the queue and remove them from the deque
                current_players.append(next_player)```
#

This will keep repeating the process of adding players to current_players as long as there are players in the queue and current_players has fewer than 10 players right?

keen cloak
#

How do i get kick command for mt bot

rare echo
#

why make a kick command? its already integrated into discord

keen cloak
rare echo
#

!d discord.Member.kick

unkempt canyonBOT
#

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

Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick "discord.Guild.kick").
slate swan
#

i'm trying to make a bot command that allows me to reset bots but it's not working:

#

or better, it's showing those error messages

#

syntax erroes

slate swan
#

using this:

os.execv(sys.executable, ['python'] + sys.argv)
oak oar
slate swan
oak oar
#

this is assuming your main file is named bot.py

slate swan
#

can you use slash commands in dpy?

#

and any pointers would help cause youtube and google isnt :)

naive briar
#

YouTube tutorial moment

naive briar
slate swan
#

👍

slate swan
winged coral
winged coral
#

Could you print(discord.__author__)

slate swan
#

or coding

winged coral
#

In your file

#

Right after the import discord

slate swan
winged coral
#

Yeah did you try running that?

slate swan
#

i did

#

thats what it showed

winged coral
#

That's odd

#

Okay so open a cmd for me

slate swan
stray carbon
slate swan
#

prolly not just asking

stray carbon
#

No

#

Dont nist copy paste what I said

#

You already have commands extension imported from discord.ext

stray carbon
# slate swan

Just have to replace discord.Bot with commands.Bot here

stray carbon
#

You didnt save the file.

slate swan
stray carbon
slate swan
#

i can just add onto the intent line correct

stray carbon
#

Yes.

stray carbon
slate swan
slate swan
#

i have slash commands enabled

#

in dev portal

stray carbon
# slate swan bruu

Mhm, in discord.py there isnt any slash_command decorator

For slash commands discord.py has @discord.app_commands.fommand and @bot.tree.command decorators

#

Maybe instead of copying someone's code you should read the docs.

slate swan
stray carbon
slate swan
stray carbon
#

Because you are doing it wrong

slate swan
stray carbon
#

If you read it, you wont need to ask me

slate swan
#

i really dont know what to put down lol

naive briar
#

There's no much difference

slate swan
#

idk what to put to fix my error

naive briar
#

There's no guild_ids argument 🤷

#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
slate swan
slate swan
slate swan
naive briar
#

Where did you get that from, first of all

slate swan
#

she or him

#

you are using py-cord code and expecting it to work in discord.py

slate swan
#

or check pins for a simpler guide

#

the code you have isnt even 10% functional in dpy

graceful ermine
#

Hey, so I don't know why, but for some reason my commands don't work and I get no errors in the console

#

and I think it might be my intents

#

is this correct?

slate swan
#

do you have an on_message event @graceful ermine ?

slate swan
#

if yes, change the .event decorator to .listen()

#

with the brackets

graceful ermine
#

Okay

#

@slate swan

#

it was my anti spam

#

but it was doing the same thing when I tried to run my command

slate swan
#

it doesnt change the functionality of anything
event overrides the default callback and ghosts the command callbacks
using listen() just creates a new listener instead of overriding the default ones

#

so your old stuff will work + the commands will work as well

graceful ermine
#

Nvm it works

#
       
@bot.listen()
async def on_message(message):
    author = message.author
    if author == bot.user:
        return
    if author in spammers:
        spammers[author] += 1
        if spammers[author] > SPAM_THRESHOLD:
            await message.channel.send(f"{author.mention} has been kicked for spamming.")
            await message.delete()
            spammers.pop(author)
        else:
            await message.channel.send(f"{author.mention} stop spamming!")
            await message.delete()
    else:
        spammers[author] = 1

    await asyncio.sleep(SPAM_TIMEFRAME)
    if author in spammers:
        spammers[author] -= 1
        if spammers[author] == 0:
            spammers.pop(author)```
#

this is my anti spam function

#

and when a bot logs something constantly

#

it keeps on saying stop spammingh

#

How could I make it stops saying that too a bot

naive briar
#

Someone already answered

vale wing
#

I wonder what kind of spam detection method this uses

slate swan
#

can anyone tell me why my security bot does not bans , kicks or punishes members while testing anti nuke commands

smoky sinew
#

you didn't even say anything

fringe narwhal
#

Hello, I have been experiencing some difficulties migrating to v2 can anyone help me figure out what is going on with the on_ready?

@client.event
async def on_ready():
    await client.remove_command("help")
    print(f"{color.FAIL}-" * 32)
    print(f"{color.WARNING}Starting Bot!")
    print(f"{color.WARNING}Loading Cogs")
    print(f"{color.FAIL}-" * 32)
    count = 0
    for cog in cogs:
        try:
            await client.load_extension(cog)
            count += 1
            print(f"{color.OKGREEN}{count}: Loading Cog: {cog}")
        except Exception as e:
            count += 1
            print(f"{color.FAIL}{count}: {e}")

    print(f"{color.FAIL}-" * 32)
    print(f"{color.WARNING}Cogs loaded!")
    print(f"{color.WARNING}Bot Online!")
    print(f"{color.FAIL}-" * 32)
    print(f"{color.WARNING}Extras!")
    print(f"{color.FAIL}-" * 32)
    print(f"{color.WARNING}Serving {color.FAIL}{str(len(client.guilds))}{color.WARNING} servers!\n{color.WARNING}Serving {color.FAIL}{str(len(set(client.get_all_members())))}{color.WARNING} users!")
    print(f"{color.WARNING}Running on discord {color.FAIL}{discord.__version__}{color.WARNING}!")
    print(f"{color.WARNING}Running on python {color.FAIL}{platform.python_version()}{color.WARNING}!")
    print(f"{color.FAIL}-" * 32)

    while not client.is_closed():
        await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=(f'z!help | servers: {str(len(client.guilds))}')))
        await asyncio.sleep(3600)
        print(f"{color.WARNING}Online!")

async def Zim():
    async with client:
        await client.start(os.getenv("TOKEN"))
        print('Ready')
asyncio.run(Zim())
full ether
graceful ermine
#

Yeah I never new that existed

graceful ermine
vale wing
unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

vale wing
#

!pypi exencolorlogs

unkempt canyonBOT
vale wing
#

I forget commands

#

@fringe narwhal ^ you can use this for logging instead of those prints

#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
golden portal
vale wing
golden portal
#

tbh ppl should use timed_out_until instead of roles

fringe narwhal
#

thank you for the colors tho

bitter perch
#

where is your client defined

radiant bough
#
await bot.load_extension("cogs.utility")

or something else?

vale wing
#

Some problems and resolutions

  1. Run bot like this
bot = comnands.Bot(...)
bot.run(token)```
You don't even need async with construction
2. Do not use while loop in on_ready, instead use `tasks.loop`
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
vital glacier
#

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

fringe narwhal
vital glacier
#
        if commands.has_permissions:
            e.add_field(name='Permissions', value=''))

how do i get what permission a command needs for a subclassed help command?

fringe narwhal
#

i think there is trouble with await client.start(os.getenv("TOKEN")) because it isnt printing "Ready" at all

fringe narwhal
vital glacier
#

That's not what I mean

#

It's for this:

    async def send_command_help(self, command: commands.Command):
        if not command.description:
            command.description = ''
        if not commands.parameters:
            commands.parameters = 'N/A'
        e = await self.help_embed(
            title=f'Command: {command.qualified_name}',
            description=command.short_doc
        )
        e.set_author(
            name=self.context.bot.user.name,
            icon_url=self.context.bot.user.avatar.url)
        e.set_footer(text=f'Module: {command.cog_name}')
        if command.aliases:
            e.add_field(name="Aliases", value=', '.join(command.aliases))
        if commands.parameters:
            e.add_field(name='Parameters', value=', '.join(command.params))
        if commands.has_permissions:
            e.add_field(name='Permissions', value=''))
        if command.usage:
            e.add_field(name="Usage", value=
                        f"```\nSyntax: {self.context.clean_prefix}{command.usage if command.usage else ''}\n"
                        f"Example: {self.context.clean_prefix}{command.qualified_name} {command.description if command.description else ''}```", inline=False)
        await self.get_destination().send(embed=e)
#

I'm subclassing my help command, but i need a field added which displays what permission you need for it

fringe narwhal
#

hmm

vital glacier
#

I doubt I can really get what permissions command needs to run with dpy. Maybe I can get all function decorators somehow and extract data from there, let me check

#

!d inspect.getsource seems like a possible way

unkempt canyonBOT
#

inspect.getsource(object)```
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised if the source code cannot be retrieved.

Changed in version 3.3: [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised instead of [`IOError`](https://docs.python.org/3/library/exceptions.html#IOError "IOError"), now an alias of the former.
vital glacier
#

yeah

#

I guess i can try that ngl

fringe narwhal
#

you are more experienced than me i think

#

ive figured it out!!!

#

i have an error now tho:

Traceback (most recent call last):
  File "C:\Users\Classified", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Classified", line 52, in on_ready
    client.remove_command("help")
    ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'remove_command'
#

client has always worked for this 😄

#

idk why it doesnt 😄

#

what am i doing wrong????

radiant bough
#

hex for invisible embed?

#

or the embed color which matches with discord bg

vital glacier
#

Discord updated their looks again

naive briar
unkempt canyonBOT
#

remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to remove aliases.

Changed in version 2.0: `name` parameter is now positional-only.
naive briar
#

This is only for the discord.ext.commands.Bot class

#

Not discord.Client

fringe narwhal
naive briar
#

It's not changed at all

unkempt canyonBOT
#

Hey @fringe narwhal! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

fringe narwhal
#

i chnaged it:

try:
    client.run("TOKEN")
except discord.errors.LoginFailure as e:
    print(f"Token is invalid: {e}")
naive briar
#

Why are you using discord_slash

#

And the error means exactly what it says

unkempt mauve
#

what else can I use

#

for cogs

naive briar
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
unkempt mauve
#

cogs?

naive briar
#

Yes?

unkempt mauve
naive briar
#

Then use it

unkempt mauve
#

bruh

naive briar
#

What's the problem

unkempt mauve
#

I just can't put everything in one file

#

it makes the code messy

naive briar
#

Is that have anything to do with it

unkempt mauve
#

like in commands folder I will put all of my commands and then in the main file it will run the commands

#

cogs it is called

vale wing
naive briar
vale wing
fringe narwhal
unkempt mauve
#

didn't you get what I meant?

vital glacier
#

yeah nah

#

i saw the thing you told my friend yesterday

#

gonna look into it inna sec

#

just tryna figure out something else rn. also a problem with my help cmd

naive briar
#
from discord.ext import commands
from discord import app_commands

class ACog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command()
    async def command(self, inter):
        ...
#

Is it really that hard

unkempt mauve
#

you confused me with your answers -_-

vital glacier
#

trying to change my help help embed to the subclassed send_command_help embed. but i can't figure out how to change my help help embed because there is no command i can change the look of it. just my subclassed and mapped help command code. but that doesn't include my help command.

#

if u have no idea what that meant, lmk and i'll show u lmfao

unkempt mauve
#

okay I did it now why the heck can't I run the bot

#

bot.run() not working

naive briar
#

Be specific

vital glacier
#

which one

#

thanks LMFAO

#

multipurpose

#

real

#

im getting there, its just checking what i needa do for it

#

but i got friends who can help me lmfao

#

real

vale wing
#

@vital glacier so basically you need to get the function source first and use regex search on it

#

!e ```py
import re
deco_pat = re.compile(r"@.(?!bot_)has_permissions(.)")
perm_pat = re.compile(r"([a-z_]+)=True")

source = """@commands.command()
@checks.has_permissions(ban_members=True, manage_guild=True)
async def func(...):
...
"""

perm_deco = re.search(deco_pat, source).group()
print(perms := re.findall(perm_pat, perm_deco))```

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

['ban_members', 'manage_guild']
vital glacier
#

or can i do it get the src for all the commands and then return the permissions?

vale wing
#

That's the only way you can determine the permissions I think

#

Yeah but do it only for the commands user needs in help ig

#

What's the point of doing it for all of them

vital glacier
#

ah, alright

vital glacier
vale wing
#

And you can get source via inspect.getsource

vital glacier
#

trying to change my help help embed to the subclassed send_command_help embed. but i can't figure out how to change my help help embed because there is no command i can change the look of it. just my subclassed and mapped help command code. but that doesn't include my help command.

golden portal
#

for example you wanna set the usage?

vital glacier
#

yeah

#

and aliases etc

#

basically the help embed needs to be the same for the help

golden portal
vital glacier
#

yeah see

#

that makes 0 sense to me, i read that like 3 times and my brain keeps drawing blanks there

#

Oooh wait, i see

golden portal
#

hmm, which part is confusing?

vital glacier
#

wait let me try

#

ok now the next problem, i have my subclassed and mapped help command in my information cog, where would i need to put the attrs' then?

golden portal
#

could set it in your init, could do it in your help command constructor

#

etc

#
class MyHelp(commands.HelpCommand):
    def __init__(self):
        attrs = {'aliases': ['helps'], 'help': 'very long docs here'}
        super().__init__(command_attrs=attrs)
vital glacier
#

so here would work?

golden portal
#

you could also set it there yea, Help(command_attrs=attrs)

vital glacier
#

ok let me test it out, if i cant figure it out i'll let u know

golden portal
#

oke :3

vital glacier
#

@golden portal i love u, u are the best

golden portal
#

welcome

vital glacier
#

thank you for explaining that properly and helping me properly 🤝

golden portal
#

hehe yea, perhaps that command attrs part in the gist need to be shorten since people get confused on it ThinkO_O

vital glacier
#

either that or they need to make something like: changing the standard on_command_help help embed

#

something like that could help a lot too

golden portal
#

i suppose

rugged shadow
#

connect to db on setup hook or on ready?

golden portal
#

setup_hook, dont do it in on_ready, it fires multiple time in the bot's lifecycle

rugged shadow
#

ok thanks

unkempt mauve
#
for filename in os.listdir('./commands'):
    if filename.endswith('.py'):
        await bot.load_extension(f'commands.{filename[:-3]}')```

it's showing red waves and not loading commands
rugged shadow
#

what's the equivalent of setup hook in disnake

golden portal
#

i dont use disnake sorry

rugged shadow
#

ah that's fine

vital glacier
# golden portal i suppose

right so, i got another question right. how do i make it so if i do a command with a parameter, it'll send me the on_command_help or on_group_help embed?

golden portal
vital glacier
#

yeah sorry

#

those are the ones i meant indeed

naive briar
#

At least that's what I would do

vale wing
#

Or overwrite the start

rugged shadow
#
async def main() -> None:
    bot = Rulebot()
    await bot.connect_to_db()
    await bot.start(os.environ["TOKEN"])

something like this?

vale wing
#
class Bot(commands.Bot):
    async def start(self, *args, **kwargs):
        ... # do setup
        await super().start(*args, **kwargs)```
golden portal
rugged shadow
#

oh yeah

#

nvm mb

vale wing
#

Because code after it does not run

vital glacier
#

i mean like this

#

how do i make it do that, when i just type the prefix and command that it'll send me the help command/help group embed

#

without any params

golden portal
#

oh. so if there is a missing required argument, you send the help?

vital glacier
#

yeah i guess

golden portal
#

!d discord.ext.commands.Context.send_help you may use this

unkempt canyonBOT
#

await send_help(entity=<bot>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") or a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command").

Note

Due to the way this function works, instead of returning something similar to [`command_not_found()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.command_not_found "discord.ext.commands.HelpCommand.command_not_found") this returns `None` on bad input or no help command.
golden portal
#

and then do this inside your command error, just handle MissingRequiredArgument

vital glacier
#

huh

#

ok hold up

#

could i make it so, on_command_error(self, error: MissingRequiredArgument):
and then await send_help

#

or how would that work

golden portal
#

nop its an event for all errors occurred in text commands

#

if you see the example, you may just do this in your command error event ```py
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send_help(ctx.command)

unkempt mauve
#

Code: ```py
import discord
from discord.ext import commands
from discord import app_commands

class MyCommands(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.commands(name="mycommand", description="This is my command.")
async def my_command(self, interaction):
await interaction.response.send_message("Hello, world!")

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


Error: `Failed to load extension hello.py: Extension 'commands.hello' raised an error: TypeError: 'module' object is not callable`
golden portal
unkempt mauve
#

Failed to load extension hello.py: Extension 'commands.hello' raised an error: TypeError: parameter 'interaction' is missing a type annotation in callback 'MyCommands.__init__.<locals>.my_command' does it need interaction: discord.Interaction?

golden portal
steep marsh
#

I'm trying to do that but it wouldn't work due to the url. Not sure if I am doing it wrong

golden portal
olive epoch
#

hey helpers

#
import discord
import asyncio

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

client = discord.Client(intents=intents)

async def send_message():
    await client.wait_until_ready() # wait until the bot is ready
    channel = client.get_channel(931974039650598925) # replace with the ID of the channel where you want to send the message
    while not client.is_closed():
        await channel.send('Hello, world!') # replace with the message you want to send
        await asyncio.sleep(5) # replace with the number of seconds you want to wait before sending the message again

        client.loop.create_task(send_message()) # create a task that sends the message

client.run('your_bot_token') # replace your_bot_token with the token of your Discord bot

i got no error but the code isn't working

steep marsh
steep marsh
#

ok

olive epoch
#

i got no error but function isn't working

unkempt mauve
#
  bot.add_cog(MyCommands(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load extension hello.py: Extension 'commands.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression```
vocal snow
unkempt mauve
golden portal
olive epoch
unkempt mauve
vocal snow
olive epoch
vocal snow
#

what]

#

in your code

golden portal
vocal snow
#

where are you executing the function

golden portal
#

hence, it doesnt match your code

unkempt mauve
#

then why am i getting this

olive epoch
golden portal
#

did you save it

vocal snow
olive epoch
steep marsh
#

i love coding guys

vocal snow
#

discord.py is not easy library if you are python beginner

olive epoch
#

i know its difficlt

vocal snow
#

you need to call the send_message function somewhere

#

so it will actually be executed

olive epoch
steep marsh
vital glacier
golden portal
olive epoch
vital glacier
steep marsh
#

floweryy, how long did it take for you to get the 'active dev?'

#

for 30 days?

olive epoch
radiant bough
#

Hex for discord.Colour.dark_theme?

steep marsh
vocal snow
steep marsh
vital glacier
unkempt canyonBOT
#

error_handler.py line 49

error = getattr(error, 'original', error)```
vocal snow
#

Ensure you have this line, since some errors are wrapped in CommandInvokeError

vital glacier
#

I do

#

I basically copied that for the on_command_error handler rq

unkempt mauve
#

why isnt it registering slash cmds

golden portal
#

whats your code essentially?

golden portal
steep marsh
vital glacier
golden portal
#

its not really in dpy docs

golden portal
vital glacier
#
    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        # This prevents any commands with local handlers being handled here in on_command_error.
        if hasattr(ctx.command, 'on_error'):
            return

        # This prevents any cogs with an overwritten cog_command_error being handled here.
        cog = ctx.cog
        if cog:
            if cog._get_overridden_method(cog.cog_command_error) is not None:
                return

        ignored = (commands.CommandNotFound, )

        # Allows us to check for original exceptions raised and sent to CommandInvokeError.
        # If nothing is found. We keep the exception passed to on_command_error.
        error = getattr(error, 'original', error)

        if isinstance(error, commands.MissingRequiredAttachment):
            await ctx.send_help(ctx.command)
#

but i assume i did it wrong anyway cus i suck with error handlers lmfao

golden portal
#

MissingRequiredAttachment is for your attachments, it should be MissingRequiredArgument

vital glacier
#

Oh wait, i didnt change that back lmfao

#

Still doesn't work though

golden portal
#

perhaps you have a local error handler with the command?

vital glacier
#

wait let me test smth rq

golden portal
#

because thats what this line is doing ```py
if hasattr(ctx.command, 'on_error'):
return

vital glacier
#

nah, i dont have any error handlers as far as im aware

unkempt canyonBOT
#

@vital glacier Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

vital glacier
#

oh shi sec

#

i had this tho, but i removed it:

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        user = ctx.author
        guild = ctx.guild
        channel = ctx.channel
        timestamp = round(ctx.message.created_at.timestamp())
        code = random_string(13)
        async with self.bot.database.cursor() as db:
            await db.execute('SELECT * FROM errors')
            data = await db.fetchall()
            if not data:
                error_id = 1
            else:
                error_id = len(data) + 1
            await db.execute(
                'INSERT INTO errors (id, member, guild, channel, timestamp, code, error) VALUES (?, ?, ?, ?, ?, ?, ?)',
                (error_id, user.id, guild.id, channel.id, timestamp, code, str(error)))
            await self.bot.database.commit()
            await ctx.success(f'An error occurred while invoking command **{ctx.invoked_with}**. Report this using the reference code `{code}` in our [support server]().')

#

but that's for my traceback command

#

and even without that, it doesnt work

#

and i dont have any other error handlers in my files

golden portal
#

can you put prints in there to see if its even getting invoked

golden portal
vital glacier
#

where would i put that print tho

#

like i said, im real bad with error handling and debugging stuff like this lmfao

#

or does it not matter

quick gust
#

put it at the start of your function

quick gust
golden portal
#

like, basically parts where there could be a potential stop rly, best to be thorough

vital glacier
#

so under every if statement and under the ignored?

vital glacier
quick gust
golden portal
#

mhm its a rule of thumb really

vital glacier
#

Only error i'm getting from my ban command tha ti just ran is: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'top_role'

#

and that was the same one that I had when i was using my traceback error thing

quick gust
#

then member is None

#

can you show the code?

vital glacier
#

of the ban command?

quick gust
#

yep

#

that's what you're trying to fix right?

vital glacier
#

well, im tryna make it so it sends the help command/group help when i type a command without parameters

#

so for instance if i type ,ban it will send the ,help ban embed

#

Ah see that was indeed the problem

quick gust
vital glacier
#

It was because member: discord.Member = None

quick gust
#

this line

vital glacier
#

because now it works

quick gust
#

oh you set a default value for member

vital glacier
#

yeah cus i was rewriting my code

quick gust
#

thats great

vital glacier
#

and prob left it

quick gust
#

mhm

slate swan
#

🗿 the b alias

naive briar
#

Beans

vital glacier
#

How can i convert a guild id into the guild name?

#

i assume through the discord api?

#

or is there a different way?

golden portal
#

then just guild.name

vital glacier
#

oh bet

shrewd fjord
#

!d discord.Client.get_guild

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
shrewd fjord
#

Hm xd

fringe narwhal
#

what does positional-only mean?

#

for example:

discord.ext.commands.Bot.remove_command(help)

Prompts this error:

discord.ext.commands.Bot.remove_command(help)
TypeError: BotBase.remove_command() missing 1 required positional argument: 'name'
vital glacier
#

i've got a prefix with database integration in my bot, but i want to make it so even when i mention the bot, it'll also act as a prefix

fringe narwhal
#

hmmmm

vital glacier
#

oh welp

fringe narwhal
#

!d discord.app_commands.AppCommand.mention

#

maybe ducky_sus

#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
fringe narwhal
#

@vital glacier

vital glacier
#

yeah i had that

#

but that didnt work ithink because of my custom prefix with db

fringe narwhal
vital glacier
#

let me test it again

naive briar
fringe narwhal
#

something happened

vital glacier
#

Yeah it doesn't work because of my DB i think

fringe narwhal
# vital glacier Yeah it doesn't work because of my DB i think

Old code of mine, but this is a good example i think:

def get_prefix(client, message):
    with open('data.json','r') as f:
        data = json.load(f)
    try:
        return data[str(message.guild.id)]['server_prefix']
    except:
        return 'z!'


intents = discord.Intents.all()
client = discord.Client(command_prefix=get_prefix, intents=intents)
vital glacier
#

im not using json

#

i'm using aiosqlite

fringe narwhal
#

its the same logic though

naive briar
vital glacier
naive briar
#

Show code

vital glacier
#

of what do u want the code

#

the prefix handler in my main file or?

#
async def prefix(bot, ctx):
    async with bot.database.cursor() as cursor:
            await cursor.execute('SELECT prefix FROM prefix WHERE guild_id = ?', (ctx.guild.id,))
            data = await cursor.fetchone()
            if data:
                prefix = str(data[0])
            if not data:
                prefix = ','
            return prefix
#

and I had this

bot = Bot(
    intents=discord.Intents.all(),
    command_prefix=commands.when_mentioned_or(prefix),
    case_insensitive=True,
    owner_ids=[566434977093386258, 323118319144271872]
)

#

but those 2 dont work together

naive briar
#

Read the docs, there's an example about this

vital glacier
#

There is?

naive briar
#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
fringe narwhal
naive briar
#

And

vital glacier
#

yeah for some reason that doesnt make sense to me

naive briar
vital glacier
#

yeah but how would i do that with my db stuff tho

naive briar
#

Same way

#

What else can I say, it's there in the screenshot

#

You get your prefixes from your db > you call the when_mentioned_or with the prefixes to get a callable > you call the callable

novel bolt
#

hey , i am creating a cog so inside the init method i am creating a variable self.filter_channels and i have a async func get_set_channels() which returns the list which i would like to set for self.filter_channels . how can i do tat?

vital glacier
upbeat gust
vital glacier
upbeat gust
#

Im not sure what you're having trouble with

naive briar
#

They are probably in __init__

novel bolt
novel bolt
naive briar
#

And why are you making that function async anyway

#

You're not using await in it

upbeat gust
#

their db lib is async

novel bolt
#

yep

naive briar
#

Oh, yeah

upbeat gust
novel bolt
#

hmm

upbeat gust
#

You can make a classmethod that creates an instance of the class, calls that method, and returns that instance

novel bolt
#

oh lemme check

#

btw thenks

upbeat gust
upbeat gust
#

but replace prefixes_for with your own function that gets prefixes from the db

unique robin
#

hello guys

#

this a project that i made a bot of jokes , i was really bored so i did try make some effort on a bot like this can you rate it?

upbeat gust
unique robin
#

the first one i get it

#

the second one one idk give me example

#

the 3rd one yes i will use on next bot

upbeat gust
unique robin
#

thanks

unique robin
humble gulch
#

Help make me a discord bot plz

radiant bough
#

Any utility command ideas?

deep osprey
#
                async with aiofiles.open('test.txt',mode="a") as f:
                    text = random.choice(f.readlines())
                    line = await f.readlines()    
                    for line in f:
                        if text in line:
                            line = await line.replace(line,"")
                            await f.write(line) ``` why doesn't that delete the specified line from the txt file?
wanton hatch
#

$help

inland quailBOT
#
MemberJoinMonitoring:
  creation_time All commands related to the Creation time trigger.
​No Category:
  help          Shows this message

Type $help command for more info on a command.
You can also type $help category for more info on a category.
slate swan
#

hey im tryna customise one of my embeds. Ive noticed when you use ">" to make like a line in the embed or any message tbh. Sometimes it comes with different thicknesses. How can i get the max thickness?

wanton hatch
#

$help print

inland quailBOT
#

No command called "print" found.

velvet compass
# wanton hatch $help print

#bot-commands is probably what you are looking for. For the @unkempt canyon bot, the prefix is ! and for @lament depot .

wanton hatch
#

Hello @velvet compass

slate swan
#

hey guys, i made a restart command but it seems to not reload the cogs

#

i'm planning to during the restart it reload the cogs

#

it was suppose to repeat the "Sucess line with the other lines that was there

#

i'm having problems here with this:

        start = args.find("[")
        end = args.find("]")
        find_brackets(start, end, 0, True)
        def find_brackets(self, start, end, mod, is_outside):
            print("entered")
            total = list()
            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(mod, end[i])
                    if(is_outside == False):
                        break
            return total```

cannot access local variable 'find_brackets' where it is not associated with a value
deep osprey
#
                async with aiofiles.open(region+'.txt',mode="w") as f:
                    text = random.choice(await f.readlines())
                    #code
                    lines = await f.readlines()
                    print(lines)
                    lines.remove(text)
                    print(lines)
                    await f.writelines(lines)``` anyone got idea why this removes all lines from txt instead of the specified line
naive briar
#

Why are you opening the file in w then try to read it

#

And you can't read if the mode isn't in read mode

slate swan
#

the "find_brackets_ thing works, but when it goes to the sub-function it doesn'1t works

#

i'm trying to create a funtion that have two ways of input:
self, args

and

self, start, end, mod, is_outside

fathom sandal
#

Hi all. I put a query in the help system about using python and discord bots to solve an invitation problem I have. Is OK to briefly mention it here as well?

maiden fable
slate swan
#

strange

maiden fable
slate swan
#

is it possible to make a command that will update a string example key = "test" !updatekey test1 and it makes key = "test1" in the code

maiden fable
slate swan
#

ok

slate swan
#

i will need to learn that

maiden fable
unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
Decorators (see !tags decorators)
Inheritance (overriding methods)
Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

gusty flax
slate swan
#

Does anyone know how I can add a description to the help command?

#

code

#

oh nvm

#

to put this into perspective each command is built into one giant class

#

so Moderation is a class and those commands are sub-classes if that makes sense

#

isn't that a normal embed up there

#

for the most part yeah

tacit horizon
#

how can i use attachment with slash command

slate swan
tacit horizon
slate swan
slate swan
tacit horizon
#

no input image

slate swan
#

I recomend you read the docs, I am not a dpy main

torn sail
slate swan
#
import discord
from discord.ext import commands

class Misc(commands.Cog):
    def __init__(self, client):
        self.client = client
    @commands.Cog.listener()
    async def on_ready(self):
        print("Embed Cog is ready")

    @commands.command()
    async def embed(self, ctx):
        embed_message = discord.Embed(title="Title of Embed", description="Description of embed", color=discord.Color.green())

        embed_message.set_author(name=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)
        embed_message.set_thumbnail(url=ctx.guild.icon)
        embed_message.set_image(url=ctx.guild.icon)
        embed_message.add_field(name="Field name", value="Field Value", inline=False)
        embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)

        await ctx.send(embed = embed_message)

async def setup(client):
    await client.add_cog(Misc(client))
torn sail
#

@commands.command(description='cool description')