#discord-bots

1 messages · Page 410 of 1

burnt quiver
#

this ain't no python

full mango
#

😬

burnt quiver
#

uh consider .gg/djs

full mango
#

oh okay

jagged sparrow
#

javascript?

full mango
jagged sparrow
#

lol

clear ledge
#

I need the help for my bot

fast osprey
#

what problem are you having?

clear ledge
#

I want to create a Roleplay bot for the community (console) but it's my first time so I'm struggling.

#

and my English is really down the drain

fast osprey
#

Where are you stuck?

clear ledge
#

Uh actually, it's a project that I want to do and I want to know the beginnings, where to start, etc. I don't know if you see what I mean.

fast osprey
#

I don't, you need to be specific about what you have tried, what you want to do and where the problem is

clear ledge
#

Then I don't even know which language would be good, I've been told Js is better but I manage a bit with Py.

fast osprey
#

Well given this is a python community server, you should come here if you decide to use python

clear ledge
#

What are the basics for starting a bot already?

#

I must admit I can't listen to tutorials since most are in English and that's not my language, so there you go.

fast osprey
#
  • Have a good solid understanding of the language you want to use. This is beyond just basics and includes things like classes and async
  • Pick a library you want to use (discord.py, pycord, disnake, etc)
  • Read the getting started guide for that library
clear ledge
#

I only created a Panel system, then I'm struggling.

fast osprey
#

Bots layer on multiple advanced language concepts like classes, async, and API's. It is suggested you learn those things before attempting to make a bot

clear ledge
#

Yeah that's true, can you just tell me if the beginning is good?

fast osprey
#

I have no idea what you're asking by that

clear ledge
#

I can send you my code and you can tell me what is wrong or what is good.

#

?

fast osprey
#

You can send it here if you would like feedback

clear ledge
burnt quiver
#

you should subclass discord.ui.View() so it's much cleaner

clear ledge
#

How is that, excuse me I don't know how to do it I'm starting development lol

fast osprey
clear ledge
patent hull
#

add_command is not a decorator

#

command is, add_command isn’t

compact ivy
#

Alright, I'm using discord.py, latest version, trying to make a logging command
in on_ready I'm getting the channel set with

log_channel = client.get_channel(LOG_CHANNEL_ID)
if log_channel == None:
    print(f"Could not connect to channel id {LOG_CHANNEL_ID}")

That print does not get called if LOG_CHANNEL_ID is valid, and does get called if LOG_CHANNEL_ID is invalid, I've tested this

The following code is used for the logging itself:

@client.event
async def on_message_delete( message ):
    print(f"Message deleted: {message.content}")
     DeletedEmbed = discord.Embed(
        title=message.author.name,
        description=message.content, color=0xFF0000
        )
    await log_channel.send(embed=DeletedEmbed)

The error I get is as follows:
AttributeError: 'NoneType' object has no attribute 'send'

#

Any ideas on what causes this?

#

It's also worth noting that I put log_channel = None is in the global scope, before any functions are called

merry cliff
#

and same thing with on_ready

#

otherwise it might be a local variable

compact ivy
#

that worked perfectly
always those little nuances that I mess up

abstract ibex
#

Are there any Discord bot developers here with a strong background in creating bots? I'd like to have a word with you

burnt quiver
full mango
#

How do you make a button permanently interactive even after restarting the bot?

timber dragon
#

Disable it?

full mango
timber dragon
#

OH

burnt quiver
#

😔

#

d! discord.ext.commands.bot.add_view

full mango
burnt quiver
#

bro

timber dragon
#

Listen for the specific custom_id in the on_interaction event

full mango
#

It's rust 😃

#

(joke)

timber dragon
#

Surely you can listen for events

full mango
#

but I like my code in OOP 😔

timber dragon
#

But you're using djs

full mango
#

the syntax is the same

#

js a different library in which you don't need to sync with the commandtree

timber dragon
#

Ooh

#

Oh god

#

I thought this was the ddevs server lmfao

#

My bad

burnt quiver
#

😭

full mango
#

Like this?

#

(The view timeout is none and the buttons have custom IDs)

timber dragon
#

Ya

#

on_ready can be called multiple times while running though

full mango
timber dragon
#

Did you also send those view with the same custom id

full mango
#

but theres no error

#

Its js saying failed interaction everytime i restart the bot and try

timber dragon
#

It dispatches based on the custom id

full mango
#

like the components of the view having the same custom button?

timber dragon
#

Sure

#

Like the custom_id= kwarg for all the buttons

#

You need to send the same view as you add to the bot

burnt quiver
#

uh then ask here

fast osprey
#

no

burnt quiver
#

Huh

fast osprey
kind trellis
#

Uhhh, which one is better? edit_original_response or edit_message?

fast osprey
#

going through an interaction has much kinder rate limits where possible than alternatives that don't

tender bobcat
#

One thing noted is edit_original_response would edit the new message sent if the interaction already replyed with a mesage, where edit_message can pre-record the message and specifically edit it

kind trellis
#

Does it matter if it's ephemeraled or not?

tender bobcat
#

I am not sure, try refer it from the documentation

fast osprey
#

pretty sure you have to go through the interaction to mess with ephemerals at all

kind trellis
#

So, original?

tender bobcat
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None, poll=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request...
split onyx
#

whats the best discord language??

#

.py, json, disnake, etc??

viscid hornet
#

they're just more human-interpretable methods of interacting with that API

#

also uh

woeful hill
# split onyx .py, json, disnake, etc??

In any of these
Only .py is a file extension of a programming language
json is another file extension to store static config (not really that good nowadays)
disnake is an api wrapper for discord, wrapping raw request into methods of objects

viscid hornet
#

JSON is a data format

woeful hill
#

if you however meant js (javascript), this is a python server, there will not be a an objective answer to X or Y question in X's server

viscid hornet
woeful hill
#

Back to python api wrappers, choose whatever you want, most people use discord.py, some uses py-cord, less use disnake, even 1 or 2 people uses hikari, interactions.py etc

viscid hornet
#
@bot.event
async def on_ready():
    print("ready!")
client.on('ready', () => {
    console.log("ready!");
};
#

pick your poison joeshrug

jaunty cape
#

Real ones use arikawa

stark ingot
viscid hornet
rose hull
#

Hikari is great idk why dpy users hate it so much

woeful hill
#

never seen people hating on it

fast osprey
#

Have literally never seen anyone say anything negative, unless you read "few people use it" as "hate"

woeful hill
#

acknowledgement = hate

severe rampart
fast osprey
#

AFAIK it's one of the few (maybe only) 'mainstream' library that is completely from scratch and not a fork of d.py

#

wildly different design patterns

severe rampart
#

Neat

timber dragon
#

Hikari's design is wild yeah

woeful hill
#

Hikari design is very bright, i mean, it means light

#

-# Pls laugh, i spent 1 hour on that

tender bobcat
white citrus
#

Why doesn't my Discord bot respond to any commands anymore?

fast osprey
#

We'll need more details, preferably code

white citrus
#

Beacuse the main bot is working

fast osprey
#

And how would we know that without seeing your code

woeful hill
#

probably overrode on_message event without process_commands()

white citrus
woeful hill
#

Share it here

#

I'm not the master dev that can solve everything, more people better help

fast osprey
#

Pretty sure you are

torn bone
#

hi anyone who has web scrapped rocket reach please help me

white citrus
fast osprey
# torn bone hi anyone who has web scrapped rocket reach please help me

you will not...engage in any systematic, automated, or excessive data collection or extraction activities (including, but not limited to, scraping, data mining, data extraction, and data harvesting) on or related to our Services or Lookup Information without obtaining our explicit written consent;

fast osprey
white citrus
fast osprey
#

That's how it has always worked

#

Events override the base functionality, listeners layer on top of it

white citrus
#

even if they are application commands?

#

so i have to just add await bot.process_commands(message)

fast osprey
#

No, use a listener

#

@bot.listen instead of @bot.event

white citrus
#

or imorvements?

fast osprey
#

You should understand what this does and why it fixes it

white citrus
#

i will not change very much so i asked if it is that one thing

fast osprey
#

Do you understand what that does

#

If you do, then you should be able to figure out if you need to change anything else rather than being told

white citrus
#

# do stuff here # do not process commands here

i have only db stuff and message stuff

#

so i need just to change the header ig

fast osprey
white citrus
white citrus
#

how can i use this in my bot code?

tender bobcat
#

<any_name:id>

#

Or for animated I think it is <a:any_name:id>

white citrus
tender bobcat
#

For bot emoji only bot can use it I think

timber dragon
#

Only the bot can use the emojis yes

#

No one else

fast osprey
#

Not with that attitude

timber dragon
#

very carefully

blissful kettle
#

hey can someone help me make this

#

like an automated python script, that can be changed via discord bot. Ping me

fast osprey
#

A screenshot doesnt really describe the behavior you want

blissful kettle
#

what does that mean

fast osprey
#

It means you just sending this screenshot isn't much to go on

#

We can't read your mind of what these buttons do

blissful kettle
#

oh I see, so i made a discord automated script via python. then I want to make the python script changeable via discord bot the (j.son file)

#

@fast osprey

#

u get it?

fast osprey
#

No

#

"Discord automated script" doesn't mean anything

blissful kettle
#

ive written a code via python for the discord automated messages and i want to make a bot like the one ive sent (I want to change the json file via discord bot

fast osprey
#

What is "discord automated messages"

blissful kettle
fast osprey
#

It is against discord developer policy to target users with advertisements or marketing

blissful kettle
#

oh I see

#

thank u

#

so basically the pic that I have sent is a custom made UI? if im not mistaken

fast osprey
#

No, it's a usage of built in UI components discord offers to bots

blissful kettle
#

sorry, im new to coding. I just coded this for 17 hrs and started to learn python. I'll delete this cuz it violates discord's TOS

fast osprey
#

Bots layer on lots of advanced topics. I would not recommend making one until you complete some more focused projects and learn the fundamentals

#

And also familiarize yourself with the TOS and dev policy

blissful kettle
fast osprey
#

It depends on what you learned and what practices you used

jaunty cape
fair topaz
#

too many hearts

mild zephyr
#

simple question. is there a "standard" way to format a discord project? "specific" ways to name folders

wanton current
#

no

#

but many people have "cogs" folders, "utils", etc.

tender bobcat
#

Or ext

fast osprey
#

cogs have nothing to do with folders/files

split onyx
fast osprey
#

It doesn't

#

cogs are classes. You can put a million classes in a file.

#

It's a very common and incorrect misunderstanding that cogs and extensions mean the same thing

split onyx
#

and this "misunderstanding" has no impact on the bot itself when using cogs

fast osprey
#

People almost always parrot what they see from some random youtuber. That doesn't mean it's right just because a lot of people say it

#

organizing things into cogs and file structure are two entirely separate exercises

split onyx
#

the cogs are using to call the files in that structure

#

Its like taking caramel and apples for caramel apples and saying that have nothing to do with each other for caramel apples.

fast osprey
#

You dont' "call" files

split onyx
#

im aware

fast osprey
#

and yet you're saying it

split onyx
#

you call the class in that file

#

and yet you understand what im saying

fast osprey
#

You also don't call classes

split onyx
#

mhm

timber dragon
#

Fml

deft sundial
#

I'm trying to make my bot's slash commands work in DMs and GCs but it simply doesnt work only in other servers

class CustomBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        intents.messages = True
        intents.guilds = True
        intents.dm_messages = True  
        super().__init__(command_prefix='!', intents=intents)
        
    async def setup_hook(self):
        await self.tree.sync()

i tried
Adding dm_permission=True to commands (got TypeError)
Using @app_commands.guild_only(False) (got AttributeError)
Setting self.tree.copy_global_to = None
Added DM intents

any advice on this problem? many thanks MrCoffee_Happy

viscid hornet
unkempt canyonBOT
#

@discord.app_commands.allowed_contexts(guilds=..., dms=..., private_channels=...)```
A decorator that indicates this command can only be used in certain contexts. Valid contexts are guilds, DMs and private channels.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored...
viscid hornet
#

!d discord.app_commands.allowed_installs

unkempt canyonBOT
#

@discord.app_commands.allowed_installs(guilds=..., users=...)```
A decorator that indicates this command should be installed in certain contexts. Valid contexts are guilds and users.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored...
viscid hornet
#

i have a helper deco that does both of these for me

deft sundial
blissful kettle
#

yes yes

#

educational purpose only

#

aight bet

tender bobcat
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

fast osprey
#

"s3lfb0ts"...honestly? Really? Is this tiktok?

cosmic elk
#

Can someone help me make my “first” discord bot? I say “first” in quotes bc I’ve made part of a bot but not a full one… if anyone has tutorials please feel free to send them my way… the main problems I am having is the best way to start and also how to use custom prefixes… like I don’t want the command to be ‘/command’ but I want it to be ‘%command’

#

Anyone who responds plz ping me! Thx in advance!

#

❤️

tender bobcat
#

You would have to show your code

cosmic elk
tender bobcat
tender bobcat
#

Also don't trust any DM request because no one would be able to cross check if they are doing something malicious

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands...
tender bobcat
#

You can set the prefix there

woeful hill
jaunty cape
#

Bro

jaunty cape
#

Do you see their server tag bro 😭

tender bobcat
celest pelican
#

a) Don't spam this across channels, b) this is a Python server

woeful plinth
#

are you even old enough for discord?

#

also what made you think that people from a python server would help you with c++?

woeful plinth
#

codebox?

#
print('oo textt')
#

this?^

#

you wanna learn how to do the codebox?

#

where code gets color?

fast osprey
#

what's your objective here?

timber dragon
#

!d discord.Message.system_content

unkempt canyonBOT
timber dragon
#

if you're using discord.py, it constructs the content for you there

split onyx
#

im interested in seeing some of the most "advanced" discord bots does anyone know any

#

and open source would be cool

burnt quiver
finite salmon
timber dragon
#

Have some more!

split onyx
#

Thank you all

jaunty cape
#

Let’s go bro I’m rocking the Python discord emblem

timber dragon
#

Snek

viscid hornet
young dagger
#

Working on a verification bot that contacts an API, changes the profile picture and then lets them in

fast osprey
#

They have oauth it seems btw

woeful plinth
#

well ig for inappropriate profiles

young dagger
fast osprey
#

Yeah authorization flows like this should absolutely use oauth when it's offered, way more secure and easier for both parties

woeful plinth
young dagger
woeful plinth
#

so if it cant change the pfp then that means its a bot?

young dagger
woeful plinth
#

wait explain

young dagger
#

Well, you need to complete the verification within a specified time

wise mica
woeful plinth
#

oooh

fast osprey
#

Wait...this is just to verify someone isn't a bot? Not to link an account?

#

Just use an interactive captcha service

young dagger
#

Can be used for different purposes

fast osprey
#

If you want to link accounts, use oauth. If you want to verify a human, use an interactive service

tender bobcat
#

^^

tidal sentinel
#

Hello,

Can i edit messages via ID

#

Is it possible?

woeful hill
#

why would you only store the message id in the view

tidal sentinel
#

After they select i want to change embed with another select class

young dagger
fast osprey
#

Just because people do it doesn't mean it's good. It means it's easy

#

That method doesnt do either of the things I described well. It just does it easily

fast osprey
wise belfry
#

Does anyone know how to connect my cog commadn to my main .py all help is appercited and I will sendwhatever you need to help me. Thanks 🙂
-# please ping me if you can assist me.

wise belfry
#

this is my main with my cogs.

full lily
#

yeah so you need to tell your bot where the cogs are actually located, and load them. They don't load on their own

wise belfry
full lily
#

Here's the relevant method

#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners...
full lily
#

somewhere in main.py you need to run this

wise belfry
full lily
#

yeah just ping me later i might be on

stark ingot
#

They have not stated what library they use so the above docs may be inaccurate.

stark ingot
#

There is no deadline to delete discord messages. Except for ephemeral messages, which require the use of an interaction token that expires after 15 minutes. This is universal to any language/library

timber dragon
#

bulk delete is limited to 14 days though

safe mist
#

can you only send 1 embed per message now?

#

no matter what i do, i can only get the 1st embed to show, here is my raw body:

{
    "embeds": [
        {
            "title": "Overall",
            "fields": [
                {
                    "name": "**Seasonal Wins**",
                    "value": "944 wins in 1322 matches (71.4%)",
                    "inline": false
                },
                {
                    "name": "**Seasonal Kills**",
                    "value": "5,722 Kills, 15.14 KD, 4.33 KPM",
                    "inline": false
                }
            ]
        },
        {
            "title": "Gamemodes",
            "fields": [
                {
                    "name": "**Solo Wins**",
                    "value": "487 wins in 525 matches (92.8%)\n4,226 Kills, 111.21 KD, 8.05 KPM",
                    "inline": false
                }
            ]
        }
    ]
}
#

sending both individually works fine

fast osprey
#

What the

safe mist
# young dagger Show full code
async with self.session.request(
    method="POST",
    url=f"https://discord.com/api/v10/channels/{channel_id}/messages",
    headers={
        "Authorization": f'Bot {token}',
        "Content-Type": "application/json"
    },
    json={
        "embeds": [embed1, embed2]
    }
) as request:
    data = await request.json()

The value of embed1 & embed2 are the exact same as my previous message. My current workaround is just to send them as 2 individual messages like this (which works fine so I don't think theres any issue with the embed structures):

for embed in [embed1, embed2]:
    async with self.session.request(
        method="POST",
        url=f"https://discord.com/api/v10/channels/{channel_id}/messages",
        headers={
            "Authorization": f'Bot {token}',
            "Content-Type": "application/json"
        },
        json={
            "embeds": [embed]
        }
    ) as request:
        data = await request.json()
tender bobcat
full lily
#

whats up guys

tender bobcat
#

Perfectly fine

full lily
#

good

#

that's the best way to be

tender bobcat
#

I believe so
Not like I can be a super human being, nor being such can be consider good anyway

vapid parcel
#

not possible to put a video inside of an embed still correct?

full lily
vapid parcel
#

aight figured lol

#

L discord fr

#

I remember not being able to set the video in an embed for awhile, but checking again just incase I missed something

full lily
#

although....

#

I see some screenshots of what might be just that

#

oh i wonder if its uh

#

like youtube, steam, twitter preview

#

facebook

vapid parcel
#

thats website embeds, which discord bots don't use those embeds

#

websites have special embeds or something where the API does not let you access ig

full lily
#

yeah seeing that now. The screenshot mislead me

vapid parcel
#

its not hard to do logic to avoid conflicts, but all being in embeds looks better than via content

#

personal opinion ^

tender bobcat
#

I mean technically you can format such?

#

Also have you checked component v2

tender bobcat
#

Which isn't API oriented

vapid parcel
vapid parcel
tender bobcat
#

Oh, I mean check whether component v2 is capable of that

vapid parcel
#

oh let me check

tender bobcat
#

You can update dpy to the pr commit

#

To use a unstable version of it if necessary

vapid parcel
tender bobcat
#

Fair

vapid parcel
#

from what I am seeing you can't do it in v2 either unless im reading it wrong

#

I don't think its ever coming to discord for security reasons maybe, but I have no clue why

tender bobcat
#

I believe you can use media gallery component for that

#

Other only mention as "media", including official, which is quite vague

#

And example usually only provided as image

vapid parcel
#

i am just very certain it won't be in v2 because they don't show examples of videos either, they only show images / attachments

#

and if discord makes something new, they USUALLY show the preview

tender bobcat
#

And it would be weird to say image or media if it only support image

#

Display images and other media

#

So you could maybe try it in the future, maybe something to look for

#

Doesn't mean it can be directly trusted, but ye

vapid parcel
tender bobcat
#

Instead of just speculation

#

Which is what we doing

#

I am not saying they make the feature exist, but they probably have verified that the feature exist

stark ingot
#

Videos work fine

tender bobcat
vapid parcel
#

How to gift an SKU to another person..? as developer_gift is a thing?

full mango
#

this embeds look cool

burnt quiver
#

It's just components v2

viscid hornet
white citrus
#

Hey i need some helping with my host. Basicly he is not autoupdsting the files

woeful hill
#

Wdym by not auto updating the files

white citrus
woeful hill
#

Yeah what about that that doesnt work

#

What have you done, what it does, why is it not working

white citrus
#

It has the git username a git Access token and the git repo adress

woeful hill
#

Still not enough of an answer, what have you done, also if you do it on bot start just do a quick git pull before starting the bot

woeful hill
#

So i have to guess how you do it

#

Sure

white citrus
# woeful hill Sure

if [[ -d .git ]] && [[ "1" == "1" ]]; then git pull; fi; if [[ ! -z "" ]]; then pip install -U --prefix .local ; fi; if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/bot.py

#

thats the startup

white citrus
fast osprey
#

Has nothing to do with python

white citrus
fast osprey
#

That doesn't mean your question is python related. Where's the python there

white citrus
#

...bin/python...

fast osprey
#

"I'm running my discord bot on a Samsung smart fridge, my fridge is broken so help me fix my fridge"

white citrus
#

Why do you make life difficult instead of helping?

fast osprey
#

Because this isn't the place for what you're asking

white citrus
#

either help or stay out of it

fast osprey
#

Or you could ask where you're supposed to

white citrus
#

Than just say, please ask in ....

#

Is it so hard?

fast osprey
#

Nah I'm good

viscid hornet
white citrus
viscid hornet
white citrus
quick gust
#

You should try contacting the hosting support

viscid hornet
white citrus
viscid hornet
#

what website is this?

white citrus
#

XeroHost

viscid hornet
#

does that container have a git repository

white citrus
#

Yeah

tender bobcat
#

Did you put a valid git access token in there

white citrus
#

Yeah a Personal Access token

woeful hill
#

Was trying to debug that bash but seeing that image, the host is auto update as it said, so go to their server for help lol

quick gust
#

Not a very good hosting service then

woeful hill
#

Then you shouldn't use that hosting service

#

Since even them don't know what theyre doing

white citrus
#

They now but it is not fixed yet

#

There have been several attempts to solve the problem

#

So I thought someone here could help me

tender bobcat
#

It's clearly not a python code issue, and therefore you shouldn't ask herepithink

#

They should be the best in knowledge to understand this

white citrus
#

where else?

tender bobcat
#

Your hosting provider

quick gust
#

That question has already been answered. Their support server

tender bobcat
#

Who provide this specific feature and have issue with the specific feature

white citrus
#

So no one can help here

quick gust
#

They know how their hosting works and if they don't, then you shouldn't be using that hosting service anyways

fast osprey
#

Really it shouldn't be the responsibility of the hosting service to abstract things away from you; they're just giving you a vm and running the infra. Any automation should be fully in your control, ideally through something like a process manager

severe rampart
#

interesting

#

feels very similar to templates though

timber dragon
#

"AI server builder" come on..

tender bobcat
#

Seem very unnecessary pithink

#

If they know how to add your bot, they probably know how to setup a server in such way that AI can

digital rampart
#

Is a time focused tool. I know plenty of people tired of setting up servers. And templates lack customization . Thanks for your opinions tho.

fast osprey
#

Read documentation and learn systems: drakeNo

Hope a random LLM guesses right what you want: drakeYea

tender bobcat
#

Tired of setting up server:

How many time do you have to setup server🥴
Also server template already exist if they are tired of setting up server

timber dragon
#

Templates can create channels and roles.. basically what you're doing?

tender bobcat
#

Also did you setup role permission for each channel? Just making sure

timber dragon
#

?? You decided to showcase something in a public channel where anyone can say whatever they want...

Criticism isn't equal to toxicity or lame or "no life".

#

Yep deleting your messages is totally the right thing to do 473513617950638081 prettythumbsup

timber dragon
tender bobcat
#

Oh it just reload

#

My discord just haven't load the change for whatever reason before I go to a different channel and back

#

They also left so well

timber dragon
#

Amazing

woeful hill
#

me when i cant handle truth 🥀

tender bobcat
#

lol

split onyx
#
# -------------------- Imports -------------------- #
import os
import asyncio
import logging
from dotenv import load_dotenv
from pathlib import Path

import nextcord
from nextcord.ext import commands

from bot.config import DEFAULT_SETTINGS
from bot.database.db import init_db

# -------------------- Logging -------------------- #
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    handlers=[
        logging.FileHandler('bot.log', encoding='utf-8'),
    ]
)
logger = logging.getLogger('bot')

# -------------------- Load Environment -------------------- #
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
    raise RuntimeError("❌ DISCORD_TOKEN not found in .env")

# -------------------- Init Database -------------------- #
init_db()

# -------------------- Intents -------------------- #
intents = nextcord.Intents.default()
intents.message_content = True

# -------------------- Bot Class -------------------- #
class DiscordBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cog_dir = Path("cogs")

    async def setup_hook(self):
        await self.load_cogs()

    async def load_cogs(self):
        for cog_file in self.cog_dir.glob("*.py"):
            if cog_file.stem.startswith('_') or cog_file.stem.startswith('__'):
                continue
            cog_name = f"cogs.{cog_file.stem}"
            await self.load_extension(cog_name)
            logger.info(f"✅ Loaded cog: {cog_name}")

# -------------------- Bot Instance -------------------- #
bot = DiscordBot(
    command_prefix=DEFAULT_SETTINGS["general"]["default_prefix"],
    intents=intents
)

# -------------------- Run Bot -------------------- #
async def main():
    await bot.start(TOKEN)

if __name__ == "__main__":
    asyncio.run(main())
#

No terminal print loaded_cog message. I have tried multiple variations of these same actions and im not sure why its not loading the cogs or sending any success message.

#

Also I am not familiar with nextcord as much but I dont see what would need to change.

woeful hill
#

you set the logger to log into a file 🤔

split onyx
woeful hill
#

so have you checked the file

split onyx
unkempt canyonBOT
split onyx
#
[2025-06-24 10:37:34,044] WARNING: Shard ID None heartbeat blocked for more than 530 seconds.
Loop thread traceback (most recent call last):
  File "C:\Users\braed\Desktop\Nextcord Bot\main.py", line 65, in <module>
    asyncio.run(main())
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 195, in run
    return runner.run(main)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 712, in run_until_complete
    self.run_forever()
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 683, in run_forever
    self._run_once()
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 2004, in _run_once
    event_list = self._selector.select(timeout)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\windows_events.py", line 446, in select
    self._poll(timeout)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\windows_events.py", line 775, in _poll
    status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)```
split onyx
#

anyways I tried to just keep the basic stuff until I could identify the problem for now

stark ingot
#

It seems you have blocking code. The main 3 culprits are

  • Image manipulation
  • Non-async API requests
  • Non-async database calls
brazen raft
#

Or just a busy sync loop

stark ingot
tender bobcat
#

I think most common issue is beginner not listening to the advice of not picking discord bot as first project

severe rampart
#

you could do asyncio.run_in_executor()

#

i think maybe; my memory on that isn't too great atm

#

It's been a long time since i've had to do that

split onyx
#

ive awaited the init_db() in main instead that didnt help

#
[2025-06-24 12:43:15,100] INFO: logging in using static token
[2025-06-24 12:43:15,101] INFO: Allowed 1 rate limits to be garbage collected.
[2025-06-24 12:43:15,606] INFO: Shard ID None has sent the IDENTIFY payload.
[2025-06-24 12:43:15,754] INFO: Shard ID None has connected to Gateway: ["gateway-prd-us-east1-d-g0k9",{"micros":69868,"calls":["id_created",{"micros":788,"calls":[]},"session_lookup_time",{"micros":1255,"calls":[]},"session_lookup_finished",{"micros":14,"calls":[]},"discord-sessions-prd-2-48",{"micros":67412,"calls":["start_session",{"micros":55146,"calls":["discord-api-rpc-5c89788f78-9xvzh",{"micros":41836,"calls":["get_user",{"micros":5256},"get_guilds",{"micros":3472},"send_scheduled_deletion_message",{"micros":14},"guild_join_requests",{"micros":3},"authorized_ip_coro",{"micros":11},"pending_payments",{"micros":1066},"apex_experiments",{"micros":3},"user_activities",{"micros":2},"played_application_ids",{"micros":1}]}]},"starting_guild_connect",{"micros":44,"calls":[]},"presence_started",{"micros":5784,"calls":[]},"guilds_started",{"micros":62,"calls":[]},"lobbies_started",{"micros":1,"calls":[]},"guilds_connect",{"micros":1,"calls":[]},"presence_connect",{"micros":6351,"calls":[]},"connect_finished",{"micros":6354,"calls":[]},"build_ready",{"micros":19,"calls":[]},"clean_ready",{"micros":0,"calls":[]},"optimize_ready",{"micros":1,"calls":[]},"split_ready",{"micros":0,"calls":[]}]}]}] (Session ID: 6429e57d07e65395fbc463f279cc3658). Resume URL specified as wss://gateway-us-east1-d.discord.gg
[2025-06-24 12:44:05,281] WARNING: Can't keep up, shard ID None websocket is 49.7s behind.
[2025-06-24 12:44:06,879] WARNING: Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
  File "C:\Users\braed\Desktop\Nextcord Bot\main.py", line 66, in <module>
    asyncio.run(main())
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 195, in run
    return runner.run(main)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 712, in run_until_complete
    self.run_forever()
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 683, in run_forever
    self._run_once()
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 2004, in _run_once
    event_list = self._selector.select(timeout)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\windows_events.py", line 446, in select
    self._poll(timeout)
  File "C:\Users\braed\AppData\Local\Programs\Python\Python313\Lib\asyncio\windows_events.py", line 775, in _poll
    status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)

#

idk

stark ingot
#

What library are you using to connect to your database?

split onyx
#

I switch to aiosql to see if that was an issue as well

woeful hill
#

is sql a library

tender bobcat
#

!pypi sql

unkempt canyonBOT
tender bobcat
#

I guess so...

vapid parcel
#

so why when doing SKUs can you only have User Subscriptions or Guild Subscriptions, you aren't allowed to do both on the store?

#

Not really related to this server, but maybe someone in here might know..

raw arrow
#

Anyone got any suggestions

fast osprey
#

Just use server templates?

fast osprey
#

Because that seems to be what their code is doing

viscid hornet
viscid hornet
#

!d discord.Template pithink

unkempt canyonBOT
#

class discord.Template```
Represents a Discord template.

New in version 1.4.
viscid hornet
#

!d discord.Guild.create_template

unkempt canyonBOT
#

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

Creates a template for the guild.

You must have [`manage_guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_guild) to do this...
viscid hornet
#

thank god for dpy having normal names

merry cliff
#

lol

kind olive
#

Hi, looking to sell some Discord bots made with Pycord then compiled using Nuitka for compatibility and privacy of my source code. Now I am into keeping the check logic for the bot to be safe enough against reverse-engineering. I heard that storing the SERVER_ID directly allow some people to access it from the memory. What about this logic:

# A hashed + salted server ID.
SERVER_ID = "825c491944682dae4ee43cf82f7f6da5d187eda3b8a5471cfba3b9a9f3b3f9b7"


# A function to get the salt, which is should never stored;
# the salt is obtained by converting unicode code points to chars.
def salt():
    part1 = [codes here]
    part2 = [codes here]
    part3 = [codes here]
    return "".join(chr(n) for n in part1 + part2 + part3)


# A function to convert a text into a hash with the required salt.
def hash(text: str) -> str:
    return hashlib.sha256((salt() + text).encode()).hexdigest()

Then compare the bot that the bot in and the and SERVER_ID in the hash function. This way: Never storing the actual ID, instead a hashed+salted server ID string, and the salt itself is also non stored. What do you think? Hope this works and make things at least safer.

sick birch
#

there isnt really anything crazy you can do with an id

kind olive
#

A client comes, give me their server ID, I hash it with salt, include it in the bot source, and then compile. Got it?

#

When someone is looking at the memory and could find and modify the SERVER_ID variable, the bot will hash it with salt and compare with existing guilds.

Look at this:

    for guild in bot.guilds:
        if hash(str(guild.id)) == SERVER_ID:
            logger.debug(f"Bot is connected to the target guild: {guild.name}")
            break
    else:
        logger.warning("Bot isn't connected to the target guild; logging out.")
        await bot.close()
sick birch
#

hashing the id doesnt really do anything

#

if anything you're just wasting cycles

kind olive
sick birch
#

if you hand over your code they can change anything and do whatever they want with it, given they're determined enough

kind olive
#

How? The if hash(str(guild.id)) == SERVER_ID: is editable?

sick birch
#

sure. they have the executable, they can change any instruction they want to

#

can also modify any piece of memory they want to

kind olive
#

What tools/methods?

sick birch
#

anything to read and write to binary files

#

as for viewing and modifying process memory, not sure. i've never done that but im sure there are tools

kind olive
sick birch
#

i guess? hiding the ID does nothing

#

its their own server, they know the ID. and even if it wasnt an ID isnt good for much without context

#

you're treating the ID like it's some super secret piece of information when its not

kind olive
sick birch
#

it barely makes a difference

kind olive
#

Ok here we go, they knew it's hashed with SHA256, they tried to hash another ID and replace. Now the check logic hashes both IDs (the one the bot in and the one given) using salt.

sick birch
#

dont even have to do all that

kind olive
#

):

sick birch
#

if you cared enough just find where in the bytecode the comparision happens and remove it

fast osprey
#

why try to sell packaged code/software? Just sell SaaS

sick birch
#

just leave it be and spend this effort on making other features or something

fast osprey
#

Trying to obscure code you're giving to people is obscenely fruitless when there's a clear other business model

sick birch
#

if you turn it into a service theres pretty much nothing they can do

kind olive
sick birch
#

no point beyond just compiling your code if you're trying to prevent reverse engineering

#

diminishing returns, waste of time and effort

kind olive
fast osprey
#

Wouldn't just using a service already running for them be even easier?

sick birch
#

real

kind olive
fast osprey
#

It's a discord bot? So just run it?

sick birch
jaunty cape
#

My guy can’t they just remove the lines that prevent the bot from being used

sick birch
#

but just have them fill out a google form or something explaining what bot they need, send them the bot's invite link, and that's that

kind olive
#

I still think download and run easier, I don't want to host myself, not for saving that 1KB RAM, but I don't have 24/7 electricity.

fast osprey
#

How is that easier for your users to download, run, and figure out hosting themselves

#

it's easier for you, not them

kind olive
#

My target clients are very familiar with that, you don't know about Arab server owners. Btw everything in the bot is automatic, all they have to do is passing the token in a .json config file.

jaunty cape
#

Bro why would they hire you to make a bot for them if they could write it themselves

fast osprey
kind olive
jaunty cape
#

So they’re very familiar with running Python files but can’t write it somehow?

fast osprey
#

If they're not programmers, why are you worrying about them decompiling?

jaunty cape
#

are we serious rn

kind olive
fast osprey
#

If you're worried about reverse engineering, do SaaS

#

that's the answer

kind olive
#

The files

jaunty cape
#

Get a load of this guy

kind olive
#

Guys I am just taking advices, I am not saying I am 100% right.

#

I got into some points I didn't think about after this

#

This is what I am looking for

#

ONLY

kind olive
#

No Python needed

fast osprey
#

Once you hand it off to users, it's not yours at that point. If you don't want them to pick it apart, don't give it to them

#

Or charge them more and act like a programming contractor where they own the product you build

jaunty cape
#

Right some server owner is definitely gonna run a random executable from a guy with 1 commit in a private repository

fast osprey
#

I mean I would never pay someone to make something, obscure me from seeing what it does while they refuse to run it as a service for me. Incredibly naive buyer if they'd accept that

kind olive
kind olive
fast osprey
#

It's not fine, if they accept that they're fools

#

and are just begging to get ripped off

kind olive
jaunty cape
#

What does them being Arab have to do with your product

#

My guy if you don’t want your product to be reverse engineered then just write the bot in Go

kind olive
jaunty cape
#

Pyinstaller doesn’t actually compile your program

kind olive
#

I use Nuitka, it's designed for hiding the source code.

fast osprey
#

idk you do you. You can't reasonably have a result where you give them a black box and prevent them from opening it. Your options are SaaS, act on contract and sell the code, or pretend there's a third option

kind olive
#

Pyarmor make it even harder, but it's not for commercal use unless paid

fast osprey
#

From a purely business perspective, you make more money with SaaS

kind olive
#

Btw you guys forgot the trust concept. Even popular programs are compiled and at the end they found out that they steal info from you.

#

Like that anti virus program i forgot it's name

#

What i am doing is very common, acts like activation.

fast osprey
#

Popular programs are written by swarms of highly paid, experienced engineers

#

not a rando asking for help in a discord server

sick birch
#

yes, we're aware of the discord bot buying/selling "business" space. the consumers there are not technical, and most of the products are unfortunately sloppy.
for your case in particular, you really only have 2 options

  • hand over an executable to end users, but be 100% fine with them doing whatever they want with it
  • Run a SaaS and charge a recurring fee to host infrastructure and code
#

for your case in particular, there is a negligible difference whether you hash your ID or not. your efforts are better spent elsewhere

kind olive
#

I know how to build trust in my case because the clients are targetted not random

fast osprey
#

What does trust have to do with this

sick birch
#

i also don't see why it's your problem if they decide to run the bot on multiple servers

fast osprey
#

your entire point here is on not trusting them

sick birch
#

give them the source code, collect your money and be on your way

jaunty cape
#

There’s never a dull moment in this channel

#

I now declare myself the mayor of #discord-bots and am seceding this channel from the rest of the server

kind olive
stark ingot
#

Is each bot different?

fast osprey
#

Then you don't trust them

#

I know how to build trust in my case

I am worried about them doing something I specifically tell them not to

what

sick birch
jaunty cape
#

Build trust my ass

kind olive
#

Ok guys ur right ,

#

Maybe just letting them have a control panel in the purchase ticket to control the bot.

fast osprey
#

Running it SaaS isn't going to be as complicated as you might think

sick birch
stark ingot
kind olive
jaunty cape
#

Idk about you, but I wouldn’t buy from someone that’s just giving me a random executable and has one commit in a private repository

#

That’s just me though

stark ingot
#

TBH that is not relevant to the question/problem

sick birch
#

its not and the consumer base doesnt care either

fast osprey
#

We've already established that these customers are somehow incompetent enough to accept a product like this while also being smart enough to decompile code

sick birch
#

truly an interesting set of people

#

anyway.. you need to be fine with people doing whatever they want with your code

#

you dont really have a choice

kind olive
#

Okay fine

fast osprey
#

Another thing to consider is that you can license this product that you give them, and then you can sue the pants off of them if they do try to redistribute it. Rather than trying to lock it down (which won't work)

kind olive
#

I am here to take opinions only

sick birch
#

its the tradeoff you pay for not having your own infrastructure

kind olive
#

Thank you all

#

I will be making it more open source and not locked for clients.

fast osprey
#

Good luck prettythumbsup

fast osprey
#

looks like an unstable connection

young dagger
#

That is normal

tender bobcat
#

It's a little bit too frequent than nornal

timber dragon
#

Every minute isn't normal lmao

fast osprey
#

You probably don't want to be using on_ready for anything. It runs repeatedly and randomly

#

If you know then why are you trying to do it thonk

#

Will need to see more of the code

quick gust
#

!paste paste it here and send the link

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.

fast osprey
#

It's not

#

Any other code in that file (or potentially others) could interfere with what you sent us

#

That's how python works

#

We'll need to see the rest of the file at minimum

lyric echo
#

someone knows maybe how to fix old af bot in discord.py (which was done in times we were all scared it will be deleted tbh…) to work right now? i get such things:

hacknorris@fedora:~/Pobrane/tux-update-cogged$ python3 main.py 
/home/hacknorris/Pobrane/tux-update-cogged/main.py:40: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(command)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2025-06-26 16:13:25 INFO     discord.client logging in using static token
2025-06-26 16:13:27 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 0e0f8ffcfb835ded878a5ad615e20845).
2025-06-26 16:16:55 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "man" is not found
fast osprey
lyric echo
#

how to download 1.0 then?

fast osprey
#

You don't

#

The API is turned off

lyric echo
#

so bot dead, yep?

fast osprey
#

You upgrade it to 2.x

lyric echo
#

if i need to rewrite like 2/3 code i'd rather make it dead…

quick gust
fast osprey
#

Nobody said it would be 2/3

timber dragon
#

v1 to v2 isn't that big of a change

fast osprey
#

At least give it a read

lyric echo
#

(that flask thingy to keep uptime on replit when it was still free)

#

YES

timber dragon
#

still not much

fast osprey
#

Extensions, soheab

timber dragon
#

only two changes for extensions

quick gust
#

You shouldn't

fast osprey
#

Yeah not recommended

lyric echo
#

everyone does that

quick gust
#

Doesn't mean its the right thing to do

timber dragon
#

no?

fast osprey
#

A lot of people do, and a lot of people blindly copy paste from YouTube mouth breathers without reading docs

woeful hill
#

everyone = you and the other person

lyric echo
#

how you did await without def?

timber dragon
#

or just use setup_hook

lyric echo
#

you did :(

timber dragon
#

why is that bool even global..

#

then assign a value above?

quick gust
#

Doesn't excuse bad bot structure. If you're having issues with something, ask for help

woeful hill
#

why do you need to make it global

lyric echo
#

i also always make globals tbh…

timber dragon
#
basic = "python"
print(basic) # python
basic = "learn it"
print(basic) # learn it

def change_basic():
  basic = "please!"

change_basic()
print(basic) # please!
fast osprey
woeful hill
#

all of this fool proof to make it not run a second time can just be bring to setup_hook

lyric echo
fast osprey
#

Could even do it with advanced setup by starting the event loop yourself and then loading extensions, setup_hook isn't the only way but repeatedly checking some bool at random intervals for the entire lifecycle of the bot ain't the play

timber dragon
#

💀

quick gust
#

You definitely do not need to be making so many global variables

lyric echo
#

sometimes it's required to keep actual status

timber dragon
#

especially when you can assign attrs to the bot instance

fast osprey
#

It's never required

lyric echo
#

for example. or like a constant data…

#

yeah, this too

timber dragon
#

bot instance can store state too

fast osprey
#

It's a crutch for not making proper use of objects

quick gust
woeful hill
#

c programmer

fast osprey
#

I made shitloads of globals when I was starting in python because it's what you get when you Google stuff like "share value in python" and it's "intuitive"

lyric echo
#

same

fast osprey
#

And the subtext there is that you think it works until it doesn't, and you have no idea why

lyric echo
#

and now at me stopped working due to @#%#^@$^$% discord.py

woeful hill
#

when the problem is yours but you want to blame others

lyric echo
#

no because earlier it was working without problems…

timber dragon
#

oh no! changes!

fast osprey
#

Discord discontinued the backing api. It's not the library's fault

woeful hill
#

welcome to being a dev ig

fast osprey
#

And you can't reasonably expect a service to promise upholding every version of an api they ever published for perpetuity

lyric echo
woeful hill
#

yeah and youre making like a literature book or something

fast osprey
#

Then you'll need to adjust your expectations when the thing you build is on top of a live service you don't control

viscid hornet
lyric echo
woeful hill
#

technology evolves

#

fun fact

quick gust
fast osprey
#

Which is just a wrapper over the discord api

viscid hornet
viscid hornet
quick gust
#

yeah pull off an andrew tate

lyric echo
woeful hill
#

one of the problems is too much vulnerabilities since you dont want to update it

viscid hornet
lyric echo
#

i mostly run it for myself and if there was a token it was resetted n times…

viscid hornet
quick gust
#

deserved

viscid hornet
fast osprey
#

dpy hits a version of discord's api, discord discontinued the version of the api that dpy 1.x used

viscid hornet
#

OP's using like a 3yo version

#

and then complaining that it doesnt work anymore?

timber dragon
#

4*

lyric echo
#

i know i was writing this when covid started, yea

fast osprey
#

It would be nice if apis worked eternally but that's just not practical and would severely limit dev velocity

lyric echo
#

so next project to trash, okay…

fast osprey
#

I mean if you throw it away that quickly without even looking at the migration guide, you really didn't care about it

lyric echo
#

i cared when i was working on it

fast osprey
#

That's fair, it's your call

#

No, you shouldn't be using on_ready

timber dragon
#

what do you need that bool for

fast osprey
#

Not sure why you're wasting time changing everything but what we're telling you matters

#

You don't want to use on_ready

#

You might as well make a loop that runs at random intervals

timber dragon
#

you don't need on_ready, use setup_hook as we have saiid multiple times.. it's not that hard..

# subclass of commands.Bot called MyBot
class MyBot(commands.Bot):
  # override setup_hook to do stuff
  async def setup_hook(self) -> None:
    # load extension(s)
    await self.load_extension(...)

# create instance of MyBot called bot
bot = MyBot(
  command_prefix=...,
  intents=...,
  activity=...,
  status=...
)
# run bot
bot.run(...)
#

no attrs or globals bs needed when you know its only called once

fast osprey
#

Major XY problem

timber dragon
#

why do you want to use on_ready?

#

who is forcing you to use an event that can be called multiple times at runtime and is generally not recommended for doing any sort of api calls in

fast osprey
#

You will accomplish your actual goal if you listen to us telling you the right solution instead of deciding you already know the solution

neon veldt
#

question ?

I been trying to make my own app but it needs AI and I'm too poor to pay, would it work worth it if I use discords bots that already have to fix this issue ?

timber dragon
#

wdym by "it needs ai"?

neon veldt
#

trying to make a app that that uses AI for live reaction on gameplay and also be able to generate models like stuff for blender

viscid hornet
#

or is that just "it's better to just subclass atp"

timber dragon
#

no? setup_hook is called by the library after login

#

it's not an event

viscid hornet
quick gust
#

pretty sure you can, although it's not the intended use

timber dragon
#

@bot.event literally calls setattr so yes that would work but no

viscid hornet
#

does it not just bind it to the bot

viscid hornet
timber dragon
#

still doesn't make it an event

viscid hornet
#

either way, gotcha thumbsup

#

it's something that happens to work

quick gust
#

something that happens to work but shouldn't be used because it'll stop working and you'll be clueless

timber dragon
#

it'll be lovely to see that break in 3.0 maybe

neon veldt
#

question ?

If i want to add a free AI to a discord bot would it be better to make my own ?
any suggestions would be much appreciated.

fast osprey
#

You may want to review the discord dev policy and tos before you get too deep into that

neon veldt
fast osprey
#

You should read the things you have agreed to before you do anything

#

To save you a little time, it's against policy for any AI model to be trained off of user content, and it's against TOS to send any user content to a third party without that user's explicit instruction to do so

tender bobcat
#

Or just read it yourself
We are not lawyer or at least not your lawyer(at least I assume)
And out interpretation might not be correct

fast osprey
#

Incredibly lazy trolling

#

You have been explained this multiple times

tender bobcat
#

We said it multiple time
It might get executed, it might never get executed and it can execute at multiple time randomly

fast osprey
#

Because there is a specific place (multiple actually) that definitively run once. You are choosing not to use them, for no reason, and instead choosing a place that runs randomly so you can check a boolean flag thousands of times

woeful hill
#

Spent time achieving something which is achievable with just moving it to setup_hook

#

Crazy work

timber dragon
#

did yall just take the bait lol

#

unless they're actually next level stupid

woeful hill
#

Willingly be stunlocked, while they try to make a better bait i already watched 10 youtube videos

fast osprey
#

Using on_ready here is like

did_the_thing =False
while True:
  if not did_the_thing:
    do_the_thing()
    did_the_thing = True

We're telling you to

do_the_thing()
brazen raft
#

Your definition of ready should not be when on_ready executes (read up on when it does here: https://discordpy.readthedocs.io/en/stable/api.html?highlight=setup_hook#discord.on_ready ).
Even if it is, most set-up steps can and are intended to be done in setup_hook.
If setup_hook is defined, the bot will call it after logging in, and crucially, exactly once for the entire duration of the bot uptime thereafter, and before any event or other action that has to do with Discord. Just don't make an API call and don't wait on Discord related events in it so you won't hang forever trying to.
There are counter arguments against using on_ready to set your bot up, but to sum it up if you're lazy to read and comprehend the docs I shared up above, just understand that this event can fire too late, leading to problems such as relying on unset state and thus raise exceptions, and that it gets fired upon every reconnect, leading to problems such as resetting/unsetting existing important state which will lead to similar exceptions or even deadlocks because you'd be relying on an event incorrectly.
With setup_hook you deal with none of this headache for the price of being unable to rely on Discord data and events for setting things up. Loading extensions/cogs in setup_hook is better unless some part of doing so requires Discord data or events, which is quite cursed in itself but whatever.
It'd be better for users to have most if not all of the functionality of the bot and its foundation fully working as soon as it goes responsive rather than deal with a waking bot with some of the functionality half ready (could lead to bad state too in this timeframe) every single time it goes online again after maintenance or arbitrary and unexpected downtimes.

timber dragon
#

You can use an asyncio task if you need to do blocking calls in setup_hook and optional even wait until ready in one them for cache:

async def on_ready_once(self):
    await self.wait_until_ready()
    ...

async def setup_hook(self):
    asyncio.create_task(self.on_ready_once())
jaunty cape
#

No

#

If it works, but it works poorly there’s always a better solution

woeful hill
#

if it works don't touch it
the code:

def is_even(x):
    if x == 0:
        return True
    elif x == 1:
        return False
    elif x == 2:
        return True
    elif x == 3:
        return False
    ...
jaunty cape
#

💀

timber dragon
#

Fr

#

Not even elif most of the times

viscid hornet
#

bonus points for inefficiency by using it with negative numbers

burnt quiver
#

wait will that even work lol

burnt quiver
#
def custom_enum(iterable, start=0):
     count = start -1
     odd = True
     for item in iterable:
            count += 1
            if not odd:
                   yield count, item,odd
                   odd = True
            else:
                   yield count, item, odd
                   odd = False

for i, item, value in custom_enum(range(5)):
       print(f'if x == {i}: return {value}')
#

It works and I did it on mobile :P so we dont talk about the indent lol

shrewd apex
#

just use % 2 == 0 😭

jaunty cape
#

no bro you don't understand

#

obviously generating a 16 million line python script just to make a bunch of if statements is best practice

drifting arrow
#

How long it take.

brazen root
#

That's my kinda hyperfixation task.

golden plank
#

what is going on here

balmy spear
vocal kayak
#

Anyone know a good place to find python videos specific to discord bots? I drive alot and like to listen to them while on the road to learn but having trouble finding ones specific to discord bot making

#

No real need for advanced videos as I'm beginner level

fast osprey
#

Don't watch videos to learn. Read docs and articles

vocal kayak
#

Can't do that while driving. Either podcasts or videos.

#

Been slowly working my way through docs at home. But I spend most of my time on the road.

fast osprey
#

Text to speech exists

burnt quiver
#

More importantly, driving safe is what you should focus on

vocal kayak
#

No less safe than listening to the radio....

fast osprey
#

But coding is the sort of thing that benefits massively from being able to experiment alongside what you're learning. It's not the sort of thing most people can passively consume and just remember

vocal kayak
#

Yes. But this is not intended to be my sole way of learning. Just to fill gaps during down time when I can't sit on my PC and dedicate my full attention to it. Things that will talk about concepts and use cases for things I may already have a grasp of. I feel the question has started being pulled away from the original context.

rapid knoll
#

is it possible to get a guild that the bot isn't in, i'm not looking for much just member counts and simple stuff like that

fast osprey
#

No, all you get is what's on the guild preview if it has one

wise mica
scenic pike
#

How can i get random video from tiktok with specific tag than send it to specific channel

viscid hornet
stark ingot
#

I agree with what midget said above. Discord Bots are not a deep enough topic to have more than a little bit of podcast style content.
The core things they use are APIs, rate limits, web socket connections, event handling, and sometimes databases. None of these things are specific to discord bots but can be explored individually

vocal kayak
# stark ingot Are you planning on making a bot from scratch or using a library?

I would like to be able to make one from scratch if needed but I would use libraries for handling specific things like ui elements . But like I said before I am a beginner . I know the basics of python. But I am using discord bot as a way to learn how to use it. And how to learn working with api's and libraries. Possibly how to handle info that would be saved based on the user ( like coin flip game that saves how much money you have ) these things I can look up individually and learn as people have suggested. And I do intend to as I get the time. But until I get the chance to sit down at my PC I would like something I could listen to.

young dagger
#

Should I be using pytz or zoneinfo for timezone objects?

#

I want to keep track of a specific time zone including DST

timber dragon
#

I don't see why you wouldn't use the stdlib over a package

hallow nova
#

hello guys

#

who need an discord bot

#

I can create it for like 10-15 dollars

jaunty cape
hallow nova
#

?

jaunty cape
#

Also

#

!rule 9

unkempt canyonBOT
#

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

hallow nova
#

ohh

#

I didn't know

jaunty cape
hallow nova
#

my bad

desert cosmos
#

Which one is more recommended discord.js or discord.py, for speed and feature richness ?

timber dragon
#

djs for speed and dpy for features IMO

#

But these are two different languages

#

Also there are more python libraries than just dpy btw

desert cosmos
#

Actually I used to use dpy some 2 3 years ago now I am learning js for work and stuff so I have been pondering over options.
Also djs has some reputation for consistency which discord.py has lost over past years. (thats what google says)

timber dragon
#

Isn't it the opposite?

#

I heard that djs often changes things in minor version bumps

#

Sure dpy has been "slow" lately but that's also because it's maintained one person vs a whole team

desert cosmos
#

I heard that dpy was discontinued and then people started exploring other alternatives and then it was reinstigated.

desert cosmos
fast osprey
timber dragon
fast osprey
#

Unless your discord bot is a wrapper over like low level hardware architecture somehow

stark ingot
fast osprey
#

O...kay?

#

People are welcome to use whatever criteria they want, doesnt mean they're good criteria

sage abyss
#

g

hollow yacht
#

how can i save each users last two mesages?

#

for each user

tender bobcat
#

Use a database
Also why?

hollow yacht
#

cuz i want like anti spam system so if mesages same it would delete mesage before and how to use database im new

tender bobcat
#

-# Note 1: It would be better to use any well established product than implement it by just yourself. For example, if my first message and second message have a single (a space character) difference, it won't get deleted. Or if a user send Hi 30 days apart, it's considered spam.
-# Note 2: If you are new, you shouldn't take discord bot as a first project. It is the most often told and most often ignored advice

You would have to learn SQL

hollow yacht
#

no i meant not to python but python bots

tender bobcat
#

?

hollow yacht
#

the new part

#

im not very new to python more like middle

#

but new to discord bots

tender bobcat
#

So what is OOP, async?

hollow yacht
#

well not that advenced

#

i can say

#

but like def while etc

tender bobcat
#

Function?

hollow yacht
#

def

#

if im right

tender bobcat
#

How much do you know about function?

hollow yacht
#

not very much i learnt about def not too long ago

#

like this month

tender bobcat
#

Anyway, you should still:

  • learn about OOP
  • Read at least 1 or 2 article about async
  • Learn SQL
  • Learn more about function
  • Learn how to use a async library for database with SQL in python
  • Read the tutorial on how to create a bot in discord.py documentation
hollow yacht
#

okay thanks

slate swan
tender bobcat
fast osprey
#

And if you're storing message content, you'll want to read the TOS closely on what your obligations are

tender bobcat
stark ingot
#

Just use a cache, no need for a database if you are detecting spam.

civic bobcat
#

guys

#

I am trying to make a discord wrapper from scratch. I am having problems with websockets handling

#

I wanted to make a custom wrapper just for me and learn as well. Anyone here have experience with websockets library?

#

particularly 1006 error code (Abnormal close)

tender bobcat
#

Have you managed to establish websocket connection that isn't to discord? (Like just any, maybe your code communicating with your code)

unkempt galleon
#

how do i fix this python error C:\Users\Administrator\Desktop\Boost Bot V3 SRC\main.py:293: SyntaxWarning: invalid escape sequence '['
os.system("clear && printf '[3J'")
C:\Users\Administrator\Desktop\ Bot V3 SRC\main.py:315: SyntaxWarning: invalid escape sequence '\ '
/\ == \ /\ \ /\ \ /\ \ /_ \ /\ == \ /\ \ /
C:\Users\Administrator\Desktop\ Bot V3 SRC\main.py:564: SyntaxWarning: invalid escape sequence '\ '
/\ == \ /\ \ /\ \ /\ \ /_ \ /\ == \ /\ \ /
there is a invalid excape sequence

#

how do i fix that? im pretty sure thats easy for a coder. Im not a coder

full lily
#

whats the context of that line

#

why do you have a bunch of backslashes and slashes and dashes

unkempt galleon
full lily
#

you should make it a raw string. The backslash has a special meaning

#
r"this is a raw string"
unkempt galleon
#

where do i input that

full lily
#

but its hard to tell whats going on in that line

unkempt galleon
#

could you call for 2 seconds

full lily
#

line 315 and 564

unkempt galleon
#

ill share my screen for second

full lily
#

you can send a screenshot

fast osprey
#

If you're not a coder, are you just hoping we'll fix it for you?

unkempt galleon
#

calm the heck down lol

fast osprey
#

Nice projection

full lily
#

Can you send a screenshot of what's around those two lines?

full lily
#

you need to make that whole thing a raw string

#
r"""
booster
"""
#

note the r

unkempt galleon
#

which line

full lily
#

before the quotes

unkempt galleon
full lily
#

no the starting quotes

#

not ending ones

unkempt galleon
#

print("\033[95m")
print("""

                                LOGIN PAGE                                                                

""")
print("\033[0m") # Reset color

#

on one of these correct?

full lily
#

The reason why you're getting an error is because python is trying to use the bacsklash in your ascii art as an escape character, but it's not valid. To make python ignore backslashes as being special inside of a string, you make it a raw string. So you prefix the string with an r

"i am a string"
r"i am a raw string"

r"""
I am also a raw string
"""
unkempt galleon
#

What is the string i don't know anything about python, im just wondering if you could inform me on what line to input that in.

full lily
#

strings are sequences of characters

#

like words, letters, sentences

#

it's a fundamental type

#

You know it's a string if it's surrounded by quotes

unkempt galleon
full lily
#

Line 321 is fine. The stuff you see inside of that string tells the terminal to display text that comes after it in a certain colour

#

or to remove the colour in that case

full lily
#

so go to the two strings that are on those lines and prefix them with an r

#

the r should go before the first quote

#

I'm sure you already know this, but it's not a good idea to run code from untrusted sources if you don't know what it does

unkempt galleon
unkempt galleon
#

would you be able to input it if i copy and pasted the code please

full lily
#

idk man. Try it

#

run the code

unkempt galleon
#

i think i did it wrong for sure

full lily
#

your error is on line 293

#

oh yeah you did it wrong. No space after r

unkempt galleon
fast osprey
#

They want you to paste the correct code so they can copy it, they don't know how to code and they said that

full lily
#

and you have another error on line 293 it seems. Not sure what's supposed to be there though. It's an ansi escape code for colour formatting so you could remove it and it would work fine

#

!e

r"""
test
"""
unkempt canyonBOT
full lily
#

yeah no error so should be valid

#

are you running python 2?

unkempt galleon
#

no im running python 3.11

full lily
#

!e

r """
test
"""
unkempt canyonBOT
# full lily !e ```py r """ test """ ```

:x: Your 3.13 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     r """
003 |       ^^^
004 | SyntaxError: invalid syntax
full lily
#

ah yeah look

#

no space

unkempt galleon
#

os.system("clear && printf '\e[3J'")

#

could you paste it in there

full lily
#

you got it bro

#

make it a raw string. Same as the other one

unkempt galleon
#

os.system(r"clear && printf '\e[3J'")

#

like that?

full lily
#

give it a go

unkempt galleon
#

doesn't that mean its a error? when it turns red

full lily
#

don't trust whether it turns red or not. Yes, it's supposed to help you spot syntax errors but if you haven't configured your code editor then I wouldn't trust it

#

the real test is to just run the code and see if the interpreter spits out an error

unkempt galleon
#

print("\033[95m")
print("""


/\ == \ /\ __ \ /\ __ \ /\ \ /_ \ /\ == \ /\ __ \ /_ \
\ \ < \ \ /\ \ \ \ /\ \ \ _ \ /
/\ / \ \ __< \ \ /\ \ /
/\ /
\ _
\ \ _\ \ _\ /_\ \ _\ \ _\ \ _\ \ _\
// // // // /
/ // // /_/
LOGIN PAGE
""")
print("\033[0m") # Reset color

#

it says error on 315 and 321

#

anyway you could just input it bro im like a toddler learning to speak when it comes to coding.

full lily
#

yes but you won't learn if I do it for you

#

did you save the files? I feel like you modified these lines already? Or was that a different line?

unkempt galleon
#

yes i saved it ctrl s

#

that was a differnt line i didn't touch those yet because i don't know what im doing

#

i have to leave for work in 30 minutes im just trying to get this running

full lily
#

you do know. I explained to you how to find what line the error is on, and you already fixed a couple of these successfully

fast osprey
#

If you want someone to fix it without you showing any effort to learn, you should hire someone or go to whoever wrote this code

full lily
#

it's the same thing over :)

unkempt galleon
#

im trying to understand what he is saying i don't though

full lily
#

you need to make it a raw string again

unkempt galleon
#

so how are you gonna tell me im not trying like get a life and quit spectating discord chats buddy

full lily
#

because the backslashes are treated as special characters (which you don't want in this case)

fast osprey
#

You need to have fundamental python knowledge to make these changes. There isn't a shortcut

full lily
unkempt galleon
full lily
#

print is a function which takes a string. The string is everything that's wrapped in quotes

unkempt galleon
fast osprey
#

I'm not going to be silenced by you

unkempt galleon
unkempt galleon
full lily
#

yes

#

the backslash here is used for an ANSI escape code which the terminal uses to give formatting