#discord-bots

1 messages Β· Page 339 of 1

lyric solar
#

if i need to send a message do i really need to pass in parameters

shrewd apex
#

!e def foo(x): ...
foo()

unkempt canyonBOT
#

@shrewd apex :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     foo()
004 | TypeError: foo() missing 1 required positional argument: 'x'
lyric solar
#

oh i just realized "interaction" was unused

#

but im worrying bout self now

shrewd apex
lyric solar
shrewd apex
#

no the option index part

#

self.values

lyric solar
shrewd apex
#

yes

lyric solar
#

okay im confused on what to do now

#

i have self, and it is being used

shrewd apex
#

lmao u have no idea what ur code is doing

lyric solar
#

im so confused

shrewd apex
#

also idk why u need that # discriminators are not even a thing anymore

lyric solar
#

if i remove self, it will warn me that its not defined

shrewd apex
#

yes

lyric solar
#

so do i need to change this:

        option_index = int(self.values[0].split('#')[-1]) - 1
        selected_data = self.data[option_index]```
shrewd apex
#

well u need to access values whatever that is idk as for data u can just open the json file in the function

lyric solar
#

in ExpandDropdown
self.data is defined as "data"

#

@shrewd apex am i supposed to be able to call send_updated()

shrewd apex
#

which is the code ur using the Select or the above

#

Select one seems fine but u need to attach it to a view and send a message

lyric solar
#

i copy pasted the callback

shrewd apex
#

yeah no it doesn't work that way

lyric solar
#

im trying to

shrewd apex
#

u need to use it as it is

lyric solar
#

the send_updated() is supposed to make a message

shrewd apex
#

that won't work

lyric solar
lyric solar
#

how can i call this then to let the function know i want to send a message

shrewd apex
#

were just going round in circles u obviously don't know basic python anything i do needs to be spoonfed

lyric solar
#

i have a headache

#

ive spent 2 days at this project i dont wanna throw it in the bin

shrewd apex
#

if u just want to send a simple message remove all the parameters from send_updated and remove embed and then create a view instance and pass it to the send method also the view instance needs the data object which u loaded from the json file

lyric solar
#

i want to send a simple message with an embed attached to it

#
  • the select menu
slow knot
#

@shrewd apex

shrewd apex
#

like the eval command in python bot?

#

or do you mean like accessing the actual underlying terminal of the PC running the bot?

slow knot
#

theres something i can dowload

shrewd apex
#

well jishaku has one

slow knot
#

thats the name

shrewd apex
#

but restricted to owner only

slow knot
#

thanks

#

its called jsk also right

shrewd apex
#

as an alias yeah

slow knot
#

thanks

shrewd apex
#

np

slow knot
#

my bot wont respond to ping

#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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

if __name__ == '__main__':
    bot.load_extension('jishaku')

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def ping(ctx):
    await ctx.send('Pong!')
#

all intents are on

#

and i have bot.run also

#

@shrewd apex

shrewd apex
#

enable message_content intent

#

not dashboard in the code btw

#

u can do intents=discord.Intents.all()

slow knot
#

thanks

#

do i leave intents=intents?

shrewd apex
#

u can replace it there itself

#

instead of doing it in seperate lines

slow knot
#

oh right

somber sky
#

anyone got recommendations on what host to use for canada idk anything abt hosting

raven kite
#

Hey guys, i'm having problem with a cogs, that's the error:

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ctfstart' raised an error: ModuleNotFoundError: No module named 'discord_slash'        ```
(i've already installed the module)
final iron
#

discord_slash and whatever tutorial you're following are obsolete

raven kite
#

oh ok

somber sky
#

yo pep what host do u recommend

raven kite
vague matrix
somber sky
raven kite
vague matrix
somber sky
#

my bot is pretty big too over 3k lines of code so idk what is good for soemthing that big

vague matrix
#

3K Lines in your main file? What's the majority of code taking that up?

vague matrix
#

I can't give you a definite answer because it depends, I would seperate my files up more though if possible

raven kite
vague matrix
#

Show the code

raven kite
#

(i'm porting the code, from slash_commands to discord.app_command)

#

(ignore options)

vague matrix
#

Would you have to put it inside of a class

#

the AppCommand

raven kite
#

Only the name for using slash command

#

the documentation's so bad

#

it doesn't want the argument "name"

#

BUT:

vague matrix
#

I would figure out another way to call to the decorator

raven kite
#

I'm actualy watching: commands.command

dry kelp
feral timber
#

!rule money

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

dry kelp
# dry kelp

In this code, how could i delete the CREATED webhook only because this code will just delete all of the webhooks in the current channel, which makes sense, but how can i extract the right webhook?

high mesa
#

Does anyone know the fix for SSL certificate error in VS Code venv python on macos?

final iron
#

Unless somebody has some easier solution to offer

#

Hint: use the builtin sorted method to sort the created_at values

drifting arrow
#

is on_webhook_update really a thing?

final iron
#

on_webhooks_update, but yes

#

It might be one of discord.py's artificial events though

drifting arrow
#

Oh, it only returns a channel

#

I was hoping it'd return a message.

#

Can't you just do on_message event and listen for things like webhooks?

#

Coz I'm thinking, just log message ID's

#

it's a webhook, but still a message.

final iron
#

There's no guarantee the webhook will send a message though, or a message immediately after they are added

drifting arrow
#

I think I need to read more than a singular message lol

#

Anyway. I've yeeted my yeet into the wild. I'm sure someone can figure it out.

desert kiln
#

!paste

subtle jungle
#

did render get any updates to not be able to host discord bots with uptimerobot anymore?

final iron
#

Maybe?

#

You're using a workaround to host your bot, so I wouldn't be surprised if they patched it

#

A proper VPS is as low as $4 a month

subtle jungle
#

I mean given that they have a link to webpage generated by the bot, how would they technically patch it?

final iron
#

who knows

subtle jungle
#

Hmm alr

flat pier
drifting arrow
drifting arrow
#

Idk what the user is trying to do.

#

so i cant really offer my 2 terrible cents worth of thoughts

#

maybe 1 cent. it's low value right now

flat pier
#

webhooks are integrations (as far as i know considering discord calls it one) and you should be able to use on_integration_create to get an Integration object but i tried it and couldn't get the event to trigger when making a webhook for the server or a channel, so im not sure

somber sky
#

ive been watching this tutorial on how to host my bot using digital ocean, how come it says no such file or directory

grand bobcat
somber sky
flat pier
#

show you're entire traceback not a screenshot of one line

somber sky
#

thats literally all it says

#

python3: can't open file '/root/main.py': [Errno 2] No such file or directory

flat pier
#

that is not the same thing you screenshotted

somber sky
#

it is its just shortened

#

oh wait

dusk shadow
#

hey again yall...

ok, so im FINALLY getting back into coding again, and im trying to do a sort of simple-ish slash command to have a user provide 2 string values, and have the first value to remove certain characters,
value_one.replace(" ", "-").replace("'", "").replace(":", "-")
then i have it to basically replace all spaces as -
and after all that, it make the new value processed_value and is put in places in the final_value spot
final_value = f"{processed_value}.{value_two}"

so for example, if i do
/values [The Mug: My Coffee's Burning] [CAFFEINE]

it would reply with
The-Mug-My-Coffees-Burning.CAFFEINE

im fairly new to slash commands, but i do dabble a LITTLE in the old prefix commands.
if anyone can give pointers this late at night, please lemi know, thanks!

#
@client.tree.command()
@app_commands.describe(
    value_one='Gime a value',
    value_two='second value',
)
async def values(interaction: discord.Interaction, value_one: str, value_two: str):
    processed_value = title.replace(" ", "-").replace("'", "").replace(":", "-") # Replace any spaces, or other special characters 
    processed_value = re.sub(r'\-+', '-', processed_value)  # Replace multiple "-" with single "-"
    final_value = f"{processed_value}.{value_two}" # Value produced by processing
    await interaction.response.send_message(final_value)

What i have so far :/
if you wanna know why its a little messy, its cause im trying to convert this from prefixes (old commands) to new slash

dusk shadow
#

well, when using this exact command, i get an error with re.sub
... and since it was a prefix command last, the entire system kinda changes... :/

vocal snow
#

What's the error?

dusk shadow
#

one sec

#

discord.app_commands.errors.CommandInvokeError: Command 'values' raised an exception: NameError: name 're' is not defined

#

@vocal snow

vocal snow
#

you just forgot to import the module

#

import re

dusk shadow
#

oh, ffs

#

so my command works just fine

#

actually dead af...
so sorry to bother yall

naive briar
#

🫠

dusk shadow
#

brain actually dead.
look, ive been up for 20 hours, so brain at low function

drifting arrow
#

Without using client how do i get a guild by ID?

#

Currently I'm using guild = self.client.get_guild(int(profiles['server_profile'].server_id)) but I want to change it from this

#

is there an inbuilt way?

upbeat otter
drifting arrow
#

Trying to clean up my code and fix it up a bit and I want to change the way my cogs are loaded

upbeat otter
#

well there is no other way to get a guild by its ID

drifting arrow
#

so I have to pass my bot/client to the cog

upbeat otter
#

every cog requires that to be passed

#

whether you want it or not

drifting arrow
#

oh it gets passed regardless? neat

#

Thought I had to figure that out lol

upbeat otter
#

cool

dreamy dune
drifting arrow
#

All good. Figured out my nonsense

#

and life goes on :)

pale zenith
#

What does get passed bot is an extension's setup function

alpine cove
#

sqlite always confuses me with json stuff
doing some testing rn but cant seem to get this to work
so I've tried running these two queries but always get a sqlite3.OperationalError: malformed JSON

UPDATE tbl SET data = json_insert(data, ?, ?) WHERE id = ?; 

params = ('$.newkey', '{"test": "test"}', '1')

UPDATE tbl SET data = json_insert(data, ?, ?) WHERE id = ?;

params = ('$.newkey', '"newvalue"', '1')

golden portal
alpine cove
#

wrong channel lmao

#

sry thought I was in databases

dusk shadow
#

another question,
so, lets say i want to have my bot DM me if someone used a command.

        user = await client.fetch_user(929950499787145348)
        await user.send(f"At {datetime.now()} {ctx.author.id} made a value: "+final_value)

i get an error with ctx not defined, i feel like this is cause of the interaction system, instead of command based dections...
any work arounds?

#

the discord ID, being mine of course :>

somber sky
#

how come in vscode, when i commit the file to my github it doesnt even work?

shrewd apex
#

!d discord.Interaction.user

unkempt canyonBOT
shrewd apex
#

@dusk shadow ^^

dusk shadow
#

ahhhh, got it, thank uu!

somber sky
#

oh im slow mb, idk why its pushing to a whole other repository

#

πŸ’€ mb

shrewd apex
#

change ur remote

somber sky
#

ik

shrewd vapor
#

Hello, i try to make a button on my command but this don't work i get an error

@commands.hybrid_command(name = "ticket-panel", description = "Create a ticket panel")
    @commands.has_permissions(administrator = True)
    @commands.guild_only()
    async def ticket_panel(self, ctx: commands.Context):
        embed = discord.Embed(title="Ticket Panel", description="Cliquez sur le bouton ci-dessous pour crΓ©er un nouveau ticket.")
        components = [Button(style=ButtonStyle.green, label="Create Ticket", custom_id="create_ticket_button")]
        await ctx.send(embed=embed, components=[components])```
```shell
2024-01-31 17:42:06 ERROR    discord.ext.commands.bot Ignoring exception in command ticket-panel
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/cogs/ticket.py", line 15, in ticket_panel
    components = [Button(style=ButtonStyle.green, label="Create Ticket", custom_id="create_ticket_button")]
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Button.__init__() got an unexpected keyword argument 'style'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ticket-panel' raised an exception: TypeError: Button.__init__() got an unexpected keyword argument 'style'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'ticket-panel' raised an exception: TypeError: Button.__init__() got an unexpected keyword argument 'style'```
somber sky
# shrewd apex change ur remote

how do i delete a remote cause it keeps saying rep not found cause its trying to find my old rep that i deleted cause ion need it

shrewd vapor
#

from discord.components import Button, ButtonStyle

slate swan
#

from discord.ui import Button
from discord import ButtonStyle

#

those are correct ones

shrewd apex
somber sky
#

ty

shrewd vapor
#

Ok now i get an error in the await ctx.send

#

With components

slate swan
#

most likely cause you are nesting a list inside a list again

shrewd vapor
#

Ok so its just components=components ?

slate swan
#

technically yes

shrewd vapor
#

ok let me try

slate swan
shrewd vapor
#

And don't work yes

slate swan
#

you need to use a view

#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
shrewd vapor
#

i have already try in my cog but i get error

slate swan
#

and simple example on how to

shrewd vapor
#

I get this error

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/ticket.py", line 18, in callback
    if channel.name == f"ticket-{ctx.author.name}" or channel.name == f"claimed-{ctx.author.name}":
                                 ^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'```
But i don't use interaction, i use ctx: commands.Context
slate swan
#

components use interactions

#

if you annotate it as context doesnt mean its context

shrewd vapor
#

bruh i'm lost 😦

slate swan
#

whats a big change about getting interaction in button callback intead of contexT?

shrewd vapor
#

i use that in a cog, and i'm lost with interaction in a cog

slate swan
#

how is that

shrewd vapor
#

this is my entire code

slate swan
#

just explain what you dont understand

shrewd vapor
#

How use interaction in a cog, because in everything i have look for understand cog i have never see anyone use interaction

slate swan
#

what do you mean use interaction in a cog?

#

werent we at the topic of components

shrewd vapor
#

Its the first time i try to use components, i know how to use Interaction in the main file, but in a cog idk if its the same or not

slate swan
#

just create a View subclass and handle the components in there like in an example i sent

shrewd vapor
#

ok my old code work with everything of ctx replaced with interaction

#

I just need to found how to make persistent bouton

#

Its the last things i need to found for my ticket system work

slate swan
#

its in the examples folder too

shrewd vapor
#

oh ok thanks

#

Now last things i need to understand

shrewd vapor
#

I'm lost

#

I don't understand the class DynamicButton

high mesa
#

Can someone please explain regarding the custom_id of buttons, like there are 3 buttons, so how do I get the id of the 3 buttons seperately

shrewd apex
high mesa
sick birch
#

so you should know what it is

shrewd vapor
#

How i made a Dynamic id he get my custom id look like "claim_ticket_button" all custom id from ticket finish by _ticket_button the only thing that changes its the first word

#

Because everything i read he get only an id

#

like 123456789

somber sky
high mesa
lyric solar
#
with open('data.json', encoding='utf-8') as f:
    data = json.load(f)

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

@bot.event
async def on_ready():
    print("Bot is ready")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(str(e))

class ExpandDropdown(discord.ui.Select):
    def __init__(self, data):
        options = [
            discord.SelectOption(label=f"Expand #{i+1}") for i in range(len(data))
        ]
        super().__init__(placeholder="Learn more...", options=options)
        self.data = data

    async def callback(self, interaction: discord.Interaction):
        option_index = int(self.values[0].split('#')[-1]) - 1
        selected_data = self.data[option_index]

        embed = discord.Embed(
            title=f"{selected_data['title']}",
            description=f"{selected_data['title_expanded']}\n\n{selected_data['content']}",
            color=0xFFFFFF
        )
        await interaction.response.send_message(embed=embed, ephemeral=True)```
there is an issue in this code for some reason, it doesn't print it out but i get this interaction has failed after like 3-5 refreshes
i need to paste the code tho
vestal gyro
final iron
sick birch
#

and the button object itself

lyric solar
#

some help would be nice

high mesa
shrewd vapor
#

I'm always lost with persistent view 😭

#

i don't understand how to do for my ticket system

glad cradle
#

ignore the Dynamic thing

#

!d discord.ext.commands.Bot.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
shrewd vapor
#

I need to add that in my setup hook ?

glad cradle
#

yeah

#

ignore the other class of the example

#

that example shows 2 different things in 1 example, it doesn't make sense

glad cradle
shrewd vapor
#

If i put that this work ?
bot.add_view(TicketCog(bot))

glad cradle
#

in your case using the former is ok

glad cradle
#

view must be a view not a cog

shrewd vapor
#

Every of my view is in a cog

#

I need to import every view ?

glad cradle
#

wait first i have a question

#

are the views for a single message that is created once or are they used in response messages for commands?

shrewd vapor
#

I have a view used on the Ticket Panel where you have the button Create Ticket

#

In the ticket you have 2 views Close Ticket and Claim Ticket

#

The Close Ticket after used change for Delete Ticket

glad cradle
#

then nevermind you need the Dynamic thing approach, ignore everything in that example about the Persistent view

dry kelp
#

anyone knows how to fix this ?

slate swan
glad cradle
lyric solar
#

how do i prevent this from happening

#

😭

final iron
#

It's normal

lyric solar
#

😭 ?

final iron
#

how often do the disconnects happen

lyric solar
#

every 15 minutes??

#

i didnt know that i disconnected

final iron
#

how are you hosting it

lyric solar
#

aws

#

tried google cloud

#

same thing

final iron
#

is it consistently every 15 minutes

lyric solar
#

is disabling sharding a solution

final iron
#

Do you need sharding in the first place?

lyric solar
final iron
#

no it isnt

lyric solar
#

how do i disable it

final iron
#

its not enabled by default

lyric solar
#

i didnt enable it
just saying

final iron
#

if you didnt enable it, it won't be enabled.

lyric solar
final iron
#

Shard ID None

lyric solar
final iron
#

who knows

#

set logging to debug and send the associated logs when it occurs

lyric solar
#

i dont use logging

final iron
#

then start

lyric solar
#

how

#

is it because i make the discord bot act like a webhook

final iron
#

its legitimately impossible to say without any code/logs

lyric solar
#

gimme as ec

lyric solar
#

@final iron no sharding error apparenlty

#

it just doesn't wanna load after some time idk why tho

final iron
#

why would there be a sharding error

#

Have you setup logging yet?

lyric solar
lyric solar
final iron
#

We went over this. It has nothing to do with sharding.

lyric solar
final iron
#

Already went through this. It’s impossible to say without logs

#

Show your updated code

#

You didn’t set up the logging level properly

lyric solar
#
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')

if __name__ == "__main__": 

    bot.run("token", log_handler=handler)```
final iron
#

Go over the link I sent please

lyric solar
#

okay

#

log_level=logging.DEBUG?

final iron
#

Go over the link.

lyric solar
#

debug or info

#

nvm that was a stupid question

lyric solar
#

okay wait

#

i just have to wait for it to log now

lyric solar
#

@final iron caught some logs

#

it seems like the bot would "time out" if no one used the interaction

#

and in the console, when requested to open data.json it should print "loaded", however it didnt

#

"This interaction didn't respond"

pale zenith
lyric solar
pale zenith
#

yes that would be most helpful

lyric solar
#

okay one sec

pale zenith
# lyric solar https://paste.pythondiscord.com/ELAQ <@349373972103561218>

I see. That's quite a lot of code, and what I assume is happening here is that a logging entry from asyncio is being eaten, because you only have the discord logger enabled, and no errors of what you do would get propagated to them.

Could you please enable the root logger, and send the resulting logs? (do not enable debug logs since that's just gonna fill your console up with bullshit.)

handler = logging.handlers.RotatingFileHandler(
    filename='discord.log',
    encoding='utf-8',
    maxBytes=32 * 1024 * 1024,  # 32 MiB
    backupCount=5,  # Rotate through 5 files
)

if __name__ == "__main__":
    bot.run("token", log_handler=handler, root_logger=True)

patent lark
lyric solar
#

πŸ‘

patent lark
lyric solar
#

im assuming yes

pale zenith
#

the addHandler can be omitted

#

but the formatter part, sure, keep it, unless you want to keep discord.py's default formatter. (wont affect anything useful either way)

lyric solar
#

this get's removed too right

pale zenith
#

yeah, that only brings up useless stuff

lyric solar
#

okay gimme a sec

lyric solar
#

i don't know if the error occurs rn tho so gimme a sec

pale zenith
#

πŸ˜”

#

with no error, it's hard to debug unfortunately

lyric solar
#

idk how it happens or when

pale zenith
#

you mean the fact that a button(view*) stops functioning after the default timeout of 180 seconds?

lyric solar
#

maybee...??

#

180s is 3 minutes right?

pale zenith
#

yeah

lyric solar
#

wait 1 more minute

pale zenith
#

it will stop working after a restart, though

lyric solar
#

was it really that simple.

pale zenith
#

this whole code is a big mess though, I would suggest organizing things out. massive while true with... a lot of... stuff πŸ₯΄

lyric solar
#

yeah umm

lyric solar
#

if it works dont touch it

pale zenith
#

rule #2 of coding: ignore rule #1

#

TLDR of every programming standard out there

lyric solar
#

rule #3 of coding: (maybe) ignore rule #2

pale zenith
#

rule #4: error- infinite cycle

lyric solar
pale zenith
#

wrong init

lyric solar
#

wait i MIGHT be silly

#

yep indeed i WAS silly

pale zenith
#

or nvm lmao yeah

lyric solar
#

thanks πŸ™

pale zenith
pale zenith
lyric solar
#

@pale zenith thanks for telling me how to change the timeout

#

i knew it timed out 😭

flat pier
regal dragon
#

can someone help me with my slash commands?

void pumice
regal dragon
#

iv fixed it by now, forgot to sync

stray drum
#

well mates i have i question , i am tryna make a bot for code quiz like a competitive and score sharable bot but cant understand how can i get question for quizz the way i want (in subtopics and different difficulty level ) what is the best way you think ?

vestal acorn
stray drum
vestal acorn
#

what do you want to do exactly?
Send an infinite amount of questions?

stray drum
#

i mean not infinte but atleast not like just same 10-20 question repeating

vestal acorn
#

yeah I see

stray drum
#

and as a user you dont want like repeating question in a quiz beats the whole purpose of quiz

vestal acorn
#

of course

vestal acorn
#

like generating questions?

stray drum
# vestal acorn what did you think about when you said api?

well im tryna find a api which works like my criteria but ig feels like im dream real high so have to go down on it , like there is quiz api there is barely for programming quiz + just for normal topics like html python like very lil catagorys

vestal acorn
#

I think in this case, the best you could do is to create yourself a lot of questions

#

because, if you use an ai to generate it, the questions won't have any sense
If you could find an api, it could work but I don't have any in mind rn

stray drum
#

well ig if it have to work i just have to make a self api

#

preety hard

vestal acorn
#

if you want to use it with a discord bot, I don't think you must create an api

#

you can have your questions locally

stray drum
vestal acorn
#

a local json file, or in a database

stray drum
#

understand

#

lets se how i do , well is it better to have mulity choise question or a single word text answer

vestal acorn
#

as you prefer, I thought first about a multiple choice question, but both are pretty easy to do

stray drum
vestal acorn
#

yes

#

the easiest is multiple choices

#

you could do strings comparisons if you expect for string answers

stray drum
#

well what is the best way of storing question in way that amount of space they take wont matter

vestal acorn
#

You store only ascii characters, so even if you have a huge amount of questions, your file won't exceed some MB

#

which is quite reasonable I think

#

or, if you do it with a database, it will be a little bigger but you won't have to load it in ram

stray drum
#

hmmm @vestal acorn what if i give them id number and as they are being answered by the user store the id number and try not to repeat them this way

vestal acorn
#

I would work I think

quick gust
vestal acorn
drifting arrow
#

How many buttons can a response have?

#

12?

slate swan
#

you can have 5 buttons in 1 row and a total of 5 rows

#

so 25

drifting arrow
#

oh lord

#

that's a lot of buttons

quick gust
vestal acorn
#

yes

candid flume
#

for whatever reason, my bot's commands are not working, they are showing up in the server's integrations tab but not showing up when trying to use them, is there something I did wrong?

pale zenith
swift siren
#

how can you make your bot check if a users message contains a sticker

slate swan
unkempt canyonBOT
swift siren
slate swan
drifting arrow
#

Does interaction.followup not have a send_modal? D:

shrewd apex
drifting arrow
#

I figured as much

#

So I have to do something else :(

#

:D it's okay. I think this solution is better anyway

#

More intuitive for the end user!

#

@shrewd apex :D

shrewd apex
#

πŸ‘

shrewd apex
#

each would occupy a line

drifting arrow
#

Something I could do to improve?

#

Because I need to be able to send multiple modals and I dont want individual commands.
It needs to be simple and straight forward.

#

@shrewd apex

#

Mobile

shrewd apex
drifting arrow
shrewd apex
#

just a gui concept thing it's not anything discord specific

drifting arrow
#

Oh

#

I mean, I could improve the button text to explain more

#

Like "Don't Ban User" and "Ban User"

#

Or "Toggle Ban User"?

somber sky
#
@client.tree.command(description='Use this before setting channels.')
@app_commands.checks.has_permissions(administrator=True)
async def setup(ctx):
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute(
                'SELECT settransactionschannel FROM users WHERE guild = ?',
                (ctx.guild.id, ))
            data = await cursor.fetchone()
            if data:
                pass
            else:
                await ctx.response.send_message(f"Set everything up!", ephemeral=True)
                await cursor.execute(
                    'INSERT INTO users (settransactionschannel, setlogschannel, setalertschannel, setgametimechannel, setpickupschannel, setstreamschannel, setfreeagencychannel, setnoticeschannel, setverdictschannel, guild, setdemandchannel) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                    (
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        ctx.guild.id,
                        0,
                    ))
        await db.commit()```

i have this command where when u run it it like setsup the database so that you can set channels, how would i put this in my on_ready so that people dont gotta run it everytime a new set command is added and instead it updates the second the bot is started
leaden olive
#

how can i disable a button after one click it doesnt work here

glad cradle
somber sky
#
py
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/root/bullshark/main.py", line 100, in on_ready
    await cursor.execute(
  File "/usr/lib/python3/dist-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/usr/lib/python3/dist-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3/dist-packages/aiosqlite/core.py", line 129, in _execute
    return await future
           ^^^^^^^^^^^^
  File "/usr/lib/python3/dist-packages/aiosqlite/core.py", line 102, in run
    result = function()
             ^^^^^^^^^^
sqlite3.DatabaseError: database disk image is malformed```
#

idk what to do i tried so many things

somber sky
# somber sky ```` py Traceback (most recent call last): File "/usr/lib/python3/dist-package...
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute(
                'CREATE TABLE IF NOT EXISTS users (settransactionschannel STRING, setlogschannel STRING, setalertschannel STRING, setgametimechannel STRING, setpickupschannel STRING, setstreamschannel STRING, setfreeagencychannel STRING, setstatschannel STRING, setnoticeschannel STRING, setverdictschannel STRING, guild INTEGER, setdemandchannel STRING)'
            )
        await db.commit()
    async with aiosqlite.connect("main.db2") as db2:
        async with db2.cursor() as cursor:
            await cursor.execute(
                'CREATE TABLE IF NOT EXISTS users (setrefereerole STRING, setcandidaterole STRING, setcaptainrole STRING, setsuspendedrole STRING, setstreamerrole STRING, guild INTEGER, seteligiblerole STRING, setmanagerrole STRING)'
            )
        await db2.commit()```
somber sky
#

idk how it was, i fixed it that shit took so lonng

#

i had to deleted the databases and re add them and push it to github

#

but like i already did it so idk why it didnt work the first time but it worked now

rugged shadow
#

don't commit your database πŸ€¦β€β™‚οΈ

#

especially if this is open source

shrewd apex
#

why would you create a different database just for another table

rugged shadow
#

lolll actually

glad cradle
#

1 db per table

young dagger
#

What is the best package for detecting non-English messages for my Discord bot?

finite salmon
#

While also excluding symbols and numbers

golden portal
#

well, it's not just english that uses the latin alphabet

golden portal
#

idk maybe use googletrans or something

finite salmon
slate swan
unkempt canyonBOT
young dagger
slate swan
#

obviously messages like that will be missunderstood

young dagger
#

(same message '+1 Draft')

slate swan
#

how is that polish

young dagger
#

Niewiem

slate swan
#

ja tez nie

young dagger
# unkempt canyon

Is this really using Google's language-detection? Because Google shows me this

slate swan
young dagger
onyx horizon
#

cool

glossy mauve
#

how do i reload my bot with jishaku

golden portal
#

jsk reload folder.filename

#

or you mean restart your bot?

somber sky
#

howw ould i make a command where i transfer data from a command to a googlr spreadsheet?

drifting arrow
#

When it comes to sharding a discord bot , is it possible to assign certain commands and cogs to a specific shard?
And can I reload specific shards or do I need to reload the entire not still?

rotund wagon
#

I'm hosting my bot with heroku and it's being difficult, the github is connected, but the deploy says it can't identify what default language it's using(what type of code)

slate swan
#

You can set it in the settings

#

and you should have a Procfile I suppose, which you're eventually missing

rotund wagon
#

I found the deploy keys section, I just don't know what to put there

shrewd apex
#

u need to add a procfile iirc and the python package

rotund wagon
#

No idea what any of that means lol, do you mind explaining ?

rotund wagon
rugged shadow
#

iirc means "if i remember correctly" fwiw

rotund wagon
#

._. Oh dang I'm not smart when it comes to abbreviations

#

Lmao

#

Now it's saying buildpack not compatible with app

drifting arrow
#

Is there any specific way to assign specific commands/cogs to a given server on loadup?
Either using sharding or something else?

#

I know I can just have a decorator that checks if the guild has permissions based on my database, but it'd be nice if they couldn't even see the command to begin with.

golden portal
#

!d discord.app_commands.guilds

unkempt canyonBOT
#

@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.

When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.

Note

Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command) or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu) decorator then this must go below that decorator.

Example...
golden portal
#

there is also discord.app_commands.default_permissions so it doesnt appear for users without the perm

drifting arrow
#

@golden portal - Can I update that dynamically? Like lets say originally a guild isnt in the list of IDs, could I update it using a command?

golden portal
#

the built in way, no, since its a guild specific commands, you can however just sync an empty tree onto that guild that you removed it from

drifting arrow
#
import discord
import json
from discord.ext import commands

# Import cogs
from cogs.cheetos import Cheetos
from cogs.private_commands import PrivateCommands
from cogs.public_commands import PublicCommands
from cogs.rah import Rah
from cogs.rahlink import RahLink
from cogs.vdfchecker import VDFchecker
from cogs.tickets import RAHTickets
from cogs.chatmoderator import ChatModerator
from cogs.test1 import Test1
from cogs.test2 import Test2

with open("./configs/config.json", "r") as config_file:
    config = json.load(config_file)

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix=config['additional']['prefix'],
            intents=discord.Intents.all(),
            application_id=config['additional']['application_id']
        )
        self._cogs_to_load = {
            #"Cheetos": Cheetos,
            #"PrivateCommands": PrivateCommands,
            #"PublicCommands": PublicCommands,
            #"Rah": Rah,
            #"RahLink": RahLink,
            #"VDFCHECKER": VDFchecker,
            #"RAHTickets": RAHTickets,
            #"ChatModerator": ChatModerator
        }
        self._cogs_to_load['Test2'] = Test2
        self._cogs_to_load['Test1'] = Test1
        #self._cogs_to_load['RAHTickets'] = RAHTickets
        #self._cogs_to_load['ChatModerator'] = ChatModerator

    async def on_ready(self):
        for guild in self.guilds:
            if guild.id == 1203230080512294922:
                print(f"Syncing to {guild.name}")
                for name, cog_class in self._cogs_to_load.items():
                    cog_instance = cog_class(bot=self, config=config)
                    await self.add_cog(cog_instance)
                await bot.tree.sync(guild=guild)

        print("Bot fully loaded and ready to go!")

# Ensure the script is being run directly, not imported as a module
if __name__ == "__main__":
    bot = MyBot()
    bot.run(config['tokens']['discord_token'])

#

Already doing this and it doesnt seem to work properly

#

although I'm definitely doing something wrong lol

golden portal
#

why arent you syncing globally tho

drifting arrow
#

Coz I want to be able to sync specific cogs/commands to specific guilds.

#

For example "PrivateCommands" in that code i shared are just for me. So why should others see them?

golden portal
#

you can just set the cog to be for a specific guild in the extension like so, ```py
guild = discord.Object(1203230080512294922)
await bot.add_cog(cog, guild=guild)

then just `bot.tree.sync(guild=guild)` at the end
#

why aren't you using extension?

rotund wagon
#

i need help with heroku hosting, says the app isnt compatible with buildpack even thought thier both python

drifting arrow
golden portal
drifting arrow
#
async def on_ready(self):
        for name, cog_class in self._cogs_to_load.items():
               cog_instance = cog_class(bot=self, config=config)
               await self.add_cog(cog_instance)
        await self.tree.sync()
        print("Bot fully loaded and ready to go!")
``` All my cogs are in individual files. I'm just loading them here.
Instead of needing the "setup" at the end where it adds the cog it does it here
golden portal
#

i know, im just asking why

drifting arrow
#

Easier to remove a cog if I need to

#

Just # out the cog and reload the bot

golden portal
#

u could achieve the same with just a list of extensions, but oh well im not gonna go nerdy

drifting arrow
#

This way I can add new features without needing to remove the files

#

I can also parse things like the config file down to each cog

#

Instead of each cog needing to load the config

#

Why open the file many times when 1 is enough?

golden portal
#

having to reinvent the wheel isnt really my thing so you do you

drifting arrow
#

Β―_(ツ)_/Β―

#

It works don't it?

drifting arrow
#

Is there a proper way to make a command sleep/wait?

golden portal
#

need more elaboration on that, do you just want an asyncio.sleep?

unkempt canyonBOT
#

utils/bot.py lines 68 to 78

def auto_setup(self, module_name: str) -> None:
    module = importlib.import_module(module_name, None)
    sys.modules[module_name] = module
    members = inspect.getmembers(
        module,
        lambda x: inspect.isclass(x) and issubclass(x, commands.Cog) and x.__name__ != "Cog",
    )
    for member in members:
        self.add_cog(member[1](self))

    self.log.ok("%s loaded", module_name)```
vale wing
#

Or make it bot subclass attribute

sand ingot
#

how and where do i start making a discord bot

slate swan
#

See pinned messages and the channel description

robust fulcrum
faint rapids
slate swan
#

as far as i know you can only set it on developer portal

rotund wagon
#

i need help with heroku hosting, says the app isnt compatible with buildpack even thought thier both python

rigid shard
#
async def saldo(ctx, user: discord.User = None):
    if user is None:
        user = ctx.author
    
    user_id = str(user.id)
    balance = get_balance(user_id)

    embed = discord.Embed(title=f"Perfil de {user.name}", description=f":MoedaGira: Saldo: {balance} Uabos", color=0x00ff00)
    embed.set_thumbnail(url=user.avatar.url)

    await ctx.send(embed=embed)``` how can i make like the bot reply the image like its on the image?
slate swan
#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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

A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) referenced by this context.

For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send).

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
slate swan
#

Instead of ....send()

#

can someone help me make a discord bot

ivory storm
#

!d intents

unkempt canyonBOT
#
slate swan
slate swan
wicked pollen
#

I need help with the sb discord ai project if anyone would be willing to help me let me know in a private message

inner barn
#

How can I make a bot that automatically assigns a role when someone comes to the server?

slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
slate swan
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
slate swan
#

Listen to the event on_member_join and use the add_roles method on the member to add the role you wish

gilded sable
#
import discord
from discord.ext import commands
from PIL import Image
from io import BytesIO

PREFIX = '!'

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

bot = commands.Bot(command_prefix=PREFIX, intents=intents)

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user.name}')

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

    await bot.process_commands(message)

    if message.attachments:
        for attachment in message.attachments:
            if attachment.url.endswith(('.png', '.jpg', '.jpeg', '.gif')):
                await process_image(message, attachment)
                return

    print("Message received:", message.content)

async def process_image(message, attachment):
    image_data = await attachment.read()
    image = Image.open(BytesIO(image_data))

    text = ocr_text_from_image(image)

    print("Extracted text:", text)

    target_sentence = how many ppl in the earth"

    if target_sentence.lower() in text.lower():
        await message.channel.send("8billion")
    else:
        await message.channel.send("No match found.")

def ocr_text_from_image(image):
    try:
        import pytesseract
        return pytesseract.image_to_string(image)
    except ImportError:
        print("pytesseract library not installed. Install it using 'pip install pytesseract'.")
        return ""

bot.run(TOKEN)```
why does this don't work, it's should take the image that the user send it to the channel, then check if it's include the question 'target_sentence = how many people in the earth" then send me the answer which is 8B, if didn't find say i don't know the answer, help please
gilded sable
gilded sable
#

But still not working 😭

proud finch
#

Heya I'm tryna make my bot do some stuff and frankly

I'm lost for ways to try make it work :0

fast musk
#

try hitting it

proud finch
# merry cliff what stuff?

basicly im trying to get it to react to a message as in

you type ?hi and it picks up on that and replys with hi... hru

u then answer and depending on ur answer get a differant responce

if u say good or smthg u get like great have a good day

and if u reply with not so good you get a completely differant answer and dialog

also i want the code to basicly have a shut off time of 1 min so if you dont answer in that time the interaction stops

and i want it to react to the person who origonally did the ?hi

merry cliff
#

so like a chatbot

proud finch
#

yea basicly

proud finch
#

itll have other functions but mainly yea, as its my first time building a bot so its a way for me to learn how to implament it practicly

merry cliff
#

might be a bit complicated for a first bot lol

proud finch
#

i like to challange myself

slate swan
proud finch
#

long ago and remember little to nothing

slate swan
#

And I know getting chatbots will even further complicate this.

#

Or just chat-gpt the whole thing

tiny coyote
#

id like to know how to create a countdown timestamp (doesn't have to be timestamp) on discord.py using datetime/timedelta

golden portal
tiny coyote
#

sounds like alot of unnecessary work ngl ima use the first option

#

thanks btw

golden portal
#

sure, use the R style for format_dt

sick birch
#

much easier, and it's also live, check this out:

<t:1707019080:R>

tiny coyote
tiny coyote
golden portal
#

huh?

tiny coyote
# golden portal huh?

or should i say calculate the time so
for example if it says in minutes 0 or 1 minute ago it triggers an event

sick birch
#

you would simply wait until then with asyncio.sleep

tiny coyote
#

the explanation hasnt clicked yet srry

tiny coyote
sick birch
#

something wrong?

feral timber
golden portal
tiny coyote
sick birch
#

but also running a while true and checking the current time wastes clock cycles

tiny coyote
#

i apologize

sick birch
#

not sure what you mean by "time weilding"

tiny coyote
slate swan
#

where should I learn to start coding discord bots?

#

I have a decent understanding of python now

river plank
#

wait nvm

tiny coyote
#

thats why i said it doesnt have to be timestamp so i can manipulate it more efficiently

slate swan
#

I can't use decorators though or lambda.

golden portal
sick birch
slate swan
vapid parcel
#

Assuming Discord Bots will be able to get Join Method soon?

sick birch
tiny coyote
#

makes sence.
welp atleast now ik.

vapid parcel
#

Aka invite, and whos invite n stuff like that

sick birch
#

Ah, not sure about that then

vapid parcel
#

Because currently they still do not have access to that unless im living under a rock..?

sick birch
#

they do not

#

as far as i'm aware, that is

vapid parcel
#

Yeah, im hoping just hoping, they add it.. because it would be kinda nice. But if they don't then thats fine, been like that for 3 years now, we started asking 3 years ago, they still haven't done it 😭

sick birch
#

it is how it is

drifting arrow
#

Is there a clear way to see what guilds my bots in? outside of just listing them using my bot?

#

like is it on the discord website somewhere?

drifting arrow
#

It would be nice if it was listed somewhere lol

#

Oh well

final iron
#

Discord dispatches that information when you connect to the gateway

shrewd apex
drifting arrow
#

If I want to use the timeout function to time someone out, do I need to submit a proper datetime or can I use something like "1d"?

golden portal
#

the Member.timeout method? have to be a datetime object or a timedelta

tough mantle
#

someone know yt channel that have good playlist for beginners?

glad cradle
slate swan
#

Why is it a Link in the insert and not the images?

#

Because it's an embed

naive briar
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
leaden olive
#

guys can someone help me, the part of the code isnt being executed i mean the command works but it should send a message that says that i successfully withdrew the coins, but it doesnt

slate swan
#

First I'd remove that horrible try/except

#

Then you'll see errors in the console and it will help you debug your code

leaden olive
#

sure!

mighty pilot
#
    async def banner(self, ctx, member: discord.Member = None):
        if not member:
            member = ctx.author
        elif isinstance(member, int):
            member = await self.get_member_by_id(ctx.guild, member)
            if not member:
                embed = discord.Embed(description="User not found.")
                return await ctx.send(embed=embed)

        banner = member.banner
        if banner:
            banner_url = banner.url
            embed = discord.Embed()
            embed.set_image(url=banner_url)
            embed.set_author(name=f"{member.display_name}'s banner", icon_url=member.avatar.url)
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(description="User does not have a banner.")
            await ctx.send(embed=embed)```

Even if the user has banner it says "User does not have a banner." Did they change the way to get someone's banner or?
leaden olive
#

fixed! Thank you krypton, i really appreciate your help!

naive briar
#

!d discord.Member.banner

#

!d discord.User.banner

unkempt canyonBOT
#

property banner```
Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
naive briar
mighty pilot
naive briar
slate swan
#

self bot Sus

mighty pilot
#

no sir m_joobishycry

gilded sable
#
import discord
from discord.ext import commands
from PIL import Image
from io import BytesIO

PREFIX = '!'

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

bot = commands.Bot(command_prefix=PREFIX, intents=intents)

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user.name}')

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

    await bot.process_commands(message)

    if message.attachments:
        for attachment in message.attachments:
            if attachment.url.endswith(('.png', '.jpg', '.jpeg', '.gif')):
                await process_image(message, attachment)
                return

    print("Message received:", message.content)

async def process_image(message, attachment):
    image_data = await attachment.read()
    image = Image.open(BytesIO(image_data))

    text = ocr_text_from_image(image)

    print("Extracted text:", text)

    target_sentence = how many ppl in the earth"

    if target_sentence.lower() in text.lower():
        await message.channel.send("8billion")
    else:
        await message.channel.send("No match found.")

def ocr_text_from_image(image):
    try:
        import pytesseract
        return pytesseract.image_to_string(image)
    except ImportError:
        print("pytesseract library not installed. Install it using 'pip install pytesseract'.")
        return ""

bot.run(TOKEN)```
why does this don't work, it's should take the image that the user send it to the channel, then check if it's include the question 'target_sentence = how many people in the earth" then send me the answer which is 8B, if didn't find say i don't know the answer, help please
slate swan
#

Hi, can anyone tell me the problem with this code? It takes me the names of random people, and it doesn't tell me who moved who when a person is taken to its own

@client.event
async def on_voice_state_update(member, before, after):
mover = None

# Trova l'utente che Γ¨ stato rimosso dalla stanza vocale originale
for member_before in before.channel.members:
    if member_before not in after.channel.members:
        mover = member_before
        break

# Costruisci il messaggio in base a chi ha effettuato lo spostamento
if mover is not None:
    # Se mover Γ¨ diverso da None, utilizza il suo display_name
    if member != mover:
        # Se il membro non Γ¨ il responsabile dello spostamento, allora ha spostato l'altro utente
        message = discord.Embed(title="1", description=f"{mover.display_name} ha spostato {member.display_name} dalla stanza vocale '{before.channel.name}' alla stanza vocale '{after.channel.name}'")
    else:
        # Altrimenti, considera l'utente stesso come responsabile dello spostamento
        message = discord.Embed(title="2", description=f"{member.display_name} ha spostato {mover.display_name} dalla stanza vocale '{before.channel.name}' alla stanza vocale '{after.channel.name}'")
else:
    # Nessun utente rilevato come responsabile dello spostamento, quindi l'utente stesso si Γ¨ spostato
    message = discord.Embed(title="3", description=f"{member.display_name} si Γ¨ spostato dalla stanza vocale '{before.channel.name}' alla stanza vocale '{after.channel.name}'")

# Invia il messaggio nel canale specificato
channel = client.get_channel(CHANNEL_ID)
await channel.send(embed=message)
rigid shard
#

I'm getting this problem which I don't understand why its happening, I want the image to be on the embed but its not. Heres the code: ```
user_id = str(ctx.author.id)
cost = 10

current_balance = get_balance(user_id)
if current_balance < cost:
    embed = discord.Embed(title="Erro ao abrir a caixa", description=":x: NΓ£o tens Uabos suficientes para abrir a caixa.", color=0xff0000)
    await ctx.reply(embed=embed)
    return

case_folder = os.path.join("C:\\Users\\Admin\\Desktop\\bot\\Itens", case)
if not os.path.exists(case_folder):
    embed = discord.Embed(title="Erro ao abrir a caixa", description=":x: Caixa nΓ£o encontrada.", color=0xff0000)
    await ctx.reply(embed=embed)
    return

rarity_folder = random.choice(os.listdir(case_folder))
rarity_path = os.path.join(case_folder, rarity_folder)
if not os.path.isdir(rarity_path):
    embed = discord.Embed(title="Erro ao abrir a caixa", description=":x: Pasta de raridade nΓ£o encontrada.", color=0xff0000)
    await ctx.reply(embed=embed)
    return

item = random.choice(os.listdir(rarity_path))
item_name = os.path.splitext(item)[0]
item_path = os.path.join(rarity_path, item)

# Determine the rarity based on the folder name
rarity = rarity_folder.capitalize()

desguaste = random.uniform(0, 1)

update_balance(user_id, current_balance - cost)

embed = discord.Embed(title="Caixa aberta", description=f"{ctx.author.mention} abriu a caixa `{case}` e obteve `{item_name}` ({rarity}) com desgaste {desguaste:.10f}.", color=0x00ff00)

try:
    file = discord.File(item_path, filename=f"{item_name}.png")
    embed.set_image(url=f"attachment://{item_name}.png")
    await ctx.reply(embed=embed, file=file)
except FileNotFoundError:
    embed.set_image(url="attachment://image.png")
    await ctx.reply(embed=embed, file=discord.File(item_path, filename="image.png"))```
lament ruin
#

Hey everyone.
I am currently working on a Discord Bot. I want to bring it to the next level. So if anyone is interested in developing this Project with me. Let me know.

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
glad cradle
#

bruh they didn't implement a file kwarg

#

skill issue

vapid parcel
glad cradle
vapid parcel
#

Discord should just allow us to do it, instead of doing all of that 😭

random obsidian
#

Guys

@bot.tree.command(name="count",description="Count 1 To 9")
async def get_orders(interaction: discord.Interaction):
  for x in range(9):
    await interaction.channel.send(x)

For example , i have an slash command when i trigger it , it count 1 to 9
I want to recieve an error when another command or slash command is triggered when this command is counting from 1 to 9

And have another slash command like :

@bot.tree.command(name="say_hello",description="Send Hello In Chat")
async def say_hello(interaction: discord.Interaction):
  await interaction.channel.send("Hello!")

I want to recieve an error when trigger
say_hello
command , while another slash command is working (counting 1 to 9)
How it work?
Can anyone help me?

graceful ermine
#

How do I prevent this code from advertising my own ad in my advertising channel?

Hello, I've created this public bot that can do partnerships and advertising and for some reason people are having issues with this feature of my bot saying that it keeps on advertising their own ad in their own advertising channel so I figured to come here and get some support.

#
    @tasks.loop(seconds=2400)
    async def auto_advertise2(self):
        async with self.bot.db11.cursor() as cursor:
            await cursor.execute("SELECT channel, guild FROM advertise WHERE setup='TRUE' AND auto_advertise='TRUE' ORDER BY RANDOM() DESC LIMIT 40")
            channels = await cursor.fetchall()
            channel_ids = [channel[0] for channel in channels]  # Extract channel ids from the tuples
            guild_ids = [guild[1] for guild in channels]  # Extract guild ids from the tuples
            placeholders = ', '.join('?' for _ in channel_ids)  # Create placeholders for the query
            await cursor.execute(f"SELECT guild FROM advertise WHERE channel IN ({placeholders})", channel_ids)
            guild_id_tuples = await cursor.fetchall()

        # Extract guild ids from the tuples and convert to a tuple
        guild_ids = tuple(guild_id[0] for guild_id in guild_id_tuples)

        async with self.bot.db2.cursor() as cursor:
            placeholders = ', '.join('?' for _ in guild_ids)  # Create placeholders for the query
            await cursor.execute(f"SELECT guild, ad, discord_link FROM ad WHERE guild IN ({placeholders}) ORDER BY RANDOM() DESC LIMIT 40", guild_ids)
            ads = await cursor.fetchall()

        for i, channel_id in enumerate(channel_ids, start=1):
            guild, ad, link = ads[i % len(ads)]
            ad = ad.replace("@everyone", "").replace("@here", "")

            # Skip if the guild is the same as the current guild


            channel = await self.bot.fetch_channel(channel_id)
            if channel == channels:
                print("Prevented guild from advertising in its own advertising channel")
                continue
            await channel.send(ad)
            await channel.send(link)```
#

DB 11 SQL structure:
await cursor.execute("CREATE TABLE IF NOT EXISTS advertise (guild INTEGER, channel INTEGER, setup STRING, auto_advertise STRING)")

DB 2 SQL Structure:
await cursor.execute("CREATE TABLE IF NOT EXISTS ad (guild INTEGER, ad STRING, banner1 STRING, banner2 STRING, discord_link STRING)")

torn solar
#

i dont know what this means cus i dont have a file named <stdin>

#

those are my files

slate zephyr
# torn solar

looks like an issue in vs code, it seems youre in the python repl mode

#

type in

#

exit()

torn solar
#

in my terminal?

slate zephyr
torn solar
slate zephyr
#

raise SystemExit

torn solar
#

line 2 and 3 are what i got when i tried to run the file

slate zephyr
torn solar
#

ive made a ton of bots before not sure where i went wrong

slate zephyr
#

are yoy on windows?

torn solar
#

yeah

slate zephyr
torn solar
#

sorry for sending ss of the code lol

#
class EmbarkBot(commands.bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix="!", intents=intents)
        
    async def setup_hook(self) -> None:
        self.add_view(PersistentCloseButton())
        self.add_view(PersistentConfirmation())
        self.add_view(PersistentTicket())
        
bot = EmbarkBot()```
slate zephyr
# torn solar

ah idk about that, well at least you got your vs code fixed now

torn solar
#

ok thanks

#

found the issue lol, bot is supposed to be Bot

dapper cobalt
dapper cobalt
torn solar
#

i had to compare to some old code

lyric solar
viscid hornet
#

hello

#

pressing a button registers that you pressed a button but it doesnt record you pressed the button

#

so the board still thinks it's empty when you make a move

#

and when the board fills and you cant play any more, it just times out

drifting arrow
#

uhh

drifting arrow
viscid hornet
#
[
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
#

set out like this

drifting arrow
#

I got that.

#

So is your issue that it's detecting you're pressing ANY button? and not the ones related to TTT?

viscid hornet
# drifting arrow I got that.

when i press a button, it responds appropriately by changing the label from an invisible character to the player that clicked it

#

but it doesnt make note of that on the board

#

it just says "interaction already responded or smth"

drifting arrow
#

oh

#

Just edit the message.

#

hold up

#

await interaction.response.edit_message(embed=embed, view=self) is what I do.

viscid hornet
#
# terminal
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before```
drifting arrow
#

!paste

viscid hornet
drifting arrow
viscid hornet
drifting arrow
#

So the "message_edit" basically resets the interaction

#

im currently working on trying to send modals XD

viscid hornet
drifting arrow
#

My code is different to yours but has the same concept

viscid hornet
#

what the fuck

drifting arrow
#

allow the user to click many buttons on the same interaction

drifting arrow
#

Want to see some screenshots of it in action?

viscid hornet
viscid hornet
#
# terminal
axololly is playing against altololly in Tic-Tac-Toe.
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Exception: This interaction has already been responded to before```
drifting arrow
viscid hornet
#

full error py Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "c:\Users\user\OneDrive\Desktop\My mum made me do this\Python\Discord\some games\tictactoe.py", line 184, in four await self.input_move(interaction, button, 4) File "c:\Users\user\OneDrive\Desktop\My mum made me do this\Python\Discord\some games\tictactoe.py", line 167, in input_move await interaction.response.defer() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 639, in defer raise InteractionResponded(self._parent) discord.errors.InteractionResponded: This interaction has already been responded to before

drifting arrow
#

Alright i'll debug it now.
Also, it's all 1 script for sharing purposes right?

#

@viscid hornet i'm going to make some changes to improve it as well, do you mind?

viscid hornet
#

so thats those 2 problems solved. i just need to fix the logic for tictactoe

drifting arrow
#

Something like that's happening as well

viscid hornet
#

like checking when theres a win

drifting arrow
#

I'm going to make some modifications to the code, improve it, make it easier for users to use etc.

#

f"Probably a good idea to find new friends.", lol i love all these things

viscid hornet
drifting arrow
#

not you, dingus

#

this is weird. why are you doing this

#

If you remove the self.players from your code, you can do stuff like this. Idk if it's better, but it'd make for cooler variable names.

unkempt canyonBOT
#
Resources

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

viscid hornet
drifting arrow
#

XD

viscid hornet
#

i dont even use player and opponent

viscid hornet
# drifting arrow XD

how do i go about a system to do this? ```py
1 2 3
4 5 6
7 8 9

[(0, 0), (0, 1), (0, 2)]
[(1, 0), (1, 1), (1, 2)]
[(2, 0), (2, 1), (2, 2)]```

#

i want (0, 0) to be 1, (0, 1) to be 2, etc

drifting arrow
#

Also it looks like a list of tuples.

#

So just print out the list number and add 1

viscid hornet
#

each tuple just represents a pair of list indices ```
(x, y) where board[y][x] is valid

#

so you can have board[1][0] which corresponds to the 1st item in the 2nd list

#

but you cant have board[34][-29] because thats not a valid index

leaden olive
#

Can someone help me? lemon_sweat

slate swan
#

interaction.bot is a boolean

#

!d discord.User.bot

unkempt canyonBOT
slate swan
#

Which doesn't have a pool attribute

naive briar
unkempt canyonBOT
#

property client```
The client that is handling this interaction.

Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot) are all subclasses of client.
leaden olive
#

ohh may i use interaction.client?

bright dirge
#

Any examples of quiz bots that I can use for deciding how to handle multiple rounds of a quiz? I'm at the point where my bot can generate one quiz question or fetch data for multiple questions, but not sure what the best way to handle responses and listening for messages across multiple questions would be

leaden olive
formal basin
#

WARNING discord.gateway Can't keep up, shard ID None websocket is 12.6s behind. what does this mean

strange briar
#
import os
import discord
from discord.ext import commands

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

client = commands.Bot(command_prefix='!', intents=intents)


@client.event
async def on_ready():
    print('Logged in')


async def setup():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')
import discord
from discord.ext import commands

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

client = commands.Bot(command_prefix='!', intents=intents)


class ping(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')


def setup(client):
    client.add_cog(ping(client))```

Can anyone help me with this?

[2024-02-05 18:52:57] [ERROR ] discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

formal basin
#

and how to stop blocking

sick birch
#

if you paste all of your code we could take a look

formal basin
#

all my code?

#

like all

#

i have 7 files

#

but

#

i think i know which file it is

sick birch
#

!paste allows for uploading multiple files

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

sick birch
#

Or a GitHub repository if you've got one

sick birch
#

and maybe better_profanity but i'd have to read src code for that

formal basin
#

oh is it this,

#
      host='redis-11943.c56.east-us.azure.cloud.redislabs.com',
      port=11943,
      password='

')
    ```
supple kraken
#

I am trying to implement discord bot using Chat GPT interface

Here's the Code

# App id 1203563046262538250
# public key ec4c2301877d7edca03a8e6a
import discord
import os
import openai

# client = OpenAI()
openai.api_key = os.getenv("GPT_KEY")
token = os.getenv("SECRET_KEY")

# rest of the code remains the same


class MyClient(discord.Client):

  async def on_ready(self):
    print(f'Logged on as {self.user}!')

  async def on_message(self, message):
    print(f'Message from {message.author}: {message.content}')
    if self.user != message.author:
      bot_mentioned = any(user.id == self.user.id for user in message.mentions)
      if bot_mentioned:
        response = openai.completions.create(.      #<--------Possible ERROR 
          model="gpt-3.5-turbo-instruct-0914",
          prompt=message.content,
          temperature=1,
          max_tokens=256,
          top_p=1,
          frequency_penalty=0,
          presence_penalty=0
        )
        channel = message.channel
        messageToSend = response.choices[0].text
        await channel.send('Hello I am Chitti Boom!')


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

client = MyClient(intents=intents)
client.run(token)

I was somehow able to locate the problem to some extent to response = openai.completions.create line but not sure about this

#

My discord bot is not responding to my messages

wintry crown
#

I need help with cogs

#

I added everything I need (I think)

#

But when I run my main file nothing else works

#

none of my cogs work

shrewd apex
#
  • did u load the cogs?
  • verify the cog paths when loading?
  • make sure your cog loading is async following changes in dpy 2.0
  • if its slash command, did u sync?
slate swan
pale zenith
#

inb4 this was generated code

vapid parcel
#

is

broken?

#

Like move_members

#

I have all perms in my test server, but I run the command that wants that perm, it says I don't have that perm. Make me wonder if its bugged or im doing something wrong?

#

Same with mute_members and deafen_members

#

The 3 permissions are just not correct? Like I have all permissions, but still says I don't have them, which is weird

shrewd apex
#

u sure bot has the perm? can u show the exact exception paste the traceback here

vapid parcel
#

sure hold on

#

The bot has the same perms I have.

#
Traceback (most recent call last):
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 1021, in invoke
    await self.prepare(ctx)
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 925, in prepare
    if not await self.can_run(ctx):
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\hybrid.py", line 526, in can_run
    return await super().can_run(ctx)
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 1288, in can_run
    return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\utils.py", line 703, in async_all
    for elem in gen:
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 1288, in <genexpr>
    return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
  File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 2210, in predicate
    raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Deafen Members permission(s) to run this command.```
#

Clearly have the permission too

shrewd apex
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
shrewd apex
#

current channel perms

#

try setting the permissions in channel settings

vapid parcel
#

same issue

#

i gave it all permissions to the channel with my role.

#

Im pretty sure its broken.. what goes off guild permissions? instead of channel permissions?

shrewd apex
#

!d discord.ext.commands.has_guild_permissions try this check

unkempt canyonBOT
#

@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage).

New in version 1.3.
vapid parcel
#

with guild it works...

#

is it better to do guild tho? over channel?

shrewd apex
#

depends if it's a multi server bot i would say yeah it's easier to manage single server perhaps channel is more atomic

shrewd apex
vapid parcel
shrewd apex
#

dont forget to save after adding role and user with relevant perms

vapid parcel
#

Yes ik lol

shrewd apex
vapid parcel
#

ill send a video 😭

drifting arrow
#

How often can we call change_presence?

vapid parcel
#

Category, channel, role all has the perm.

#

Unless you see an issue in it that I truly do not see.. then I think its a bug.

#

All 3 of these give the same error using commands.has_permissions, but when i use commands.has_guild_permissions it works. I think has_permissions is truly bugged with these 3..

shrewd apex
#

is that a hybrid command?

vapid parcel
#

yes

shrewd apex
#

add ur developer role to the channel. did u add that?

vapid parcel
#

i did in another channel

#

ill do it in this channel tho

#

same error

shrewd apex
#

also if ur using guild_only decorator u might as well leave it with have_guild_perms u can raise this issue in the dpy server

drifting arrow
#

It appears my message got hidden away in all the mass messages ;-; #discord-bots message
Anybody know? ;-;

shrewd apex
#

just create a help post

shrewd apex
drifting arrow
#

U sure? I was thinking it'd be a few times a minute

shrewd apex
#

there isn't a limit perse

#

discord ratelimits are dynamic

drifting arrow
#

Would a 20 second cooldown/gap between changes suffice?

shrewd apex
#

seems a bit too frequent imo but u can try should be fine i suppose

vapid parcel
#

I mean, you did see I checked everything... do you see a possible error on my end?

#

Well i see now, it wasn't a channel perm. I feel stupid now. But that is reasonable, I was thinking it would give a differen't error if it wasn't a correct perm for channels. But that is fine.

shrewd apex
#

what was the issue

vapid parcel
#

So channels don't have those 3 perms lol

#

only guild does

#

so it was kinda obvious it was gonna give that error. I am just dumb and didn't read the channel perms.

drifting arrow
#

Trying to make a basic bot.. why the heck isnt this command working? ;-;

from discord import Intents, ActivityType, Activity, Embed
from discord.ext.commands import Bot, command
from discord.ext import commands
from discord.ext import tasks
import asyncio
import requests
import json

# Read server information from servers.json
with open('servers.json', 'r') as file:
    config = json.load(file)
    
class MyBot(Bot):
    def __init__(self, config):
        self.config = config
        self.server_population = []
        super().__init__(
            command_prefix=f"!",
            intents=Intents.all()
        )
        
    @command(name='pop')
    async def server_pop(self, ctx):
        print("POP!")
        embed = Embed(title="Server population information!")
        for pop_info in self.server_population:
            embed.add_field(name=f"{pop_info['server_name']}", value=f"{pop_info['online']}/{pop_info['max']}", inline=False)
        embed.set_footer(text="Footer information")
        
        await ctx.send(embed=embed)
hushed glacier
#

commands.command decorator is for use with Cogs.

drifting arrow
#

this isnt a cog

#

Im not working in a cog :D

hushed glacier
#

exactly, so commands.command decorator won't work

drifting arrow
#

What decorator do I need?

hushed glacier
#

there is none for subclasses of Bot. you usually create an instance of your Bot, and then use the bot.command decorator on regular functions

drifting arrow
#

I've tried @Bot.command() but I get an error

#

I guess I need to modify this bot to have cogs I guess lol

hushed glacier
#

class MyBot(Bot):
    ...

bot = MyBot()

@bot.command('pop')
async def server_pop(ctx):
    ...
drifting arrow
#

Ya wont work for my setup. Ty tho. I'll just make a proper bot with cogs and what not

drifting arrow
#

it started with 4 files, about 75 lines total.

#

;-;

#

now many folders and files later.

hazy dome
#

I am thinking of creating my discord bot with drawing AI, what good drawing free AI with it's API would you recommend to use?

restive cobalt
#

yo guys wanna ask for opinion about slots minigame on my discord bot what is an ideal weight/multiply ratio so the game feels satisfying to play but not too rewarding

            symbols = [':cherries:', ':lemon:', ':tangerine:', ':watermelon:', ':bell:', ':gem:', ':star:']
            weight = (45, 35, 25, 20, 15, 7, 5)
            multiply = (6, 9, 12, 15, 30, 50, 150)
            spin = random.choices(symbols, weights=weight, k=3)
sturdy fractal
#

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.reactions = True
intents.messages = True

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='!',
                         intents=intents,
                         status=discord.Status.online,
                         case_insensitive=True,
                         help_command=None,
                         owner_ids=[1096379840011190272],
                         activity=discord.Activity(
                             type=discord.ActivityType.watching,
                             name="Anime Hub"))
        self.initial_extensions = ["cogs.general"]
        
    async def setup_hook(self):
        for extension in self.initial_extensions:
            try:
                await self.load_extension(extension)
                print(f"{extension} cog has been loaded.")
            except Exception as e:
                print(f"Failed to load extension {extension}. Error: {e}")
    
    async def on_ready(self):
        print(f'We have logged in as {self.user.name}')
        print(self.cogs, self.extensions)
        
        
bot = MyBot()   
    
         

bot.command()
async def greet(self, ctx):
    if ctx.message.content.startswith('$greet'):
        channel = ctx.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await self.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')
        
@bot.command(name='list_cogs', hidden=True)
async def list_cogs(ctx):
    """List all loaded cogs."""
    loaded_cogs = [cog for cog in bot.cogs]
    await ctx.send(f'Loaded cogs: {", ".join(loaded_cogs)}')


bot.run("TOKEN_HERE")
sturdy fractal
thick anvil
#

hey, i was wondering if someone could tell me all the ways a bot can ask for input, like you got slash commands, buttons but is there also something like a prompt?

supple kraken
thick anvil
#

thank you, that is why i did not find it most likely

void pumice
sturdy fractal
random kiln
#

excuse me sir how to i handle to many reqeuts database nextcord

import nextcord
from nextcord.ext import commands
import asyncpg


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


async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(
        "..."
    )


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


@bot.command()
async def hello(ctx):
    await ctx.send("Hello, I am a robot")


bot.loop.run_until_complete(create_db_pool())
bot.run("...")```
this error 
```bash
asyncpg.exceptions.TooManyConnectionsError: too many connections for role ...```
void pumice
sturdy fractal
void pumice
sturdy fractal
#

none of them working

#

i have made a test cmd in cog even it doesnt work

#

none of the cmds work

naive briar
unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

sturdy fractal
#

i forgot intents

sturdy fractal
unkempt canyonBOT
#
List comprehensions

Do you ever find yourself writing something like this?

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

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

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

List comprehensions also get an if clause:

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

For more info, see this pythonforbeginners.com post.

zealous jay
#

Is it possible to send multiple embeds in the same message?

naive briar
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

zealous jay
#

yeah i managed to do it

#

thanks!

naive briar
#

I died

naive briar
sturdy fractal
unkempt canyonBOT
#
List comprehensions

Do you ever find yourself writing something like this?

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

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

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

List comprehensions also get an if clause:

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

For more info, see this pythonforbeginners.com post.

buoyant crater
#

!pypi nacl

unkempt canyonBOT
buoyant crater
#

!pypi pynacl

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

wispy pasture
#

so i have a code i which i want the text of the message to be changed once a user clicks on the button, but i think i am doing something stupid:

start_time = time.time()

class PingView(discord.ui.View):
    def __init__(self):
        super().__init__()
        button = discord.ui.Button(label="Click Me", disabled=False)
        button.callback = self.on_button_click
        self.add_item(button)

    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction = None):
        if interaction is not None:
            # Change the label to "Stop it" when the button is clicked
            button.label = "Stop it"
            button.disabled = True
            await interaction.response.edit_message(content="Button clicked! Label changed to 'Stop it'.", view=self)

@commands.guild_only()    
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
    try:
        latency = bot.latency * 1000
        uptime_seconds = int(time.time() - start_time)

        uptime_days = uptime_seconds // (24 * 3600)
        uptime_seconds %= 24 * 3600
        uptime_hours = uptime_seconds // 3600
        uptime_seconds %= 3600
        uptime_minutes = uptime_seconds // 60
        uptime_seconds %= 60

        uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"

        # Create an instance of PingView and pass it as the view parameter
        await ctx.send(f"### Pong! πŸ“ \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=PingView())
    except Exception as e:
        await ctx.send(f"An error occurred: {str(e)}")```

there r no errors but the text wont update
slate swan
#

button is second

#

and you should not provide a default value for any of those

wispy pasture
#

probably did something more stupid now:

2024-02-06 20:59:18 ERROR    discord.ui.view Ignoring exception in view <PingView timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Click Me' emoji=None row=None>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/main.py", line 247, in click_button
    button.label = "Stop it"
    ^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'label'```
#
class PingView(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label="Click Me", style=discord.ButtonStyle.secondary)
    async def click_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        # Change the label to "Stop it" when the button is clicked
        button.label = "Stop it"
        button.disabled = True
        await interaction.message.edit(content="Button clicked! Label changed to 'Stop it'.", view=self)

@commands.guild_only()    
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
    try:
        latency = bot.latency * 1000
        uptime_seconds = int(time.time() - start_time)

        uptime_days = uptime_seconds // (24 * 3600)
        uptime_seconds %= 24 * 3600
        uptime_hours = uptime_seconds // 3600
        uptime_seconds %= 3600
        uptime_minutes = uptime_seconds // 60
        uptime_seconds %= 60

        uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"

        # Create an instance of PingView and pass it as the view parameter
        view = PingView()
        await ctx.send(f"### Pong! πŸ“ \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)
    except Exception as e:
        await ctx.send(f"An error occurred: {str(e)}")```
slate swan
#

and this error is cause of that

wispy pasture
#

okay okay lemme see my code again, i think i misunderstood it

wispy pasture
#

not sure what to do now tbh bash An error occurred: MessageReference.init() takes 1 positional argument but 3 were given

start_time = time.time()

class PingView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.click_count = 0

    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.click_count += 1

        if self.click_count == 1:
            button.label = "Stop it!"
        elif self.click_count == 2:
            button.label = "Stop it!!"
            await interaction.message.edit(content="I am warning you", view=self)
        elif self.click_count == 3:
            url = "https://www.example.com"  # link button
            await interaction.message.edit(content="Link Button", view=LinkView(url))
            self.stop()  # ending button 

@commands.guild_only()    
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
    try:
        latency = bot.latency * 1000
        uptime_seconds = int(time.time() - start_time)

        uptime_days = uptime_seconds // (24 * 3600)
        uptime_seconds %= 24 * 3600
        uptime_hours = uptime_seconds // 3600
        uptime_seconds %= 3600
        uptime_minutes = uptime_seconds // 60
        uptime_seconds %= 60

        uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"

        # Create an instance of PingView and pass it as the view parameter
        view = PingView()
        message = await ctx.send(f"### Pong! πŸ“ \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)

        # Set the message reference for the view to perform edits
        view.message_reference = discord.MessageReference(message.id, message.channel.id)
    except Exception as e:
        await ctx.send(f"An error occurred: {str(e)}")```
wispy pasture
tiny coyote
#

how do i make a command cooldown in cogs

wispy pasture
#

error:

An error occurred: MessageReference.init() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given```
#

code:

class PingView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.click_count = 0

    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.click_count += 1

        if self.click_count == 1:
            button.label = "Stop it!"
        elif self.click_count == 2:
            button.label = "Stop it!!"
            await interaction.message.edit(content="I am warning you", view=self)
        elif self.click_count == 3:
            url = "https://www.example.com"  # rick astle
            await interaction.message.edit(content="Link Button", view=LinkView(url))
            self.stop()  # end buttons

@commands.guild_only()    
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
    try:
        latency = bot.latency * 1000
        uptime_seconds = int(time.time() - start_time)

        uptime_days = uptime_seconds // (24 * 3600)
        uptime_seconds %= 24 * 3600
        uptime_hours = uptime_seconds // 3600
        uptime_seconds %= 3600
        uptime_minutes = uptime_seconds // 60
        uptime_seconds %= 60

        uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"

        # Create an instance of PingView and pass it as the view parameter
        view = PingView()
        message = await ctx.send(f"### Pong! πŸ“ \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)

        # Set the message reference for the view to perform edits
        view.message_reference = discord.MessageReference(message.id, fail_if_not_exists=False)
    except Exception as e:
        await ctx.send(f"An error occurred: {str(e)}")```
tiny coyote
#
Traceback (most recent call last):
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Naseer\Desktop\That one server\cogs\Fighting_Commands.py", line 305, in fight
    self.bot.cd[user]["F"] = discord.utils.format_dt(now + timedelta(minutes=2), style = "R")
    ~~~~~~~~~~~^^^^^^
KeyError: 502684803783720982

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

Traceback (most recent call last):
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 502684803783720982
#
user = ctx.author.id```
#

I dont understand.?

#

and in my on_message it says

if user not in bot.cd:
                bot.cd[user] = {"F":"βœ”", "M":"βœ”", "C":"βœ”"}

but this is a command

cloud dawn
#

@tiny coyote Is user defined beforehand in the dict?

tiny coyote
#

hmmm

#

Wait i think i figured it out πŸ˜…

#

no nvm i had it

cloud dawn
#

!d discord.MessageReference.from_message

unkempt canyonBOT
#

classmethod from_message(message, *, fail_if_not_exists=True)```
Creates a [`MessageReference`](https://discordpy.readthedocs.io/en/latest/api.html#discord.MessageReference) from an existing [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message).

New in version 1.6.
cloud dawn
tiny coyote
tiny coyote
formal basin
#

how do i put a flask into my discord bot
So I can use it for uptime robot for uptime logging

cloud dawn
#

Well the keyerror comes from a key, in this case the user, wasn't in the dict.

tiny coyote
#
 bot.cd = {}
            if message.author.id not in bot.cd:
                bot.cd[message.author.id] = {"F":"βœ”", "M":"βœ”", "C":"βœ”"}
                print(f"{user} is the given attribute")
#

i changed user and put message.author, no more errors thankfully BUT it doesnt do what its suppose to do

#
self.bot.cd[user]["F"] = discord.utils.format_dt(now + timedelta(minutes=2), style = "R")```
unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a new alternative leveraging structural concurrency; it allows for waiting for a group of related tasks with strong safety guarantees.
tiny coyote
#

no error, i created another command that shows you what the variable holds but it says βœ”

formal basin
cloud dawn
tiny coyote
#

im not sure if this is the issue but i used asyncio.sleep to change the variable back to what it was after the cooldown timer..@cloud dawn

self.bot.cd[ctx.author.id]["F"] = discord.utils.format_dt(now + timedelta(minutes=2), style = "R")
            await asyncio.sleep(120)
            self.bot.cd[user]["F"] = "βœ”"
tiny coyote
cloud dawn
#

So a cooldown function.. or..?