#discord-bots

1 messages · Page 140 of 1

shadow vigil
#

lol is that your goal : sob :

slate swan
#

kinda ,yes

maiden fable
#

or your condition

glass quail
#

🤔 yeah I’ll have to look at a guide to walk me through it lol

maiden fable
#

You should see their API (if they got any) or search YouTube I am sure there are some

slate swan
maiden fable
#

You're welcome

gleaming herald
#

what would happen if bot commands do not have timeouts?

maiden fable
#

Wanna join me in completing IT Project?

slate swan
maiden fable
maiden fable
glass quail
gleaming herald
slate swan
maiden fable
glass quail
maiden fable
shadow vigil
maiden fable
#

What kind of example u talking about here?

gleaming herald
#

a command with no timeout

glass quail
gleaming herald
#

and how it will block the bot

shadow vigil
maiden fable
#

It can crash the bot if the command takes too much resources
It can block the event loop of the bot which will render the bot unresponsive. Though it hardly happens, it will happen when u use sync libraries like time, requests etc

shadow vigil
slate swan
#

really had second feelings that its more advanced than taught and will get rejected

maiden fable
slate swan
#

lol it works that way most students in my class did same

maiden fable
#

Its easy

#

But ot so eh imma go complete it

slate swan
#

is it python mysql bindings or just raw sql

maiden fable
#

MySQL.connector

slate swan
#

laughing_man throw some asyncio and run_in_executor in it

maiden fable
#

Bro, my peers and teacher already think I am some Python god so no thanks

shadow vigil
#

ngl it was so so easy but for them, it's deadly hard

slate swan
#

the examiner was in next room and he was like
help others if you're done

maiden fable
#

Nice

maiden fable
#

Its kinda weird but okay if u think like that

shrewd apex
#

🗿it was a joke bruh

maiden fable
#

I am at that point of my life where jokes are serious and seriousness is joke

maiden fable
#

you joke

maiden fable
slate swan
warped mirage
#

I need some help

#

So a basic command, wc_set, one option, and yea it posts in a specific channel what the user said in that option. and like a list of available things, if its in the list, then it sends, if not, then it says this item doesnt exist on the list. and obvs lower or caps doesnt matter, as long as spelling is correct

slate swan
#

So- what is the actual issue?

warped mirage
slate swan
#

What have you tried so far?

warped mirage
#

Idk just made the basic so async def and that

sick birch
slate swan
sick birch
#

thisFirst steps would be to create a function definition.

#

Show us what you've got so far and we'll go from there

warped mirage
#

This is all I have atm

sick birch
#

That's a pretty good start, you've got a slash command that takes no arguments

#

So you want 2 arguments:

  • the channel to post it to
  • a list of things they can say
#

Start off with the channel, as that's the easiest. See what you can come up with

warped mirage
#

Well. Not quite. the only option they have is the country. it will automatically send the thing into a specific channel i have

sick birch
#

Ah, you want it to be a pre-selected channel?

warped mirage
#

Yes

#

like a specific one

sick birch
#

Alright, no prob. Just one argument then:

  • a list of things they can say
#

let me find the appropriate docs, it's been a while since i did this. give me a sec

warped mirage
#

Correct, in other words. just one country lmfao

sick birch
# warped mirage Correct, in other words. just one country lmfao

Ah here's an example

@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
@app_commands.choices(fruits=[
    Choice(name='apple', value=1),
    Choice(name='banana', value=2),
    Choice(name='cherry', value=3),
])
async def fruit(interaction: discord.Interaction, fruits: Choice[int]):
    await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.')
#

As noted in the docs, however, there are 2 better ways to do it

#

The easiest way would be to use a Literal, the best way (while not as easy, still pretty easy, however) would be to use an Enum

warped mirage
#

hmm

#

Let me explain what i mean

#

choices = ["England", ""... and so on]

if msg doesnt equal choices, sends a ephemeral, this doesnt exist
if choice equals in the message, then send to channel. idk how to explain

#

I am making a command for world cup. so whichever team wins. but only the team that are in group stages. if not in it. then the country doesnt exist in world cup.

sick birch
#

I get what you're saying - this is exactly what you need

warped mirage
#

Oh ok

sick birch
warped mirage
#

Oh. nvm i made a mistake

sick birch
#

It's impossible to pick something that's not an choice you've defined

warped mirage
#

I meant country is the option. and u write a any country. I was confused sorry

#

for example

sick birch
warped mirage
#

/wc_set country: england

sick birch
#

No options to choose from?

warped mirage
#

kinda confusing

sick birch
#

I don't see why you can't use a option for that

warped mirage
#

Idk, i guess I just want it that way lol. itll be better for me

sick birch
#

The UI is very nice for it - discord shows you all the options you can choose from and you just need to point and click

#

Much easier on your end as well because you don't have to handle the case of "user picked an invalid option"

#

Because it's impossible to pick an invalid option

warped mirage
#

I mean that would be easier for me to understand. But whatever works.

sick birch
#

Just make sure you

from typing import Literal

at the very top

warped mirage
sick birch
#

Oh that is quite a lot

warped mirage
#

ye, there is a bunch lmao

sick birch
#

it should work but I would recommend changing it to an Enum later on

warped mirage
#

Okay

sick birch
#
class Country(enum.Enum):
  Netherlands = 1,
  Ecuador = 2,
  ...

@client.ree.command(...)
async def wc_set(interaction: discord.Interaction, country: Country):
  ...
#

When you switch later on

warped mirage
#

Okay

#

so what should I do now?

sick birch
#

Does the wc_set function have anything in it's body?

warped mirage
#

Like wdym

sick birch
#
@client.tree.command(...)
async def wc_set(interaction: discord.Interaction, country: Country):
  ... # anything here?
warped mirage
#

Not yet

#

Rn i was just setting the literal

sick birch
#

Just put some placeholder like:

await interaction.send(f"The country you chose was: {country}")
warped mirage
#

So i need an if statement, if the country doesnt equal to what is in the literal, nothing happens. if it does. then it sends message

#
if country != Literal:
        await interaction.response.send_message("This country is not in the world cup..", ephemeral="True")
    else:
        await interaction.send(f"The country you chose was: {country}")```
#

This would work?

sick birch
#

You just need

await interaction.send(f"The country you chose was: {country}")
#

A user can only pick from the options you give them

warped mirage
#

Wait what are we doing

sick birch
#

So you don't need to worry about handling that

warped mirage
#

Im confused

sick birch
#
@client.tree.command(description="Set your wc country")
async def wc_set(interaction: discord.Interaction, country: Literal[...]):
  await interaction.send(f"The country you chose was: {country}")
warped mirage
#

oh

sick birch
#

Your code should look something like that

#

With the countries filled in of course

warped mirage
#

I wanted to do like this lmao. so any string

sick birch
#

Oh you want them to be able to pick 3 different countries?

warped mirage
#

Only 1. for example lets take wc1 as an example. when u click on it. no options get shown. U write any string. but if it doesnt exist on the list of countries, then send message lol

naive briar
#

Use autocompletes

sick birch
#

What we're doing here is when you click on wc1, it shows a list of options you can pick from

warped mirage
#

oh, i thought something else

sick birch
warped mirage
#

is it possible to do what i said or not really

sick birch
#

Random image i found online

#

Demonstrates it pretty well

#

What code do you have so far? It should actually work right now

warped mirage
#

same what u showed

warped mirage
#

yh

sick birch
#

Sync your command, and run it in discord

#

It'll be easier to understand once you can actually see it

gilded lily
#

I just had a funny idea for a project. An Eliza like discord bot that just replies with generic leading questions and is named "Professor R. Duck"

fading dirge
#

how do I enable slash commands on my bot?

slate swan
fading dirge
slate swan
#

Remember to only sync when you actually need to though 🙂

normal ginkgo
warped mirage
#

@sick birch

#
@client.tree.command(description="Set your wc country")
async def wc_set(interaction: discord.Interaction, userchoice):
    choices = ["dawda", "fwqfwffw"]
    if userchoice not in choices:
        await interaction.response.send_message("This team is not in the list", ephemeral=True)
    else: 
        await interaction.response.send_message(f"I have selected your team as {userchoice}")
        channel = await interaction.guild.fetch_channel(232323131313)
        await channel.send(f"{interaction.user.id} Chose {userchoice}")
        open(f"./choices/{interaction.user.id}", "w").write(userchoice)``` would this work?
topaz helm
#

Does anyone have a staff application system?

#

(py)

shrewd merlin
#

anyone know the code off the top of their head to make a scheduled event happen each day?

sick birch
warped mirage
sick birch
#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
warped mirage
#

But I need help

sick birch
#

With?

slate swan
#

can someone help me please

#

im making a very simple but i keep getting an error message

warped mirage
sick birch
slate swan
#

sure on seck

sick birch
slate swan
#

there is a picture of my code and error message

warped mirage
sick birch
#

So what's the issue?

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
warped mirage
sick birch
slate swan
sick birch
# warped mirage idk, how to do.

Looks like you're already doing it no?

        channel = await interaction.guild.fetch_channel(232323131313)
        await channel.send(f"{interaction.user.id} Chose {userchoice}")
sick birch
#

Which is why you're getting that error

#

They made intents require on versions 2.0 and above

slate swan
#

oh right, so how can i fix it?

sick birch
#

If you'll look at the embed it should have a code snippet showing how to include intents in your code

Also make sure to enable it in your developer dashboard

slate swan
#

sorry this is the first time ive made a bot

#

yeah it say init()

warped mirage
#
@client.tree.command(description="Set your wc country")
async def wc_set(interaction: discord.Interaction, country: Literal[...]):
await interaction.send(f"The country you chose was: {Literal}")
channel = await interaction.guild.fetch_channel(232323131313)
 await channel.send(f"{interaction.user.id} Chose {Literal}")
#

Should be fine I think

sick birch
#

The indents look a bit messed up but I'm not sure if it's just discord screwing it up

#

After that just sync your command like usual and it should work

slate swan
#

so how should i change line 4 to use intent?

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.

sick birch
#

Like in that little code box

slate swan
#

okay lemme try

#

im rlly bad at python, i never use it,

sick birch
slate swan
#

thnx

#

i replaced line 4 of my code with this, intents = discord.Intents(messages=True) but not sure how to add client to this because the rest of my code uses client

sick birch
#

What do you have currently?

slate swan
#

because client is not defined now

#

ill screen shot it

sick birch
#

Text, please

slate swan
#

sure

#

it jsut says name "client" is not defined

#

because i replaced the client bit with intents = discord.Intents(messages=True)

sick birch
#

Can you show us the entire code you have at the moment?

slate swan
#

sure

#

import discord
import os

intents = discord.Intents(messages=True)

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

@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$hello"):
await message.channel.send("Hello")

client.run(os.getenv("TOKEN"))

sick birch
#

Yeah it doesn't look like you have a client

#

You need to define your intents alongside your client, and then pass in your intents to the client

slate swan
#

yeah it isnt defined anywhere

sick birch
#
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(..., intents=intents)

is how people usually do it

slate swan
#

okay thnx, btw what should i put in place of the elipse

#

or is that mean to stay like that

sick birch
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
sick birch
#

The arguments that go here

#

So whatever you want really

slate swan
#

oh right thnx

slate swan
sick birch
#

I can try

slate swan
sick birch
#

Doesn't seem like you have the console module installed

#

Try python -m pip install console

slate swan
#

still dont work

sick birch
#

Does your python project use a virtual environment?

sick birch
slate swan
#

i dont know im new to this i made it into a exe file now it does this

sick birch
#

Made what into an exe file? And how?

slate swan
sick birch
#

Ah that would explain it

slate swan
#

i did pip install pyinstaller

sick birch
#

Yeah pyinstaller/py2exe will usually do that. We don't recommend using it

slate swan
#

then pyinstaller --onefile -w main.py

sick birch
#

Probably just an issue with pyinstaller. Don't know if it's fixable

#

Why not just leave it as a .py file?

slate swan
sick birch
slate swan
sick birch
#

You can't

#

Unless you put your application server-side and only have a frontend user interface. Even then it's possible

sick birch
slate swan
#

obfuscate?

sick birch
#

Nope

reef trail
sick birch
#

It's only a matter of time and determination

reef trail
#

thats why you use actual good obfuscating methods

sick birch
#

Doesn't matter. Still reversible.
Better yet, make your software open source! Distribute the Python file

reef trail
#

theres pros and cons to open source

sick birch
#

Only when you're making something malicious

#

Or you're a corporate company

reef trail
#

no need to say the same thing twice HAHA

slate swan
#

i don't see the point of encrypting a single python file Kannakillyourself

pliant gulch
# sick birch Or you're a corporate company

I wouldn't even bother, slap a license on it and it's done. Bc other companies need to follow the laws as well as you, so add a copyright, etc. If they steal it, sue for damages

sick birch
slate swan
#

what if the world collapsspichu_v20 , there's no end to what ifs

night crater
#

Unless your Adobe, people are not going to care about your random python app and steal it

edgy thorn
#

question

#

how do you get a discord bot to just simply send a message to a specific channel without waiting on any sort of discord event

slate swan
#

with commands you can define a channel and make it send to there

#

on phone so can't send code soz

edgy thorn
#

basically just on command

#

just a one way message to discord

sick birch
#

Should be easy to just do it inside the command then

#
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
  ... # do whatever

  channel = bot.get_channel(123) # your ID here
  await channel.send("Hello, world!")
edgy thorn
#

ok I'll give that a try ty!

tranquil badge
#
    @commands.hybrid_command(name='img', description='High quality images of the ships.')
    async def img(self, ctx: commands.Context, ship: str):
        rank_list = [i[0] for i in sql_rank_obj()]
        res = [i for i in rank_list if i.lower() in ship.lower()]
        s_obj = sql_ship_obj()
        if len(res) == 0:
            s_obj = ShipData(ship).s_obj
            ship_embed_title = f"{customemoji(ctx, s_obj['rarity'])} {s_obj['name']}"
            col = int(s_obj['colour'], 16)
            embed = discord.Embed(
                title=ship_embed_title,
                colour=col)
         embed.set_image(url=get_ship_image(s_obj['number']))
            await ctx.send(embed=embed)
#

"TypeError: list indices must be integers or slices, not str"

#

pretty much anything that is s_obj['blah']

#

gives me that type error

#

It works with my currently running bot but the hybrid command conversion seems to have broken it

sick birch
tranquil badge
#

yea

sick birch
#

So you'll have to access it by index

#

E.g s_obj[0] to get the first item

tranquil badge
#

let me check through my sql queries

#

so would i add the [0] to every instance basically?

#

oh adding it worked

#

but

#

it returned everything for the first item in the list

tranquil badge
#

@sick birch how would i go about doing s_obj[<row of item>]? Like grab the row it came from

sick birch
#

Just like that

#

s_obj[0] would get everything in the first row

#

s_obj[1] would get everything in the second row

#

etc

tranquil badge
#

i need it to be a variable essentially

#

the input of the user determines what row

sick birch
tranquil badge
#

yea

#

just unsure how to define

sick birch
sick thicket
hushed galleon
unkempt canyonBOT
#

examples/app_commands/slash_groups.py lines 17 to 20

@math.command()  # Create a slash command under the math group
async def add(ctx: discord.ApplicationContext, num1: int, num2: int):
    """Get the sum of 2 integers."""
    await ctx.respond(f"The sum of these numbers is **{num1+num2}**")```
sick thicket
#

ah

hushed galleon
#

it also appears from their source code that all the same slash command parameters, including description, should be supported

#

but its quite concerning that their documentation completely omits the SlashCommandGroup.command() decorator

sick birch
#

Well Pycord isn't really known for being good at anything really

slate swan
#

@sick birch best way to check for a certain permission without doing it with a decorator?

sick birch
#

Why not decorator?

slate swan
#

It's kinda a long explanation

#

there surely has to be a way no?

torn sail
slate swan
trim shadow
#

hello, how can has param like that?

torn sail
slate swan
#

and just pass a member object

slate swan
#

@sick birch How can I implement a guild set prefix thing?

sick birch
unkempt canyonBOT
#

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

Retrieves the prefix the bot is listening to with the message as a context.

Changed in version 2.0: `message` parameter is now positional-only.
sick birch
#

As this is run on every message I would recommend you use some sort of caching system

slate swan
#

what if I want something like prefix, but just some type of bool statement per guild?

sick birch
slate swan
sick birch
#

You'd just create a check for that

#

return True/False depending on if that command should be run

slate swan
#

it could be different for each guild though

sick birch
slate swan
#

tbh

#

im too lazy to do it ima just say its whatever

orchid ledge
#

how do I add choices to slash pycord? pepethink cant find anything and tried different ways

orchid ledge
#

example :
I do /hello then I get like a field I need to click on then I type in it

shrewd apex
#

just add a parameter typehint it str

fierce light
#

anyone know how to change the default help command for discord.py interactions??

loud junco
#

wdym i dont quite understand

naive briar
#

You return value before closing the connection

#

🤷

loud junco
#

i need to return after closing it?

naive briar
#

The rest of the function wouldn't be executed after you returned a value. So, in your case, the connection wouldn't be closed

loud junco
#

so return after close right?

naive briar
#

Eh, yeah

loud junco
shrewd apex
#

just var[0] is enough

naive briar
#

You should consider keeping the connection in your bot instance so you don't have to keep connecting to it every time you need to do something with the database. Like Asher said

shrewd apex
#

imagine connecting to db and closing everytime so inefficient 💀

loud junco
#

add bot= blahblah on top?

shrewd apex
#

bruh literally just do in setup_hook bot.db = connect()

#

and u can use bot.db anywhere now

loud junco
# shrewd apex and u can use bot.db anywhere now
import asyncpg
import discord
from discord.ext import commands

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

@bot.event
async def setup_hook() -> None:
    # this override's Bot.setup_hook and is triggered before the bot starts.

    # creating a database pool
    bot.db_pool: asyncpg.Pool = await asyncpg.create_pool("PGSQL SERVER URL HERE.")

    # example to making a query to the database anywhere in your code ->
    async with bot.db_pool.acquire() as connection:
        await connection.execute(
            """SQL QUERY HERE"""
        )
        # creating a connection cursor if needed
        async with connection.cursor() as cursor:
            await cursor.fetch("FETCH QUERY...")
```this thing?
shrewd apex
#

yeah but aquire thingy is not needed

loud junco
#
@bot.event
async def setup_hook() -> None:
    bot.db_pool: asyncpg.Pool = await asyncpg.create_pool("PGSQL SERVER URL HERE.")
```this is fine?
shrewd apex
#

yeah

loud junco
#

how do i use it tho

shrewd apex
#

u can use bot.db_pool everywhere

#

in cogs it will be self.bot.db_pool

loud junco
cloud dawn
#

Create a connection pool.

Can be used either with an async with block:

async with asyncpg.create_pool(user='postgres',
                               command_timeout=60) as pool:
    await pool.fetch('SELECT 1')

Or to perform multiple operations on a single connection:

async with asyncpg.create_pool(user='postgres',
                               command_timeout=60) as pool:
    async with pool.acquire() as con:
        await con.execute('''
           CREATE TABLE names (
              id serial PRIMARY KEY,
              name VARCHAR (255) NOT NULL)
        ''')
        await con.fetch('SELECT 1')

Or directly with await (not recommended):

pool = await asyncpg.create_pool(user='postgres', command_timeout=60)
con = await pool.acquire()
try:
    await con.fetch('SELECT 1')
finally:
    await pool.release(con)
loud junco
#

they say its not efficient

cloud dawn
#

Who's saying that?

#
Connection pool can be used to manage a set of connections to the database. Connections are first acquired from the pool, then used, and then released back to the pool. Once a connection is released, it’s reset to close all open cursors and other resources except prepared statements.
shrewd apex
#

better to make a persistent pool and use that throughout the bot

cloud dawn
shrewd apex
#
async def setup_hook():
    bot.db = await asyncpg.create_pool()

async def foo(bot):
    await bot.db.fetch()
loud junco
#

so what should i follow 💀

shrewd apex
#

i dont see a problem with using a async context manager but i would go with the second one

loud junco
#

i just put query in the () of await bot.db.fetch()?

shrewd apex
#

yeah

cloud dawn
shrewd apex
cloud dawn
#

If you make a pool which in this Discord bots case you should, should still be acquired and release the connection back to the pool.

shrewd apex
#

the context manager is just a fall back safety measure to automatically code the cursor/connection

shrewd apex
cloud dawn
#

Well I strongly disagree how you handle that connection. Postgre is amazing but you should handle it properly.

loud junco
#

i dont think its bot.db cuz db is not defined

naive briar
#

You didn't define it 🤷

placid skiff
#

lmao why do people keep defing the db connection in their bot instance

cloud dawn
shrewd apex
#

only valid argument i found till now yet

shrewd apex
loud junco
loud junco
fierce light
upbeat gust
loud junco
#

how do i fix this

slate swan
#

Why are you linking discord py to your db 😭

loud junco
upbeat gust
loud junco
#

wait its bot.db_pool 💀

shrewd apex
loud junco
#

oo

#

keep forgetting that var is a list ;-;

loud junco
shrewd apex
#

can u show me the db and whats arg here?

loud junco
shrewd apex
#

hmm

loud junco
#

:/

#

i have no idea what is happening

#

this is the channel id 1038754543682469936

shrewd apex
#

and can u actually just do dict(var[0]) for me once

shrewd apex
loud junco
#

await ctx.send(dict(var[0]))?

shrewd apex
#

yeah

loud junco
shrewd apex
#

can u hardcode it once and check first time i am encountering such a situation as well

shrewd apex
#

just use this SELECT * FROM match WHERE matchid = 'channelid'

loud junco
#

but its integer

#

it will become string 💀

shrewd apex
#

yeah the ' was only for demo

loud junco
#

ik

shrewd apex
#

u put it without '

loud junco
#

this is what i did

#

it will be integer?

shrewd apex
#

replace $1 with *

#

arg is not needed

#

i think that $1 is causing the problems

loud junco
shrewd apex
#

also just print var

#

dont do ctx.send just for debugging

loud junco
loud junco
#

lemme print var

shrewd apex
#

yep $1 is the problem

#

u cant use place holder there

loud junco
#

lmao

#

then how 💀

shrewd apex
#

now u can either hardcode this or
(f"SELECT {arg} FROM match WHERE matchid = $1", id)
but idk how valid/robust this is or if its allowed in general

#

u can test it ig

shrewd apex
loud junco
#

its outputting the whole continent 💀

#

larger than russia

#

oo because im using SELECT *

loud junco
shrewd apex
#

bro y str

#

(f"SELECT {arg} FROM match WHERE matchid = $1", ctx.channel.id)

#

@loud junco

#

also even if u are doing str y like that 💀put it in the {}

placid skiff
#

don't use f strings for queries

loud junco
shrewd apex
#

ik

loud junco
loud junco
placid skiff
#

wdym?

loud junco
#

but i cant use f-strings

placid skiff
#

db query take a tuple as parameter

db.execute("SELECT var1 from table1 where key=?", (value))
vale wing
#

Not the tuple

shrewd apex
#

code and words don't match pithink

vale wing
#

*args is argument list, you don't parse arguments to it as tuple but it is a tuple after parsed

shrewd apex
#

ik i was talking about (value)

vale wing
#

Ah yes

shrewd apex
#

bruh don't just copy paste

#

in asyncpg its $ for placeholder so $1

#

@loud junco

loud junco
shrewd apex
#

duh

loud junco
shrewd apex
shrewd apex
#

u can do var[0]["matchstarted"] as it is

loud junco
loud junco
loud junco
loud junco
#

$1 $2 $3?

orchid ledge
#

anyone has an example to a command with options like that:
/hello [123] [456] ...
and the Bot responds (sends) an embed like that:

Hello!
.... : [123]
.... : [456]

orchid ledge
#

its just an example

slate swan
#

A little more details will help

orchid ledge
#

for choice / option and im bad in explaining in chat

slate swan
#

Ok like

orchid ledge
#

where are u from? pepethink

slate swan
#

When you do /hello there some option will pop bup with 123 456

slate swan
orchid ledge
#

no where u can type in whatever u want

slate swan
#

Oh yeah

#

Do u know how to create slash command?

#

If no i can help from start

orchid ledge
slate swan
#

As example:

@bot.tree.command(name="hello")
async def hi(interaction: discord.Interaction, msg: str):
  embed=discord.Embed(title="Hey", description={msg})
  await interaction.response.send_message(embed=embed)
#

@orchid ledge

shrewd apex
#

just create an extra Param other than interaction type hint it str

#

yep like that

slate swan
#

Ye forgot about that

#

Typing on mobile just hard

#

Ngl

shrewd apex
#

mhm

orchid ledge
slate swan
slate swan
#

bot.slash_command

#

you're running main.py from a path that doesn't point to it directly

slate swan
slate swan
#

Hmmm weird

slate swan
#

O I didn't know he did that

#

which causes change in package levels

#

yooo i know what did i do wrong

slate swan
#

Thank you for help guys

#

Is this your bot?

#

Damm verified congrats

#

Hmm personally I don't use sql so can't help sorry

#

Im a mongo db user 💪

placid skiff
#

print result in the console and let's see if it has some values

#

also you should not use f-strings for queries

#

They're not safe, db methods takes a tuple for variable values:

db.execute("SELECT var1 FROM table1 WHERE key1=? AND key2=?", (value1, value2))
coral mirage
#

can some one help me please?

#

I'm trying to add help command to my menu command. This is a select option so when ever a user clicks help the help command response. How it's possible?

coral mirage
#

sure

slate swan
#

Ye, also using class it's way more easy

coral mirage
placid skiff
#

probably you're returning an embed but you're not sending it in the send method

coral mirage
#

give me a momemt

placid skiff
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
placid skiff
#

embed is a keyword parameter

#

you're passing content in your send method

coral mirage
coral mirage
slate swan
coral mirage
#

lol I'm new

#

This is my first project in python

slate swan
#

Can you tell what actually you want it to do?

coral mirage
#

I didn't use classes cause I'm still learning.

coral mirage
slate swan
#

Oh ok

#

there is one more params in select option is value

#

U can set the value as 1, 2, 3

#

Is it possible to add animated emoji's in a message my bot sends via a link>?

slate swan
coral mirage
gloomy cloak
#

if pinging me annoys you i can leave the server?

slate swan
#

it will be select.values

#

Giving you quick examples

coral mirage
#

all daaaayyyy 😢

slate swan
#
discord.SelectOption(label="Miscs",
                           value="4",
                           description="Shows some fun or useful command :)"),
      discord.SelectOption(label="End Interaction",
                           value="5",
                           description="Ends the interaction between user.")
    ])
  async def slct3(self, interaction: discord.Interaction, select):

    if select.values[0] == "1":
       #send different embed
#

@coral mirage

coral mirage
#

This is what I want to pop up when user click help. To jump to another command.

coral mirage
slate swan
#

U r welcome :]
It may look different as because i used classes but works the same

shrewd apex
#

oh @slash

maiden fable
#

lol

gloomy cloak
#

yeah

#

i don't mind it but i get it can be annoying for some people

#

and \ doesn't even prevent the ping lol

slate swan
#

@\Slash

#

welp the mentions can be ghosted when using a bot but not a normal client

slate swan
#

Xd sorry tho

#

@gloomy cloak

gloomy cloak
#

@Spooky.exe

slate swan
#

O nvm

gloomy cloak
#

@Spooky.exe#0001

#

weird

slate swan
#

Yep

gloomy cloak
placid skiff
maiden fable
#

hi

jolly rapids
#

Can someone tell me how to send an embed with d.py? I tried .send(embed=embed) which results in discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

maiden fable
#

show the embed variable

jolly rapids
#

i also saw on stackoverflow that it was changed to .send({embeds: [embed]}) but that results in NameError: name 'embeds' is not defined

jolly rapids
# maiden fable show the embed variable

wdym?
this?

        title: @blu#3821: Lorem ipsum dolor sit amet, consectetur adipiscing
        description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis purus convallis, blandit lectus a, commodo augue. In pharetra eros ut metus hendrerit, ac maximus ante eleifend. Proin fermentum sit amet enim eu lobortis. Sed ultrices lobortis sapien, in cursus ex pellentesque ut. Sed molestie at nunc sit amet pretium. Suspendisse a nulla lobortis, semper est quis, aliquam dolor. Nam vitae pretium orci, quis volutpat mauris. Suspendisse non posuere elit. Suspendisse aliquet neque ut turpis scelerisque tincidunt in vitae diam. Integer ut erat faucibus, cursus purus eu, vehicula ex. Nam nec lacus placerat diam condimentum consectetur. Integer in molestie nunc. Morbi facilisis lorem eu urna rutrum scelerisque. Suspendisse potenti. Pellentesque finibus magna aliquam ipsum mattis venenatis. Donec sit amet mollis orci, id porta leo.
        color: #007bff
        url: https://discordapp.com/channels/845364558805336104/1045011044470358066/1045016395898966056
        timestamp: 2022-11-23 16:42:04.248000
        author: EmbedProxy(name='blu#3821')
        footer: EmbedProxy(text='Discord #test')
jolly rapids
naive briar
#

Stackoverflow isn't always the answer

jolly rapids
jolly rapids
maiden fable
#

You can simply do

embed = discord.Embed(title=..., description=...)
await ctx.send(embed=embed)
#

And yea, please don't search stack for dpy questions
Most of them are old since v2 was released only a few months back

slate swan
maiden fable
#

calm down sarth

jolly rapids
#

does the message need to have content besides the embed?

maiden fable
#

nah

slate swan
#

not really

jolly rapids
#

hmmm. then idk what it complains about

#

because when i send the embed alongside a "." i get the dot in discord but no embed

maiden fable
#

What is the module version?

jolly rapids
jolly rapids
maiden fable
#

hm

lime lance
#

hi one question in discord.py
how can i convert this to an a leaderboard
{1032230667897024622: 1, 615253982721343488: 2}

maiden fable
#

Can you paste the code here please? @jolly rapids

jolly rapids
# maiden fable hm

which fields does an embed need to be sent? maybe it's complaining because i didn't add any field

#
    async def send_news(self,item:NewsEntry):
        embed=discord.Embed(title=item.title or ".", description=item.content or ".", color=0x007bff, url=item.url or ".", timestamp=item.timestamp)
        # embed.add_field(name="Fiel1", value=item.url, inline=False)
        embed.set_author(name=item.author or ".")
        embed.set_footer(text=item.source or ".")
        print("title:",embed.title)
        print("description:",embed.description)
        print("color:",embed.color)
        print("url:",embed.url)
        print("timestamp:",embed.timestamp)
        print("author:",embed.author)
        print("footer:",embed.footer)
        """
        title: @blu#3821: Lorem ipsum dolor sit amet, consectetur adipiscing
        description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis purus convallis, blandit lectus a, commodo augue. In pharetra eros ut metus hendrerit, ac maximus ante eleifend. Proin fermentum sit amet enim eu lobortis. Sed ultrices lobortis sapien, in cursus ex pellentesque ut. Sed molestie at nunc sit amet pretium. Suspendisse a nulla lobortis, semper est quis, aliquam dolor. Nam vitae pretium orci, quis volutpat mauris. Suspendisse non posuere elit. Suspendisse aliquet neque ut turpis scelerisque tincidunt in vitae diam. Integer ut erat faucibus, cursus purus eu, vehicula ex. Nam nec lacus placerat diam condimentum consectetur. Integer in molestie nunc. Morbi facilisis lorem eu urna rutrum scelerisque. Suspendisse potenti. Pellentesque finibus magna aliquam ipsum mattis venenatis. Donec sit amet mollis orci, id porta leo.
        color: #007bff
        url: https://discordapp.com/channels/845364558805336104/1045011044470358066/1045016395898966056
        timestamp: 2022-11-23 16:42:04.248000
        author: EmbedProxy(name='blu#3821')
        footer: EmbedProxy(text='Discord #test')
        """
        self.log(embed)
        await self.get_channel(self.targets[0]).send(embed=embed)
maiden fable
#

Fields are optional.

jolly rapids
#

then idk anymore

maiden fable
#

Can you print item?

jolly rapids
#

sure 1 sec

#

well, not really ```
[Discord] '==='
[Discord] <db.struct.news.NewsEntry object at 0x7f9432f910>
[Discord] '==='

maiden fable
#

hm

#

hella weird

slate swan
unkempt canyonBOT
#

sorted(iterable, /, *, key=None, reverse=False)```
Return a new sorted list from the items in *iterable*.

Has two optional arguments which must be specified as keyword arguments.

*key* specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). The default value is `None` (compare the elements directly).

*reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed.

Use [`functools.cmp_to_key()`](https://docs.python.org/3/library/functools.html#functools.cmp_to_key "functools.cmp_to_key") to convert an old-style *cmp* function to a *key* function.
jolly rapids
#

even pprint only prints the definition

naive briar
#

What error did you get exactly

maiden fable
#

okay so weird request but can ya try commenting out the self.log line?

jolly rapids
#

sure

slate swan
#

any chance that you are selfbotting? asking cuz embeds are not sendable by normal users

#

but discord.py doesnt allow that anymore so that should not be the case

jolly rapids
slate swan
#

ah alright, that might have been the issue if you were

maiden fable
#

Wait BTW @jolly rapids is this a class method?

shrewd apex
maiden fable
#

that's what I also wanted to ask
that's why asking if its a class method

#

Also, r u subclassing commands.Bot or smth?

shrewd apex
#

and whats self.log ? post the whole error if u can please

shadow vigil
#

i saw someone made a discord bot in a server but it's a user account that's breaking the tos right?

maiden fable
#

mhm

slate swan
#

those method look valid there, atleast as per vscode theme syntax highlighting
missing attributes are highlighted white instead of yellow

slate swan
maiden fable
slate swan
#

yeah

shadow vigil
#

the admins in the server are not doing anything even tho they know its a bot

slate swan
#

skill issue

maiden fable
#

-> Leave the server
-> Report the server
-> Sit back and enjoy

maiden fable
#

or should I say, report the specific user and the server (for not taking actions)

#

Totally not a devil thought

slate swan
#

i'd rather spam their bot and make it ratelimited

#

only if it interacts ofc

maiden fable
#

Lmao

#

I remember a person getting banned in dpy server for self botting cz he forgot to make it so that only he can run the commands.
Some helper ran !help and his ID sent the help embed 🤣

shrewd apex
#

imagine reaction of the guy who sent !help

slate swan
#

how much of a boomer do you have to be to use ! prefix for yourself

maiden fable
#

I suspect if he was online at that time
Lmao he prolly left the PC on/user a VPS and came back only to find a server missing and a DM from R. Danny

slate swan
#

can anyone help me with how sharding works ?

maiden fable
#

Tbh you can simply think of it as a commands.Bot alternative for big bots. No need to handle the underlying IPC since dpy does that for u

slate swan
#
@client.event
async def on_member_join(member):
    channel = discord.utils.get(member.guild.channels, name="👋┇welcome-wagon")
    await channel.send(
        f"{member.mention} has arrived! \nWelcome to Supernova! \n<https://cdn.discordapp.com/emojis/1021425058054410280.gif?size=44&quality=lossless> Check [#888401895973089280](/guild/267624335836053506/channel/888401895973089280/) \nNavigate the server  [#1021842239749619732](/guild/267624335836053506/channel/1021842239749619732/) \nJoin our games [#888403619119001651](/guild/267624335836053506/channel/888403619119001651/) \nGrab ping roles [#1021908586852515971](/guild/267624335836053506/channel/1021908586852515971/) "
    )
maiden fable
#

Lemme guess
The event doesn't get triggered

slate swan
#

i hate discord.utils.get UCrempout

maiden fable
#

Bad typings 😭

slate swan
#

and i might not even need it

maiden fable
slate swan
#

cos basically i want 2 scripts to run a single bot

#

on different pc's
then i need to do like
/command [specific pc running the program]

maiden fable
#

Ah

slate swan
#

but it only works on the person who most recently ran the script

maiden fable
#

Well you gotta implement that logic yourself
AutoShardedBot is different from your usecase, yes

slate swan
maiden fable
#

Nah

hollow bridge
slate swan
#

i mean idk what this is abt then

maiden fable
slate swan
#

Does it have an efffect?

hollow bridge
maiden fable
slate swan
#

the code is exactly the same

slate swan
maiden fable
slate swan
#

like to show stats and stuff

#

i've been identifying each user like this tho which could be it ?

maiden fable
#

Hm
Well you can kinda do that, but you won't have control as to which bot will receive the command and which will not

#

You can either add a command arg to show the stats of friend1's pc and use if statements to control the response but I don't see any other way for this

slate swan
#

make a webserver and make your friends run a websocket client instead of the bot
when asked for stats that client can send the stats to the server

maiden fable
#

so like discord-ext-ipc right?

slate swan
#

i dont wanna flood the channel

#

kind of

slate swan
#
class BOT(commands.InteractionBot):
    def __init__(self, **options):
        super().__init__(**options)
        self.ip_addr = IP()
        self.identifier = os.getenv("username") 

bot = BOT(status=disnake.Status.do_not_disturb, activity=disnake.Activity(type=disnake.ActivityType.watching, name=""))

@bot.slash_command()
async def listusers(ctx):
    await ctx.channel.send( 
        embed=disnake.Embed(title=f"The identifier for {os.getenv('username')}:", description=bot.identifier) 
    )
    await ctx.response.send_message("Checked all available users:\n_ _")```#
maiden fable
#

hm

slate swan
#

and to execute commands u need the arg of the user

maiden fable
#

mhm

#

so uhhh what seems to be the issue then?

#

If you got the whole code written

slate swan
#

well the same as before

#

it only runs if you specify the id of the script that last ran it

#
@bot.slash_command(description="Gets the system information.")
async def sysinfo(ctx, user):
    if user == bot.identifier:

        cpu, ram, disk, ramusage, gputemp= getsysinfo()
        #embed
        embed = disnake.Embed(title="System Information", description="user's system information", color=0x00ff00)
        embed.add_field(name="CPU", value=cpu, inline=True)
        embed.add_field(name="RAM", value=ram, inline=True)
        embed.add_field(name="Disk", value=disk, inline=True)
        embed.add_field(name="RAM Usage", value=ramusage, inline=True)
        embed.add_field(name="GPU Temperature", value=gputemp, inline=True)
        await ctx.send(embed=embed, ephemeral=True)
    else:
        await ctx.send("user not found.", ephemeral=True)```
#

this is an example command

maiden fable
#

Mhm

slate swan
#

but say me and my friend both run it, and my friend was the latest person to run it, it only registers if i do his identifier

#

and if i do mine it says user not found

maiden fable
#

That's.... weird

#

can u print what is bot.identifier?

slate swan
#

the pc name

slate swan
maiden fable
#

Hm

#

Tell me something.......

#

Why are you using kinda complex logic?
Why not just check in each command invocation if user is the same as the PC's name and if it is, then send else do nothing

slate swan
maiden fable
#

you are specifying the user arg

slate swan
#

yea

maiden fable
#

Why not do something like

if user == getenv("username"):
    # send the message
slate swan
#

oh lol

#

cos if i want to look at my friends stats

maiden fable
#

and don't add that else clause because in case one bot falls back to the else clause but the other doesn't (the if statement is true), then it will send a double response

#

Are you running the other instance on yr friend's machine?

slate swan
#

yea

#

like imagine this

maiden fable
#

I understand ya now

slate swan
#

me and my friend are running the program and i wanna check his stats

#

i'll need to specify his pc instead of mine

maiden fable
#

If u r invoking the command with the user being the same as his PC's name, then u should use the if statement I sent above.

#

Basically move the if statement from the bot's init to the command (the condition, not the identifier thingy)

slate swan
#

but then that would break this command

maiden fable
#

Which one?

maiden fable
#

Well if that is your concern then don't move the if statement from the init but implement the if logic for the sysinfo command

slate swan
#

but would that fix the problem of the bot only listening for the most recent user ?

maiden fable
#

It should

#

You can ping me in case you need implementing this thing

slate swan
#

i mean could u try ?

maiden fable
#

What?

slate swan
#

my fix aint working

maiden fable
#

Hm lemme get the code

#
@bot.slash_command(description="Gets the system information.")
async def sysinfo(ctx, user):
    if user == os.getenv("username"):

        cpu, ram, disk, ramusage, gputemp= getsysinfo()
        #embed
        embed = disnake.Embed(title="System Information", description="user's system information", color=0x00ff00)
        embed.add_field(name="CPU", value=cpu, inline=True)
        embed.add_field(name="RAM", value=ram, inline=True)
        embed.add_field(name="Disk", value=disk, inline=True)
        embed.add_field(name="RAM Usage", value=ramusage, inline=True)
        embed.add_field(name="GPU Temperature", value=gputemp, inline=True)
        await ctx.send(embed=embed, ephemeral=True)
#

Something as easy as this lol

slate swan
#

that doesnt work

#

tried that

maiden fable
#

What in the

slate swan
#

its to do w discorrd

#

and running the bot

maiden fable
#

How r u invoking the command?

slate swan
#

i think

maiden fable
#

?

slate swan
maiden fable
#

No like what are the arguments u r passing

slate swan
#

async def sysinfo(ctx, user):

#

this ?

maiden fable
#

No no

#

like /sysinfo <what-here>

slate swan
#

oh

#

/sysinfo [bot.identifier]

maiden fable
#

what? Are you literally typing [bot.identifier]?

slate swan
#

no lol

#

but like the pc users name

#

like if my windows pc account was called 'slikc'

#

i'd do /sysinfo slikc

maiden fable
#

and is the value the same as what is returned by getenv("username")?

slate swan
#

yea

maiden fable
#

That's hella weird. Should have worked

#

Tbh the only thing left is using a websocket

#

Create a websocket and use that to request data based on the username. You will have to run the bot only on one pc and run a websocket on another

slate swan
#

oh

#

i mean i guess that would work

maiden fable
#

I don't see any other way out of something like this

slate swan
#

but like i'm certain there must be a way to use it using discord.py itself

maiden fable
#

Nope, the library doesn't provide anything like this

slate swan
#

like theres no way theres 0 workaround for 2 people running one bot ?

maiden fable
#

No

slate swan
#

usually there is for that kinda thing

maiden fable
#

The closest was AutoShardedBot but that doesn't reallu suit your use case, does it?

slate swan
#

i mean how does sharding fully work

#

i dont quite understand it

maiden fable
#

Well we can try replacing commands.Bot with commands.AutoShardedBot and see if it fixes the issue

#

So how sharding works is:
Suppose your bot is too big... then the bot is split across various systems/machines that is you can run the same codebase on various machines and the bot will work like normal

slate swan
#

oh

#

isnt that like exactly what i need

maiden fable
#

But that won't work for one server bots

slate swan
#

oh

#

why not ?

maiden fable
#

It works for bots in 1000 or smth more servers

#

Because dpy creates "groups" of servers
Like, the events by Group 1 will be received by Shard1, the events from Group 2 will be received by Shard2 and so on

slate swan
#

oh

maiden fable
#

This is also one of the reasons why some big bots like Dyno are sometimes shown offline in some servers but online in others

silent portal
#

When I pass in datetimes in a loop.task, does it run 1x on that datetime?

fading marlin
#

yes

slate swan
#

okay i might have fixed it @maiden fable

#

but i'm now getting a different error

maiden fable
#

Hm?

slate swan
#

when the bot takes more than 3 seconds to execute the command, it doesn't reply

maiden fable
#

Yup that is a slash command issue

slate swan
#

and gives this error disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: InteractionTimedOut: Interaction took more than 3 seconds to be responded to. Please defer it using "interaction.response.defer" on the start of your command. Later you may send a response by editing the deferred message using "interaction.edit_original_response" Note: This might also be caused by a misconfiguration in the components make sure you do not respond twice in case this is a component.

slate swan
maiden fable
#

use interaction.response.defer() and then edit using interaction.edit_original_response(...) or send using interaction.followup.send(...)

slate swan
#

oh okay

dry kelp
brittle ocean
#
@bot.event
async def on_message(self, message=str):
    # if message.author == self.user:
    #     return
    # else:
    bannedmsgs = None
    bannedmsgs = (bad_words.values() for x in bad_words.values())

    await print("you said a bad word")


asyncio.run(on_message(self=database_functions.user_id, message="test"))

with bad_words being:

bad_words = {
  "verybad": ["test", "test2"]
}

which outputs:

TypeError; Object NoneType can't be used in 'await' expression

please help? I dunno what i did wrong

#

it does print "you said a bad word" though

sick birch
# dry kelp

Either your hardware doesn't support virtualization or it needs to be enabled in BIOS like the error says

sick birch
#

You don't await print statements

brittle ocean
#

oh ok thx

slate swan
#

how do i make buttons not spammable

#

is it self.stop in my class?

#

@sick birch

sick birch
slate swan
#

[2022-11-23 16:07:43] [INFO ] discord.gateway: Shard ID None sessio n has been invalidated.

#

started getting this message after upgrading my discord.py version

#

anyone know how to fix?

merry sail
coral mirage
slate swan
sick birch
#

No you'll have to use interaction_check for that

slate swan
#

How so

sick birch
#

And some sort of way to store state on who's clicked and who hasn't

dry kelp
#

I made everything run with 1 command. Bot, web, db

sick birch
#

Yeah that's pretty common, we do it with most of our bots

dry kelp
#

which is really nice. No need to create the virtual env manually it will do that

#

and also migrating the db is automatically

sick birch
#

yup

dry kelp
#

so i truly prefer docker than pm2

#

Beside this i got 1 question

#

for some reasons when i run the bot web api on the vps if it's not me running it that will return a internal server error

#

so i suppose something has to do with localhost

#

@sick birch

sick birch
dry kelp
#

1 sec

#

i left it turned on lol

#

Yeh but if i run it it will work

#

oh nvm it erroed me

#

If i give u the OAuth2 link could u test it? I think it's because there's already a value inside of the db and it will just override

#
@app.get("/api/v1/auth")
async def auth(code: str):
    global AUTH_REQUESTS
    AUTH_REQUESTS += 1

    async with await exchange_code(code) as oauth_response:
        if oauth_response.status != 200:
            logger.error(f"A Error has happend: {await oauth_response.text()}")
            raise HTTPException(status_code=400, detail="Bad request")

        json = await oauth_response.json()
        me = await fetch_me(json["access_token"])
        userResponseJson = await me.json()

        oauthUser = OAuth2User(
            id=int(userResponseJson["user"]["id"]),
            token=json["access_token"],
            expires_in=json["expires_in"],
        )
        await oauthUser.update_or_create()
        await oauthUser.save()
        return {"status": "OK", "user": userResponseJson["user"]}


register_tortoise(
    app, config=TORTOISE_ORM, generate_schemas=True, add_exception_handlers=True
)
#

multiple objs returned yes

sick birch
dry kelp
vivid gate
#

where can i ask something for normal python, not related to discord ?

vivid gate
#

ow

#

thank you

ionic garden
#

so what's the convention for dbs in discord bots
i'm thinking of having a global module w/ the db cursor and stuff
and have the cogs, etc. all interact w/ that module

ionic garden
#

ok cool

sick birch
#

Create a file with all of your database models and functions

pliant gulch
#

Not sure if I'm quite the fan of making it a global module

#

It should at the very least be bounded to the bot instance

#

Make sure it's concurrent as well

ionic garden
#

concurrent?

pliant gulch
pliant gulch
ionic garden
#

how would the cogs access it then?

pliant gulch
#

If it's bound to the bot it'll be available through the bot. And every cog instance is given the bot instance

#

So that would be un-effected

ionic garden
#

ok that's good

woven flint
#

i need help
this is my file structure: bot.py colors.py economy,py tools/ fun.py mod.py
in mod.py, i have the following line from ..colors import palette. i am making a discord bot so i actually kind of use this file by running bot.py but whenever i do, it gives me this error: ImportError: attempted relative import beyond top-level package

sick birch
#

Please don't crosspost

sick birch
#

You were told not to impersonate a self bot by a staff member.

simple niche
#

Sorry

sick birch
#

They were helped already - this is why we don't crosspost

shrewd apex
#

ah

severe mural
#

problem error

#

look code

#

for interaction.

slate swan
slate swan
slate swan
# severe mural problem error
  1. the command name you use in the code is suggestion (not suggest)
  2. stop implementing normal command logic in application commands ( in the except )
    interaction.response.send_message returns None, not a Message
maiden fable
#

Nice

vale wing
#

To get you quickstarted

async with aiohttp.ClientSession() as session:
    r = await session.get(url)
slate swan
#

you can't edit a interaction message.

#

you need to get the mssage from channel history manually and edit it

#

instead of message vars you can use await interaction.edit(...)

slate swan
#

!d nextcord.Interaction.edit is there an edit?

unkempt canyonBOT
#

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

This is a shorthand function for helping in editing messages in response to a component or modal submit interaction. If the interaction has not been responded to, [`InteractionResponse.edit_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.edit_message "nextcord.InteractionResponse.edit_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is edited via the [`Interaction.message`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.message "nextcord.Interaction.message") using [`Message.edit()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Message.edit "nextcord.Message.edit") instead.
slate swan
#

cool

slate swan
#

yeah nextcord added it :p

#

ye lol

#

i had to check the docs xd

slate swan
#

you can use await interaction.edit()

#

in line 420\

#

;]

supple thorn
#

the raspberry pi zero run a discord bot that doesn't have that much features or users using it right

supple thorn
slate swan
#

if raspberry pi supports python then you can add these stuffs easilt

#

easily*

coral mirage
#

anyone awake?

topaz pumice
#

yes

#

this is the internet

coral mirage
#

I'm back after 12 hour shift

coral mirage
topaz pumice
coral mirage
#

A lot?

#

Can you help me out?

topaz pumice
#

ok

coral mirage
topaz pumice
coral mirage
# topaz pumice ok

Great, If I want a user to create a profile in my bot. How I can add the coding? If user tries to create a nation again, how I can send a return that he already has a profile.

topaz pumice
coral mirage
#

How I can add in my both time and math like a economical way of math.

slate swan
coral mirage
topaz pumice
#

datetime.now?

coral mirage
#

Thanks

coral mirage
# topaz pumice datetime.now?

So, basically I want every hour to remove something from a user and/or add something from the user. Like money or points.

topaz pumice
#

make a time.sleep(1000*60*60) on a repeat loop

coral mirage
#

do I have to import anything for the economic and time?

topaz pumice
#

import time, datetime

coral mirage
#

I imported math is that useful?

#

besides time

topaz pumice
#

yes

coral mirage
#

Great! Thanks mate!

#

Happy Thanksgiving!

coral mirage
slate swan
#

Also did u fix the problem of your dropdown box?

coral mirage
coral mirage
# slate swan Cool

Yes, I love Game Development. I heard is one of the hardest career. Yet, I'm still down to explore this area. If it doesn't work. I'll stick with Data Analysis.

slate swan
#

Yep, game development is actually pretty hard

coral mirage
#

what's so bad of being creative and be enable to create whatever comes in your imagination?

coral mirage
slate swan
#

I am tooo bad at picking things

polar dawn
#

Is it possible to logs in a channel when a person in other server executes a command?

slate swan
polar dawn
slate swan
#

Also there is an event for it too.

coral mirage