#discord-bots

1 messages Β· Page 43 of 1

heavy swift
#

For organizational purposes, you could have it there and reference it across all ur other files

shrewd apex
#

@commands.is_owner() ;-;

silk fulcrum
shrewd apex
#

huh? then this is same as isowner meaning only owner can use this command

silk fulcrum
#

add*

heavy swift
#

is_owner is static

#

he wants it so that people with certain roles and perms

silk fulcrum
#

add something like {owner check}

heavy swift
#

can use that cmd but the owner of the bot has a special privieldge (spelt correctly)

#

@robust fulcrum You would roughly need to do this. (https://discordpy.readthedocs.io/en/latest/api.html#permissions)

  1. Make a command that only people with certain roles on the server can use ( for eg. manage_nicknames)
@bot.command()
@has_permissions(manage_nicknames=True)
async def c_nick(ctx):
    await ctx.send("blah")
  1. Make an error for that command that sends an error for people who dont have that required permission but checks if the bot owner used it
@c_nick.error
async def c_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    if ctx.author == bot.application.owner:
      return await ctx.send("blah")
    await ctx.send("No perms")
  else:
      raise error
  1. Altogether it should look like this
@bot.command()
@commands.has_permissions(manage_nicknames=True)
async def c_nick(ctx):
  await ctx.send("blah")


@c_nick.error
async def c_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    if ctx.author == bot.application.owner:
      return await ctx.send("blah")
    await ctx.send("No perms")
  else:
      raise error
silk fulcrum
#

error hardler? uhm.... i dont think this is gud

#

hardler lmao

drifting arrow
#

Hey guys. With discord modals, is it possible to put the question into a list or dictionary?
This is what I have tried ```python
question_set.append(discord.ui.TextInput(
label=f"{i['label']}",
style=discord.TextStyle.long,
placeholder='Placeholder',
required=i['required'],
max_length=1000,
))

#

Apparently doesnt work πŸ€”

limber bison
#

Is buttons with reaction role good idea , like no. Of reaction appear in button label ?

silk fulcrum
silk fulcrum
#

what exactly do you want to do

limber bison
#

Infinite time for buttons ?

silk fulcrum
limber bison
#

Oh k k

drifting arrow
#

In a modal, if you want an input/question, you create a variable and do the discord.ui.TextInput() thing.

I want to put the selected input/question into a dictionary so I can have a single class to handle it and allow as many questions as possible.

silk fulcrum
#

That can be used to keep link buttons for example too

silk fulcrum
drifting arrow
#

Alright. Let me go back to the beginning. from the very very very start.
If I want to send a discord modal, that popup that asks for input such as what is your name? I have to set the question what is your name into a variable that contains ```python
discord.ui.TextInput(
label="What is your name",
style=discord.TextStyle.long,
placeholder='Placeholder',
required=True,
max_length=1000,
)


And if I want another question  (Up to I believe 5 or 6?), i need another variable and so on, basically repeating the same code.

I want to put the first block into a loop and pull the questions from a `json file`. so the I don't need to rummage through my code, but also I don't need to remove variables just to remove a question. I can just remove it from a `json file`
#

and from there, if there's more than 5 questions, I can send another modal.

tight dagger
#

Traceback (most recent call last):
File "main.py", line 12, in <module>
client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'

#

getting this error

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

tight dagger
# tight dagger Traceback (most recent call last): File "main.py", line 12, in <module> cl...

import discord
from discord.ext import commands, tasks
import B
import os

key=os.getenv('key')

wkey=os.getenv('wkey')

client = discord.Client()
client = commands.bot(command_prefix="(prefix)")
client.remove_command('help')
@client.command()
async def command(ctx):
await ctx.send('This command was successful!')
@client.command()
async def help(ctx):
embed = discord.Embed(name="Help", value="help command", color=0xFFFFFF)
embed.add_field(name="command", value="command description")
await ctx.send(embed=embed)
B.b()
client.run(os.getenv('TOKEN'))

tight dagger
fresh hedge
silk fulcrum
tight dagger
drifting arrow
silk fulcrum
#

i mean not subscriptable... idk

drifting arrow
#

I tried to put it into a dict.. I tried putting it into a list..

fresh hedge
drifting arrow
#

have you ever used discord modals @silk fulcrum ?

silk fulcrum
#

nop'

tight dagger
drifting arrow
#

Alright I'll wait until someone else can answer then

silk fulcrum
#

probably i am missunderstanding something(

drifting arrow
#

Until I can figure out a shorter way of doing it, I'll have to do it the long way

left idol
#

i have a line of code
super().__init__(150, 5, 5, 3, 'Dark', 'Light', 'Tank')
which returns an error

    raise TypeError(f"expected Item not {item.__class__!r}")
TypeError: expected Item not <class 'int'>

in my command but when i try it outside of my classes it works fine? my command is for a combat menu with buttons and i have my combat stats (hp, atk, etc) in a Combat view and my view in CombatView(discord.ui.View, Combat)

fresh hedge
#

I think i have a solution to ur problem

drifting arrow
#

Lots and lots and lots of if statements ;-;

fresh hedge
#

But i didn't quite understand what u want to achieve

silk fulcrum
fresh hedge
#

There is a simpler way to put dynamic discord.py modals in a loop

#

Without classes and stuff

drifting arrow
#

Well this is what I have atm..

class TestForm(discord.ui.Modal, title='Testing'):
    def __init__(self):
        super().__init__()
        self.currentform = {}
    question_set = {}
    questioncount = 0
    with open("questions.json", "r") as f:
        questions = json.load(f)
    for i in questions['questions']:
        if i['long']:
            print("Adding a long question..")
            print(i['label'])
            question_set[i] = discord.ui.TextInput(
                label=f"{i['label']}",
                style=discord.TextStyle.long,
                placeholder='Placeholder',
                required=i['required'],
                max_length=1000,
            )
        else:
            print("Adding a short question..")
            print(i['label'])
            question_set[i] = discord.ui.TextInput(
                label=f"{i['label']}",
                style=discord.TextStyle.long,
                placeholder='Placeholder',
                required=i['required'],
                max_length=1000,
            )
        questioncount += 1
            
    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Thank you {interaction.user} for applying for staff!", ephemeral=True)
``` It errors out ofc
fresh hedge
#

Just DM me that code

#

I will get back to u in an hr

#

I am outside atm

silk fulcrum
left idol
#

didn't realize i couldn't pass *args into the view

fresh hedge
#

import something from Something

#

It's a keyword which can't be used as a variable name

#

Use From isntead

#

Instead*

silk fulcrum
# left idol im still noob with classes but in that case would i just need to make my `*args`...

arguments (args):

# in function
def func(arg1, arg2, arg3):
    print(f"you passed args: {[arg1, arg2, arg3]}")
# usage
func(123, 231, 321) # output: you passed args: [123, 231, 321]

keyword arguments (kwargs):

# in function
def func(*, kwarg1, kwarg2, kwarg3):
    print(f"you passed kwargs: {[kwarg1, kwarg2, kwarg3]}")
# usage
func(kwarg1=123, kwarg2=231, kwarg3=321) # output: you passed kwargs: [123, 231, 321]

multiple arguments (*args):

# in function
def func(*args):
    print(f"you passed *args: {args}")
# usage
func(123, 231, 321) # output: you passed *args: [123, 231, 321]

multiple keyword arguments (**kwargs):

# in function
def func(**kwargs):
    print(f"you passed **kwargs: {kwargs}")
# usage
func(this=123, that=231, those=321) # output: you passed **kwargs: {"this": 123, "that": 231, "those": 321}
fresh hedge
#

python hate from
Use From instead

#

python happy

silk fulcrum
fresh hedge
#
async def moveFrom(interaction:nextcord.Interaction, From, etc)
silk fulcrum
#

oh

fresh hedge
silk fulcrum
#

yeah, shadowing names is bad

fresh hedge
#

And doesn't know English

#

So

silk fulcrum
#

from is shadowing a built-in name

fresh hedge
#

Yea basically just fixing it in a wacky way

fresh hedge
left idol
#

thank you for the info by the way

silk fulcrum
fresh hedge
#

wtf are you talking about

silk fulcrum
#

not **kwargs btw

silk fulcrum
left idol
#

alr thank you for the help!

fresh hedge
silk fulcrum
fresh hedge
#

i can but how do u explain that shit to a non English speaker

#

bending the rules

silk fulcrum
fresh hedge
#

im talking about meek

silk fulcrum
#

who asked

fresh hedge
#

dumbass read the conversation i had with him

silk fulcrum
#

any askers?

#

btw what do you mean

vale wing
fresh hedge
#

He wants to implement slash cmds

silk fulcrum
#

absolutely correct

vale wing
#

You will get syntax error if you tryna use it as a var

silk fulcrum
#

ok

fresh hedge
#

Master32 where is Master64

silk fulcrum
#

why do you need him

fresh hedge
#

My brain works in 64bit architecture

vale wing
#

Where are all other bit versions

fresh hedge
#

In his basemwnt

silk fulcrum
vale wing
#

MasterARM64

fresh hedge
#

Lmao

#

Master slave jk flip flop

#

Time for the slave

#

SlaveARM64

silk fulcrum
#

wait what the hell

#

i cant open my keepass

#

i guess i have to reboot

fresh hedge
#

That one Russian kid named Dimitri who is always better than you

vale wing
#

I base64 encoded my name

fresh hedge
#

Thanks

#

which language do u speak

#

Bruh

silk fulcrum
#

aight reboot work

fresh hedge
#

Yea u

#

Master32 please take over

silk fulcrum
#

here?

tough wagon
fresh hedge
#

I don't speak any of those languages

kindred kernel
silk fulcrum
#

these are all i have

fresh hedge
#

But you don't

#

Your skills in English is a bit too low

#

To comprehend what I wish to teach you

silk fulcrum
#

i speak russian, english and very very poor french

fresh hedge
#

Slavic

silk fulcrum
#

trad

fresh hedge
#

dies from Google trad

silk fulcrum
#

trad emeralds with google

#

aight gotta make RPS command with modes: single, with friend, online

#

what are you problems?

#

description that is on the right?

#

what lib are you using? discord.py? please not pycord

#

uhm.... okay

#

idk how slash commands are made in it

#

but im sure there is description kwarg in them

#

app_commands?

#

bruh

#

uhm... there is description

#

what's the problem

#

it doesnt show up?

#

oh, i forgot

#
    """
    Parameters
    ----------
    your params in that format
    """``` in command body
#

waht

#

no

sharp hemlock
#

whats the diff between nextcord and discordpy 2.0?

sharp hemlock
#

havent been keeping up to date

#

im still using v1.0

silk fulcrum
#
  • There is no such method get_member, and also you can just typehint User to a discord.Member so you dont need to get it
  • Same with To, you can typehint it to discord.VoiceChannel
silk fulcrum
#

then you missed a LOT of stuff

sharp hemlock
silk fulcrum
#

i just told you everything you need

buoyant quail
#

How to check if emoji is default, not custom?
i am using disnake.ext.commands.EmojiConverter.convert thing and on standart emoji it gives:

disnake.ext.commands.errors.EmojiNotFound: Emoji "πŸ‘"not found.

slate swan
#

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
What access is the bot missing
It is having admin + above my role

brazen raft
#

above my role
Are you by chance the owner of the server? Bots can do nothing to server owners

silk fulcrum
#

my reaction role works for me

#

and im an owner

#

so idk maybe im dumb

#

but bot gives me a role

brazen raft
#

Maybe they can add roles

silk fulcrum
#

and that's what he's doin

brazen raft
#

How do you know

silk fulcrum
slate swan
silk fulcrum
#
  • this: interaction.user.add_roles
brazen raft
#

Is the role you're trying to add above the highest role the bot has

slate swan
brazen raft
#

Is it in the same server

slate swan
#

Yes

silk fulcrum
brazen raft
#

!paste can you show the current code

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
#
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(style=discord.ButtonStyle.grey, emoji=":blackOne:", custom_id='persistent_view:green')
    async def idk123123(self, interaction: discord.Interaction, button: discord.ui.Button):
        eman = interaction.user.guild.get_role(960601299529904218)
        if eman not in interaction.user.roles:
            await interaction.user.add_roles(eman)
            await interaction.response.send_message(f"I've added <@&960601299529904218> role to you!", ephemeral=True)
        else: 
            if eman in interaction.user.roles:
              await interaction.user.remove_roles(eman)
              await interaction.response.send_message(f"I've removed <@&960601299529904218> role to you!", ephemeral=True)
silk fulcrum
#

useless if still here

brazen raft
#

I think you need to pass an iterable into add_roles

slate swan
silk fulcrum
#

Union[Role, Iterable[Role]]

slate swan
#

.

wanton cipher
#

is the role below the bot's highest role?

slate swan
#

Yes

wanton cipher
#

and the person the bot is trying to give it to?

silk fulcrum
slate swan
wanton cipher
#

hmmm

slate swan
#

It works in another server I tried

#

Not in the server I’m currently trying

vale wing
#

Then it's an issue with the server

slate swan
#

The server I tried before it worked in it

#

Even tho I am the owner

silk fulcrum
wanton cipher
slate swan
#
async def register(ctx):
    
    conn = sqlite3.connect("userinfo.db")
    conn = conn.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, '0')", ({ctx.author.id}))
              
    con.commit()
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

ive updated the code, but still not working :/ this is sqlite3
vale wing
slate swan
slate swan
wanton cipher
#

and one last question, the bot has the correct permissions on the server correct?

slate swan
#

so how esactly do i do it then?

silk fulcrum
#

rewriting conn with .cursor() and then using undefined cursor

slate swan
#

Yes sir
Every single permission

silk fulcrum
#

πŸ’€

paper sluice
vale wing
#

Why even put it into set bruh

paper sluice
#

no wait, why do you have a set

silk fulcrum
slate swan
silk fulcrum
slate swan
#

then can someone just help me fix the code, ive looked at so many tutorials online and I JUST dont know

wanton cipher
vale wing
slate swan
#

Where to add it like in command or view?

#

i had, but do u mind giving me the code for this one and ill understand it

#

Is it possible with discord.py interactions to get the custom_id of the button that was pressed using a callback function?

vale wing
#

Nope I do things in more elegant way and it requires several files

wanton cipher
silk fulcrum
slate swan
slate swan
wanton cipher
thick mango
#

!pastebiin

#

!pastebin

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.

silk fulcrum
vestal owl
paper sluice
slate swan
#

Set's it aside for later if I'm not wrong (aka secondary action)

silk fulcrum
vale wing
vestal owl
wanton cipher
vestal owl
#

make ur cursor just con

slate swan
#

Is there a way to get the component from an interaction?

#

Or will it stop on error?

#

Or just any way to identify what caused the interaction

vale wing
slate swan
#

I'm using buttons

vale wing
#

Idk dpy types

slate swan
#

And I need to get the custom_id or a way to get the button's identifier

#
async def register(ctx):
    
    cursor = sqlite3.connect("userinfo.db")

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, '0')", ({ctx.author.id}, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

is it like this??
silk fulcrum
#

!d discord.MessageInteraction

unkempt canyonBOT
#

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

New in version 2.0.

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

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

hash(x) Returns the message interaction’s hash.
vale wing
slate swan
#

ok

#

It's a normal Interaction

slate swan
#

discord.Interaction

#

I'm using button callbacks

vale wing
#

!d disnake.MessageInteraction.component

unkempt canyonBOT
slate swan
#

There should be a way to get the identifier shouldn't there be?

vale wing
#

Disnake has that

dull terrace
#

it would take 5 seconds to learn how to assign variables

vale wing
#

No idea about dpy

slate swan
#
async def register(ctx):
    
    cursor = sqlite3.connect("userinfo.db")

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, '0')", ({ctx.author.id}, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

is this correct?
dull terrace
#

instead you're spending ages in chat asking for people to show you code

dull terrace
#

pika, he keeps doing this

slate swan
#

Ah

silk fulcrum
#

!d discord.Message.components @slate swan

unkempt canyonBOT
silk fulcrum
#

i think this is what you want

slate swan
#

😭

silk fulcrum
#

'0' πŸ’€

slate swan
#
async def register(ctx):
    
    cursor = sqlite3.connect("userinfo.db")

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", ({ctx.author.id}, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

is this correct?
slate swan
silk fulcrum
unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

dull terrace
#

^

slate swan
#

alr then

slate swan
dull terrace
#

cursor = sqlite3.connect("userinfo.db") is this a cursor or a connection pika?

dull terrace
#

then why are you using it as a cursor

slate swan
#

lemme fix that

#
async def register(ctx):
    
    conn = sqlite3.connect("userinfo.db")

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", ({ctx.author.id}, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

fixed, and then?
silk fulcrum
dull terrace
slate swan
#

πŸ™

silk fulcrum
slate swan
#

priorities

dull terrace
sharp hemlock
#

is there a module/function that can align the text below such that the colons are in a line?

Time : 1700h        Time : 1700h
Place : Here  ->   Place : Here
Date: 01/01         Date : 01/01
dull terrace
slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", ({ctx.author.id}, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```
dull terrace
#

i ran into a similar problem, you have to consider things like the font that discord uses

silk fulcrum
#

now what are brackets used for in {ctx.author.id}?

slate swan
dull terrace
#

pika what do {} brackets do

silk fulcrum
#

not inside the f string

slate swan
dull terrace
#

you're gonna run into the same thing on the next line of code you write if you don't bother googling the most basic things

slate swan
silk fulcrum
#

btw does anyone know what to do with this shit? πŸ₯²

silk fulcrum
slate swan
silk fulcrum
silk fulcrum
#

but do not guess

#

you either know or learn google

slate swan
silk fulcrum
slate swan
#

await

silk fulcrum
#

then what's the problem?

slate swan
#

It still says missing access πŸ’€

silk fulcrum
silk fulcrum
slate swan
#

ah yes so i need to remove the {}

silk fulcrum
#

so what do they do?

dull terrace
#

if you don't know why then you've failed

brazen raft
silk fulcrum
silk fulcrum
slate swan
silk fulcrum
fresh hedge
#

lol

dull terrace
slate swan
#

it can not convert a dictionary item directly in a string.

silk fulcrum
#

bruh

fresh hedge
#

why not just use pickle instead

silk fulcrum
fresh hedge
#

quick off load and on load

brazen raft
silk fulcrum
#

idk, i didnt even know bout this module

slate swan
hollow badger
# dull terrace

You had your snarky lmgtfy link blocked twice and you think it's a good idea to bypass that with a screen shot.

silk fulcrum
#

oh?

fresh hedge
#

so why not just store it as a dictionary

#

from the get go

brazen raft
#

pickle is not asynchronous

silk fulcrum
brazen raft
#

Is that a thing

silk fulcrum
#

idk

slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```
rancid grail
brazen raft
fresh hedge
#

in the beginning

#

and dump everything in the end

brazen raft
#

Also, use an asynchronous database SQLite library

fresh hedge
#

you get the O(logn) time complexity too 🀌

dull terrace
#

7739monkathink okay ill just be quiet

silk fulcrum
slate swan
fresh hedge
#

pikaa pikapi

silk fulcrum
fresh hedge
#

you forgot to close your socket?

silk fulcrum
brazen raft
#

that_socket_object.close()

fresh hedge
#

it has a .close() method

brazen raft
#

But you should use a with statement

fresh hedge
#

^

slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
              
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

so how do i fix it? its not working
brazen raft
#

There is no error, they simply haven't committed the transaction

slate swan
brazen raft
#

db.commit() in your case

fresh hedge
#

oh lol

slate swan
slate swan
#

before cursor.close() ?

brazen raft
#

Maybe

fresh hedge
#

idt they care much about blocking and non blocking code

fresh hedge
brazen raft
#

They should

slate swan
fresh hedge
snow trench
#

Should I use replit or vscode for the bot devolopment?

brazen raft
#

I have in no way the intention to enforce anything on anybody

fresh hedge
snow trench
#

that's the problem

slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
    
    db.commit()          
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

still not working :/
fresh hedge
silk fulcrum
#

Ctrl + C if opening in terminal

snow trench
#

ok

#

I can use also the bin button?

vale wing
snow trench
#

not instantly

silk fulcrum
#

i wonder how much connections he created πŸ’€

fresh hedge
snow trench
#

ok

vale wing
silk fulcrum
slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
    
    db.commit()          
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

still not working :/ how to fix?
vale wing
silk fulcrum
vale wing
#

Can you like send its code

silk fulcrum
#

like :lmao:

vale wing
#

That thing probably happens because of unclosed database connection

#

And useful info is most likely on top of traceback or in the bottom

brazen raft
#

Might be a bug in the Discord API wrapper library that they are using

slate swan
robust fulcrum
#
@commands.command(name="translate", aliases=["trs"])
    async def translate(self,ctx,lang:str):
        reply = ctx.message.reference
        conten = (reply.cached_message or await ctx.fetch_message(reply.message_id)).content
        try:
            translated = GoogleTranslator(source='auto', target=lang).translate(conten)
            trans = discord.Embed(title=f"Translator | Translated to {lang}", description=translated,color=discord.Color.green())
            await ctx.send(embed=trans)
        except:
            await ctx.send("pls send the text you want to translate")
            def check(msg):
                return msg.author == ctx.author and msg.channel == ctx.channel
            text = await self.bot.wait_for("message", check=check, timeout=5)
            text = text.content
            translated = GoogleTranslator(source='auto', target=lang).translate(text)
            trans = discord.Embed(title=f"Translator | Translated to {lang}", description=translated,color=discord.Color.green())
            await ctx.send(embed=trans)

Guys i made this translation comamdn but when the try statement is false the except statement not excecutes
why is it not working?

silk fulcrum
vale wing
silk fulcrum
#

well connection is pretty much also should be closed cus he creates new one in every single command

slate swan
#

so how do i close these things?

vale wing
silk fulcrum
#

db.close() maybe

slate swan
#

ok

slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
    
    db.commit()
    db.close()
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

its still not working
vale wing
# silk fulcrum do i actually need it?

Personally I wouldn't call every async function from non async with asyncio tools, it's better to make the whole thing async and run it one single time

#

Anyway try it and see

silk fulcrum
#

ok...

brazen raft
slate swan
slate swan
vale wing
#

Does it work if you run SQL inside that db manager

slate swan
#

so how do i fix it

vale wing
#

Does it work or no

slate swan
#

no

silk fulcrum
# vale wing Anyway try it and see

now gives this 😳 py Failed to create connection pool. Traceback (most recent call last): File "/home/bogdan/HokkerBot/launch.py", line 70, in db_initialise run(Table.create_pool(config["DATABASE"]["uri"])) File "/usr/lib/python3.10/asyncio/base_events.py", line 622, in run_until_complete self._check_running() File "/usr/lib/python3.10/asyncio/base_events.py", line 584, in _check_running raise RuntimeError( RuntimeError: Cannot run the event loop while another loop is running

slate swan
#

how do i change it

vale wing
#

Then it's an issue with your DB

slate swan
vale wing
silk fulcrum
slate swan
#

i dont think my code is written correctly

#

maybe

vale wing
#

Write a script that executes a single statement in your db and check

silk fulcrum
#

getting a lot of these unclosed things again

slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
    
    db.commit()
    db.close()
    cursor.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

so this is 100% correct? then why its not working
silk fulcrum
#

i dont think putting db.close() before cursor.close() is 100% correct

#

but whatever

slate swan
silk fulcrum
#

probably?

vale wing
slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
    
    db.commit()
    cursor.close()
    db.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

what else isnt correct here ?
vale wing
#

@slate swan you don't even need to close the cursor

silk fulcrum
vale wing
#

It will be garbage collected

vale wing
brazen raft
slate swan
#
async def register(ctx):
    
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo (userid, balance) VALUES (?, 0)", (ctx.author.id, ))
    
    db.commit()
    db.close()

    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

is this correct now?
silk fulcrum
slate swan
#

😭

vale wing
brazen raft
#

For the first problem, use any asynchronous SQLite library

slate swan
#

...

brazen raft
#

I use aiosqlite because I just picked it

slate swan
#

im using sqlite3

brazen raft
#

It does not provide asynchronous functionality

vale wing
#

He doesn't really get the common sqlite3 yet, I would suggest understanding it first and then going to aiosqlite (in a short time ofc cause migration is aids)

slate swan
brazen raft
#

As for the second problem, I recommend opening a database connection in the setup_hook function of the bot and saving it as a bot variable

vale wing
celest basin
#

I'd also point out that it's perfectly fine to use something that isn't SQL like a dictionary storage that's synced to a JSON file via a background process

#

If that's sufficient for your current use case, at least

brazen raft
#

I feel like transacted IO is safer in case of sudden disconnection

silk fulcrum
slate swan
silk fulcrum
#

works 😳

celest basin
#

Well no, that's why I said if it's sufficient for your use case

silk fulcrum
#

wth and that's it? it just works?

brazen raft
vale wing
silk fulcrum
#

bruh

vale wing
#

That's what I said at first β€” "unclosed connection"

pulsar solstice
#

hey I want to ask that how to host my bot for 24/7 free

#

I was using replit till now

#

but its bad

silk fulcrum
pulsar solstice
#

offline

slate swan
pulsar solstice
slate swan
vale wing
pulsar solstice
vale wing
#

Oracle

#

Amazon AWS

silk fulcrum
vale wing
#

Microsoft azure

#

Go ahead

silk fulcrum
#

well, almost

pulsar solstice
vale wing
vale wing
#

πŸ’€ indeed

pulsar solstice
#

bruh I am a teen and I don't have lot of money to spend on a discord bot

silk fulcrum
#

did you say that because we both...

#

beuh

vale wing
silk fulcrum
#

how lucky that my dad is a programmer and he has the host:)

celest basin
brazen raft
#

AWS requires credit card info

vale wing
#

I made a server from old computer parts and it's ok

vale wing
#

That's the only small issue

brazen raft
silk fulcrum
vale wing
#

It's a shame I can't get a Kazakhstan card without going to Kazakhstan

celest basin
#

So I'd imagine a Raspberry Pi 4 would have all the compute you could possibly want for a well written bot

vale wing
#

I run 5 bots on intel pentium and 3gb of DDR3 RAM

brazen raft
#

How does a machine have anything to do with "well written-ness"

silk fulcrum
vale wing
celest basin
vale wing
#

😩

#

Thx god I managed to rewrite it to async one

brazen raft
#

Well written implies you already wrote an optimal program that works well on your machine

celest basin
#

Yes, which is why I said if it was well written then a Pi should be plenty for whatever you're trying to do

brazen raft
#

If it is well written it doesn't matter the machine

celest basin
#

If it's not well written, because you're doing stuff in cubic time that should be linear, then you're not going to have a good time

shrewd apex
celest basin
#

But you might still be able to get it to run on your gaming rig or whatever

rugged shadow
vale wing
vale wing
shrewd apex
#

how bad written would have to be to make cpu 100% almost impossible

rugged shadow
#

ask your parents

brazen raft
shrewd apex
#

so for general cases bots about 4gb ram is enough

#

to support ur bot for most part

celest basin
shrewd apex
#

rpi 4b+ has like 8gb

vale wing
#

I'd say 1gb is ok

brazen raft
shrewd apex
#

yeah 1gb ok if it's unverified

shrewd apex
brazen raft
#

Why does it matter

vale wing
shrewd apex
brazen raft
shrewd apex
#

yep

brazen raft
#

4GB for the bot process is too much

shrewd apex
brazen raft
maiden fable
celest basin
#

Extra might help if you're running on 2000+ servers

shrewd apex
#

yeah

night crater
brazen raft
vale wing
shrewd apex
#

bot*

vale wing
#

Understandable

celest basin
#

I mean when you get up to scales like Carl, you shard onto multiple servers

brazen raft
#

Discord API wise

#

On top of registering the slash commands

#

But that's like a one time thing

night crater
#

Dropping the ws gateway just makes the amount of load you need to deal with much much lower unless you actually physically need the gateway events like on_message. But realistically that probably works better in it's own service

#

at scale the difference between handling 5,000 events/s vs just handling a few events when people actually trigger commands, is bigggg

brazen raft
#

What Discord API mechanism handles executing slash commands

vale wing
#

To use slash commands you'd still need the gateway wouldn't you

celest basin
#

But for something that runs on <75 servers then 1GB is likely fine, 4GB if you're doing something really complicated

night crater
vale wing
#

Ok

#

Yeah I remember you can redirect the events to custom endpoint

night crater
#

Everyone is just using the gateway because most libraries use it, even though in reality it's easier to use the webhook system unless you absolutely need live events

silk fulcrum
#

how can I fix this? Extension 'cogs.fun' raised an error: DeprecationWarning: ssl.PROTOCOL_TLS is deprecated

brazen raft
#

Couldn't everything be web hooked

night crater
vale wing
#

You'd need to host a server with static IP to accept the incoming requests

brazen raft
shrewd apex
#

found it

night crater
#

they're different payloads. But webhooks are only triggered when commands are triggered. Rather than unconditionally like on_message, or member updates, etc...

celest basin
#

Anyway, having accidentally diverted the conversation, all I was trying to say was that for the a cost of Raspberry Pi you should be able to run pretty much what you want, as long as you're not writing stupidly unperformant code

shrewd apex
#

βœ…

celest basin
#

And it'll be as stable as your ISP

brazen raft
night crater
celest basin
shrewd apex
#

just keep a backup power and run rpi on that to prevent frying it due to voltage fluctuations in power cuts

celest basin
#

I run mine through a surge protector

night crater
# brazen raft Slash commands don't seem conditional

I mean along the lines, the if you have a command lets say called foo and I call it with /foo, then it'll trigger my webhook. Because someone has used my command.

But if I wanted to get the messages of everything going on in the server lets say, I wont be able to. Because it only sends interaction events via the webhook.

shrewd apex
#

yeah all cool then

celest basin
#

UPS are expensive, running through a permanently plugged in power bank is a fire risk, but a surge protected power strip is <Β£10

shrewd apex
slate swan
#

How do I make it so
If the user says
,timer 1h
It should wait for 1h and then edit the message

celest basin
shrewd apex
#

also rpi itself is a fire risk if u don't have fans or heat sinks when u use long term perfomance drops also due to temp altho they throttle the pc its not completely safe

shrewd apex
slate swan
#

I did try aasnycio.sleep(3600)
But I don’t want the user to use seconds

unkempt canyonBOT
shrewd apex
#

parse get seconds then use asyncio

slate swan
#

Any sugar example?

shrewd apex
#

it's like one line

slate swan
# shrewd apex atleast open the link
@bot.command()
async def timer(ctx, time):
    Msg =await ctx.send(β€œLet the timer begin”)
    duration = Duration(time)
    await asyncio.sleep(one_hour_duration.to_seconds())
    await Meg.edit(β€œended”)
#

duration.to_seconds()*

shrewd apex
#

CTX, *, time

celest basin
slate swan
#

Doing this is correct or it requires me to store duration.to_seconds() in a far?

#

Var*

shrewd apex
#

it's fine

slate swan
#

k ty

shrewd apex
#

altho one_hour_duration is undefined here

slate swan
mossy jacinth
#

Hey! I want to send this mostly in a general chat but if there is no general chat because it has a other name it doesnt send anything

celest basin
dull terrace
mossy jacinth
slate swan
dull terrace
brazen raft
slate swan
#

and what about discord.utils.now() + discord.utils . . ?

brazen raft
#

discord.utils.utcnow() simply returns a UTC aware datetime.datetime object

#

So you can obviously use datetime.timedelta objects as you normally would

dull terrace
brazen raft
#

discord.py wants its users to use UTC aware datetime objcets

slate swan
#

but i mean if the user uses 1h it wont work at (minutes=mins) right?

brazen raft
#

I don't know whether they have enforced using them everywhere datetime objects are used

slate swan
#

in simple word show can i create a timestamp for x minutes from now?

shrewd apex
#

bruh convert to seconds then add to timedelta

slate swan
#

aka the time user sent

brazen raft
dull terrace
#

Oh okay, probably doesn't effect me then froggy_chill

slate swan
brazen raft
#

You used datetime.now() so it might break things

bleak atlas
#

Hi, I'm making a warn command, and all works fine, when I send the data in a channel, all gets displayed properly, but I want to store it into a database, I'm using sqlite3, but I've tried it all, it does not store anything into the database... Can't figure out what's wrong

data = [member, reason, case_number, ctx.author]
    cursor.execute(f'INSERT INTO warns (member, reason, id, moderator) VALUES (?,?,?,?)', data)
#

I am doing connection.commit()...

vale wing
#

Also use aiosqlite

bleak atlas
bleak atlas
shrewd apex
#

ur storing member id as int? is it even fitting?

vale wing
#

Why are you using f string tho

bleak atlas
#

a random int

shrewd apex
#

wait no u are even storing Member object

bleak atlas
bleak atlas
shrewd apex
#

is that even a decent thing to do is it a good practice pithink

shrewd apex
#

what happens if like discord makes changes to member object will the previously stored member object even be valid

#

also if it's member object why are u storing it as string ie text

bleak atlas
#

Isn't that good?

shrewd apex
#

just store member id and fetch in ur code later

brazen raft
bleak atlas
brazen raft
#

Maybe an exception was raised that was silently ignored by the default exception handler

bleak atlas
#

For the db

brazen raft
#

You can register exceptions to be handled in discord.py exception handling mechanisms

#

Or just do a try-except sqlite3.Error

#

I think it should actually print it anyway

#

Since it isn't registered as an exception type to be handled by discord.py

#

So no SQLite error has occurred

bleak atlas
#
async def warn(ctx,
               member: disnake.Member = commands.Param(name="member", description="The member you want to warn."),
               reason: str = commands.Param(name="reason", description="The reason for the warn.")):
    connection = sqlite3.connect("databases/warns.sqlite")
    cursor = connection.cursor()

    # cursor.execute("CREATE table warns (member varchar, reason varchar, case int, moderator varchar)")
    case_number = random.randint(101, 100000)

    await ctx.send(f"Member: {member}, Reason: {reason}, id: {case_number}, Moderator = {ctx.author}")
    data = [member, reason, case_number, ctx.author]
    cursor.execute(f'INSERT INTO warns (member, reason, id, moderator) VALUES (?,?,?,?)', data)```
#

I tried inserting like regular strings and int without the f strings, still didn't work..

brazen raft
#

The database connection object will be garbage collected anyway

#

In the way you do this

#

First of all use an asynchronous library like aiosqlite

#

sqlite3 is synchronous and this means it blocks

brazen raft
#

Secondly, you should open a database connection once and save it in the bot as an attribute of the bot

#

That way, you can use the database connection object thru the bot variable

bleak atlas
brazen raft
#

I don't know much about disnake, but I do this

async def setup_hook() -> None:
    conn = aiosqlite.connect("database.db")
    await initialize_database()
    bot.db = conn


bot.setup_hook = setup_hook

or this if I subclass the bot class and instantiate my subclass:

async def setup_hook(self) -> None:
    conn = aiosqlite.connect("database.db")
    await initialize_database()
    bot.db = conn
#

Basically this

slate swan
#

aiosqlite.connect is an awaitable

brazen raft
#

Is it

slate swan
#

yessir

brazen raft
#

Well then await it in your code

bleak atlas
#

Yea, in the docs yes

brazen raft
#

I actually pip installed it real quick on my local machine right now to see if it is awaitable

#

I didn't see anything that says it is

vale wing
brazen raft
#

If it is then it is

vale wing
#

In docs they haven't stated that it is awaitable, although it is

#

Too bad

robust fulcrum
#
@commands.command(name="translate", aliases=["trs"])
    async def translate(self,ctx,lang:str):
        reply = ctx.message.reference
        conten = (reply.cached_message or await ctx.fetch_message(reply.message_id)).content
        try:
            translated = GoogleTranslator(source='auto', target=lang).translate(conten)
            trans = discord.Embed(title=f"Translator | Translated to {lang}", description=translated,color=discord.Color.green())
            await ctx.send(embed=trans)
        except:
            await ctx.send("pls send the text you want to translate")
            def check(msg):
                return msg.author == ctx.author and msg.channel == ctx.channel
            text = await self.bot.wait_for("message", check=check, timeout=5)
            text = text.content
            translated = GoogleTranslator(source='auto', target=lang).translate(text)
            trans = discord.Embed(title=f"Translator | Translated to {lang}", description=translated,color=discord.Color.green())
            await ctx.send(embed=trans)

Guys i made this translation comamdn but when the try statement is false the except statement not excecutes
why is it not working?

slate swan
#
async def register(ctx):
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()

    cursor.execute("INSERT INTO userinfo(userid, balance) VALUES(?,?)", (ctx.author.id, 0))
    
    db.commit()
    db.close()

    await ctx.send("Registered!")```

why is my code not working? :/
#

its not connecting to database

vale wing
slate swan
vale wing
#

Locked database? Wtf

#

Just delete the file if you don't have any import data in there

robust fulcrum
slate swan
vale wing
#

And don't create the file manually

#

Let the code create it

slate swan
#

?

vale wing
#

I hope you are executing setup statement in setup_hook or start

vale wing
slate swan
brazen raft
#

So it is a function

#

It just returns an awaitable instance?

vale wing
#

Weird logic

slate swan
#
async def setup_hook(self) -> None:
    conn = aiosqlite.connect("userinfo.db")
    bot.db = conn

    cursor.execute("INSERT INTO userinfo(userid, balance) VALUES(?,?)", (ctx.author.id, 0))
    
    db.commit()
    db.close()

    await ctx.send("Registered!")```

like this?
brazen raft
#

This is indeed the weirdest asynchronous interface I've seen in Python

glad cradle
#

ctx.send in setup hook?

vale wing
#

This thing makes no sense

glad cradle
#

lol

slate swan
vale wing
#

setup_hook is a method of Bot you must override

#

Not a command

unkempt canyonBOT
#

aiosqlite/core.py line 153

def __await__(self) -> Generator[Any, None, "Connection"]:```
slate swan
#

oh

brazen raft
slate swan
#

mhmmmm

brazen raft
shrewd apex
#

just use asyncpg pithink

silk fulcrum
#

using already

slate swan
#

json gang where

shrewd apex
#

swas server

robust fulcrum
silk fulcrum
rugged shadow
primal token
robust fulcrum
rugged shadow
#

still says Exenifix though :P

robust fulcrum
hard hinge
#

Hi peepz, so i made a bot that stores the message date in a MySQL DB.
Code write to MySQL:

    global cursor
    global db
    global guild
    cursor.execute("select * from members_message WHERE member_id  = '{}'".format(m.author.id))
    db_get_user = cursor.fetchall()
    print(db_get_user)
    if len(db_get_user) == 0:
        cursor.execute("INSERT INTO `members_message` (`member_id`, `members_message_date`) VALUES ('{}', '{}')".format(m.author.id, date_now))
        db.commit()  
        print("Insert nieuwe user")        
    else:
        cursor.execute("UPDATE members_message set members_message_date = '{}' WHERE member_id = '{}'".format(date_now, m.author.id))
        db.commit()
        print("Update bestaande user")
        ```

Now i have a thread loop that gets the user ID, if last message was send longer then 1 month.

Code:

def Minute():
global member_from_DB_to_kick
threading.Timer(4, Minute).start()
cursor.execute("SELECT * from members_message where members_message_date < now() - INTERVAL 4 week")
db.commit()

show_date = cursor.fetchall()
member = show_date[0][0]```

Now i need to kick the user from the server.

I want that to do with:

async def kick_member(member):
    
    guild_id = 1002208148930691172
    member_id = member
    reason_str = "..."
    guild = await bot.fetch_guild(1002208148930691172)
    member = await guild.fetch_member(member_id)
    await member.kick(reason = reason_str)            ```

but i can't, because it's `async`
So i can't call it.
How can i let them work together?
shrewd apex
#

omg pithink this is wrong in so many levels

#
  1. MySQL is sync u need async
  2. don't use threads use a task loop
  3. don't use global
  4. prolly others which i will know when i read the code thoroughly
shrewd apex
west veldt
#

hey i was trying to make a meme command everything is working fine but i want the bot to react on the meme it just sent idk how to do that please help me

#
@bot.command()
async def meme(ctx):
    content = get("https://meme-api.herokuapp.com/gimme").text
    data = json.loads(content,)
    meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
    await ctx.reply(embed=meme)```
shrewd apex
west veldt
junior verge
#

Don't fully get this

#
@client.event
async def on_message(message):
    if message.author.client:
        return
shrewd apex
west veldt
crystal crater
#

pls help

#

pls help

junior verge
#

relax

shrewd apex
#

pip install requests

crystal crater
#

ty

shrewd apex
#

also bruh if u gonna ask help with a nuker atleast change the file name

crystal crater
#

lul

junior verge
#

GANG-Nuker lol

crystal crater
#

okkk

west veldt
# shrewd apex ```py msg = await CTX.reply() await msg.add_reaction() ```
@bot.command()
async def meme(ctx):
    content = get("https://meme-api.herokuapp.com/gimme").text
    data = json.loads(content,)
    meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
    await ctx.reply(embed=meme)
    await message.add_reaction(reaction1)
    await message.add_reaction(reaction2)``` is this the same thing?
shrewd apex
#

u think πŸ—Ώ

west veldt
#

...

shrewd apex
#

how it the same?

junior verge
shrewd apex
#

do message = await CTX.reply()

#

u need the message object

west veldt
#

o

shrewd apex
junior verge
#

Yeah but I use client? Or doesn't that matter

glad cradle
crystal crater
#

how to update pip

left notch
#

pip install --upgrade-pip

#

if i remember correctly

junior verge
shrewd apex
crystal crater
#

;))

shrewd apex
junior verge
left notch
shrewd apex
#

^^

left notch
#

bruh

#

gotta report to mods

crystal crater
#

wdym?

left notch
#

BRUHJ

shrewd apex
#

not making he prolly cloned or installed from somewhere

crystal crater
#

dont report it, its not a nuker

junior verge
crystal crater
#

its a self bot

junior verge
crystal crater
#

and its cloned

junior verge
crystal crater
#

from GANG Nuker github

glad cradle
crystal crater
#

pls dont i was testing it please dont report

junior verge
shrewd apex
#

y sqlite

left notch
crystal crater
#

it was testing i swear to god

#

i left raiding and nuking after 2 years

junior verge
crystal crater
#

i dont want to get reported again

glad cradle
west veldt
#
@bot.command()
async def meme(ctx):
    content = get("https://meme-api.herokuapp.com/gimme").text
    data = json.loads(content,)
    meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
    await ctx.reply(embed=meme)
    msg = await CTX.reply()
    await message.add_reaction(reaction1)
    await message.add_reaction(reaction2)``` ```raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'CTX' is not defined```
crystal crater
#

i left that goddam stuff

junior verge
west veldt
#

um

glad cradle
junior verge
shrewd apex
glad cradle
shrewd apex
#

this is what happens when u use sync db in async stuff

#

u corrupt ur own db

west veldt
#

it didnt work either

glad cradle
west veldt
glad cradle
shrewd apex
#

CTX <-- this is just my keyboard messing up

crystal crater
#

ERROR: Could not find a version that satisfies the requirement PIL (from versions: none)
ERROR: No matching distribution found for PIL

shrewd apex
#

whenever i type CTX it makes it CTX see

crystal crater
#

HELP

shrewd apex
glad cradle
#

the error is pretty self explanatory

shrewd apex
#

how u can say that with a straight face beats me πŸ—Ώ

crystal crater
#

πŸ—Ώ

#

truely pls help

junior verge
hard hinge
slate swan
#

the PIL project has been discontinued iirc

crystal crater
#

'' ERROR: Could not find a version that satisfies the requirement ultrarequests (from versions: none)
ERROR: No matching distribution found for ultrarequests ''

#

help\

glad cradle
junior verge
#

Where does it say that

glad cradle
# junior verge erm

your error says sqlite3, and then you should know what you are using since you have downloaded and imported the module into your code

slate swan
shrewd apex
#

he attempted two writes to the db at same time

slate swan
shrewd apex
#

idk how he managed to lock the db then

#

Β―\_(ツ)_/Β―

slate swan
#

yes.

crystal crater
#

ERROR: Could not find a version that satisfies the requirement ultrarequests (from versions: none)
ERROR: No matching distribution found for ultrarequests

#

HELP ME

vocal plover
#

I wouldn't say that falls under common sense, how are you to know something is a bad practice to begin with if people don't tell you that? Saying it's a lack of common sense discourages people from programming or asking for help

slate swan
#

that library simply doesn't exist

shrewd apex
#

first time i read that as ultra-rare-requests

junior verge
#

It was running on 2 screens in my vps

crystal crater
#

ModuleNotFoundError: No module named 'ultrarequests'

crystal crater
#

But its saying that

junior verge
#

I think I broke my bot with an on_message lol its not responding to anything rn

shrewd apex
#

but docs exist for examples u can avoid such situations just by reading up a bit

slate swan
junior verge
#

client.listen?

slate swan
#

if you use client for commands.Bot,yes

junior verge
#

Why use listen instead of event?

#

Event always works fine

shrewd apex
#

u could also add process_commands

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
shrewd apex
#

and work with event also

slate swan
#

because it doesn't override the default on_message method

junior verge
#

Hm let's see

#

Bot seems to be working but not adding xp to a user

slate swan
#

do you commit to the database after writing stuff?

junior verge
#

yeah

#

!paste

ashen locust
#

How to do you make a discord bot mention someone? Like for example I typed !cool @member and the bot said "@member is cool" or something

silk fulcrum
#

argument?

ashen locust
#

what? sorry im kinda new so i dont know what u mean

ashen locust
#

oh if u mean just put it in an argument i dont want that i want if someone doesnt mention a user it sends an error

silk fulcrum
#

well... Member takes a name too...

#

hmmm

#

oh wait

#

you can check message.mentions

glad cradle
#

he could also use if isinstance(member, discord.Member)

silk fulcrum
#

that works?

slate swan
#

yes

silk fulcrum
#

ok

slate swan
#

you can compare any object with the base class

glad cradle
#

sup

ashen locust
#

ill just use an argument but thanks for the help guys

pale turtle
#

AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

self.pool = self.loop.run_until_complete(asyncpg.create_pool(dsn=self.get_env("URL"), min_size=1, max_size=5))

I think it worked for me a while back, what should I do?

#

self is commands.bot

silk fulcrum
#

Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

pale turtle
#

And how do I do that

meager chasm
#

create the setup_hook method ad handle it there

silk fulcrum
pale turtle
#

Everything about it. It used to work once did something change?

meager chasm
#

Yes, asyncio's programming guidelines changed and discord.py changed to conform to them

slate swan
pale turtle
#

But I am doing it in a non-async function

silk fulcrum
#

async with in non async function :cat_dance:

paper sluice
pale turtle
#

the __init__ function

#

I don't know what a setup hook is

meager chasm
#

the _init_ of what?

slate swan
meager chasm
paper sluice
#

in short terms, in the subclass or Client/Bot, just have an async function called setup_hook and do your stuff there

pale turtle
#

Uh ok ok I get it

buoyant quail
#

How to defer interaction without Bot is thinking...?
defer(with_message=False) doesn't work

silk fulcrum
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
silk fulcrum
#

thinking kwarg

buoyant quail
#

p.s. using disnake )

silk fulcrum
#

!d disnake.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

Changed in version 2.5: Raises [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") when an interaction cannot be deferred.
junior verge
#
profile_picture = await load_image_async(str(member.avatar.url))
``` What's wrong here?
silk fulcrum
buoyant quail
#

what to do with modal? :p

silk fulcrum
buoyant quail
#

ok

#

i will send response and delete it

#

thx

junior verge
silk fulcrum
#

dpy, disnake, nextcord, hikari

junior verge
#

dpy

silk fulcrum
#

are you using 2.0?

junior verge
#

No

#

1.7.3

silk fulcrum
#

then it's avatar_url

junior verge
#

Ah yeah I forgot mb

#

thanks though heart

digital forge
#

guys do you have any suggestions for features to implement in my bot . Also is there any server where you can basically show your bot to others?

slate swan
#

because selfbots do the funny

silk fulcrum
pale turtle
#

Isn't there the discord.py server bot channel or smth?

pale turtle
#

They removed it?

silk fulcrum
#

and you can add your bot to there if you get verified by.. Danny? iirc

pale turtle
#

Yeah it is still there tho

#

The bots category

hard hinge
#

How can i use:

await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)

It doest get the prune_members and invalid syntax after ,

silk fulcrum
#

b-b-bruh

hard hinge
silk fulcrum
#

ohkay

junior verge
#

Is there any way to see your vps his ram with a command? like .ram 500mb/1gb for example

hard hinge
#

Idk how i can inplement it

silk fulcrum
junior verge
#

Ubuntu

#

Linux