#discord-bots

1 messages · Page 110 of 1

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

wont work

#

The issue is that you have multiple on_message events and only one will work, all the others will get overwritten and ignorred.

To fix that replace

@client.event

to

@client.listen()
#

ohhhhhhh

#

No, you read what the embed says

slate swan
#

it slike 100 of them

slate swan
#

It says to pack your code in a message like that:

```py
python code here
```

#

ohhhhh

#

ok

slate swan
#

@client.listen()
AttributeError: 'Client' object has no attribute 'listen' this comes upp

fading marlin
#

why do you have 2 on_message

slate swan
#

Oh yeah, use

from discord.ext import conmands

bot = commands.Bot(...)
fading marlin
#

use an elif block

slate swan
#

i am getting dizzy

#

Then replace all mentions of client to bot and remove the

client = ....

line

slate swan
#

Replace

client = discord.Client(...)

with that

slate swan
#

But remove it

slate swan
#

so i remove all client and replace them with bot

#

No reason to use client in your case

slate swan
#

Then .listen() stuff will work

#

ok

fading marlin
slate swan
#

and where do i put it

fading marlin
slate swan
#

ohhh so where do i put it

#
if message.content == "...":
    # ...
elif message.content == "...":
    # ...
fading marlin
slate swan
slate swan
#

In the on_message event

#

You pack two of them in one

#

thast the problem xd i am trying to learn python

#

Remove one and keep only one

slate swan
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.

slate swan
#

Might be worth knowing kore python before doing a bot just as side note

slate swan
fading marlin
slate swan
#

And instead of using

test_channel = ...
await test_channel.send(...)

just use

await message.channel.send(...)
#

Will send the message in the current channel where you send the message, which is most likely what you want

#

why is it yellow

#

under the message

#

Don't know, can't guess your code

#

Krypton — Today at 21:52
if message.content == "...":
# ...
elif message.content == "...":
# ... when do i use these

#

Not your code

#

That's my message

#
    # ...
elif message.content == "...":
    # ...```
slate swan
#

```py
your code here
```

Just copy paste that message above and place your code in the middle

#

i did

#

Your entire code

#

ohhhh

#

You probably have wrong indentation

#

ok

unkempt canyonBOT
#

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

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

slate swan
#

Yeah without your token :)

#

Go ahead and reset your bot token please

#
from cgi import test
from math import degrees
import discord
import http

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

@bot.event
async def on_ready():

 test_channel = bot.get_channel(1032312979594682491) 
 await test_channel.send('Hello')

@bot.event
async def on_disconnect():
 test_channel = bot.get_channel(1032312979594682491) 
 await test_channel.send('Hello')
  
@bot.event
async def on_message(message):

    if message.content == "What day is it?":
        test_channel = bot.get_channel(1032312979594682491)
        await test_channel.send("The day is the 21th")

@bot.event
async def on_message(message):

    if message.content == "Thank you for telling me!":
        test_channel = bot.get_channel(1032312979594682491)
        await test_channel.send("No Problem AnyTime :)")


bot.run('')
#

there

#

You still have 2 events

slate swan
#

Remove one and keep only one

slate swan
#

i did

slate swan
#

but it removed pretty quickly for me

slate swan
#

That doesn't matter, there are people that use client modifications, which are not allowed, to still see those messages

#

So I definitely recommend to reset the token

#

i did

#

but i am confused

slate swan
#

wdym

#
from discord.ext import commands
#

ohhhhhhhhhh

#
bot = commands.Bot(...)
#

so where do i put that

#

Case sensitive

#

At the top, with all the other imports

#

ok

#

bot = commands.Bot(...)

#

do i change that with this bot = discord.bot(intents=discord.Intents.all())

#

Yeah in the ... keep intents stuff

#

ok

#

But it's commands.Bot not discord.bot

#

ok now what

#

i need to add elif right?

#

Now you can remove an event

#

For example the last one

#

the @bot.event?

#

And add an elif in the one where you send the day

slate swan
#

Just keep bot.run(...) at the bottom

#

so i change if to elif and await to elif

#

right?

#

await to elif
?

slate swan
#

No, keep that

#

ok so what do i replace the elif with

#

can you like pls show me rq

#

In the end it will be like that

@bot.event
async def on_message(message):
    if message.content == "...":
        await message.channel.send("...")
    elif message.content == "...":
        await message.channel.send("...")
#

ohhhhhhhhhhhhh

#

so i just add elif besides await and then add another await

#

Correct, as I showed above

#

and what for text should i add after the elif and at the elif

#

Well your things

#

Like

What day is it?

And then

await message.channel.send("The day is the 21st")
#

sorry if i am annoying you

slate swan
#

but what do i add elif message.content == "...": here

#

It's fine, it's just that you're lacking of basic knowledge that is definitely required for bots

#

at the darts

slate swan
slate swan
#

Thank you for telling me!

#

And then .send("No Problem ...")

#

but now its showing somethign red under elif

#

Then there's something wrong in your code specifically

#

do i need to import elif?

#

No that's a built-in keyword

#
from cgi import test
from math import degrees
import discord
import http
from discord.ext import commands

bot = commands.Bot(intents=discord.Intents.all())

@bot.event
async def on_ready():

 test_channel = bot.get_channel(1032312979594682491) 
 await test_channel.send('Hello')

@bot.event
async def on_disconnect():
 test_channel = bot.get_channel(1032312979594682491) 
 await test_channel.send('Hello')
  
@bot.event
async def on_message(message):

    if message.content == "What day is it?":
        test_channel = bot.get_channel(1032312979594682491)
        await test_channel.send("The day is the 21th")

@bot.event
async def on_message(message):

    if message.content == "Thank you for telling me!":
        test_channel = bot.get_channel(1032312979594682491)
        await test_channel.send("No Problem AnyTime :)")
        elif message.content == "Thank you for telling me!":
        await test_channel.send("No pronelm Anytime :)")


bot.run('')
slate swan
#

See the difference between

if ...:
    await ...
    elif ...:
    await ...

and

if ...:
    await ...
elif ....:
    await ...
#

Above is your code, below is how it should be

#

ohhhhhh

#

shit my problem sorry

#

And remove the on_message above

#

You only need one

#

you see my friend is good at coding and we coded and he did the elif but i forgot

slate swan
#

How to make a bot respond in a channel? and if it's in another channel say that you need to be in #bot-commands channel

whole kite
#

bot was working last night for some reason doesnt work

#

all the code is the same from last night

slate swan
#

Traceback (most recent call last):
File "\OneDrive\Skrivbord\Disocrd bots\Discord bot.py", line 7, in <module>
bot = commands.Bot(intents=discord.Intents.all())
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'whats this for error msg

slate swan
#

i fixed the eror

slate swan
#

but now this came File "c:\Users\getbe.MOHAMADSDATOR\OneDrive\Skrivbord\Disocrd bots\Discord bot.py", line 7, in <module>
bot = commands.Bot(intents=commands.Intents.all())
AttributeError: module 'discord.ext.commands' has no attribute 'Intents'

slate swan
slate swan
obtuse blaze
#

sry for ping but quick question you recommend VM or lightsail? on aws surely I didn't pinged wrong person to ask this before

slate swan
slate swan
# slate swan nvm

You need

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

instead of what you had previously

slate swan
slate swan
#

== => !=

#

That's what i want

#

Oh wait

#

I misspleded

#

Ye

#

You want to execute commands only if it's in that specific channel?

#

krypton

slate swan
#

Yeah then

if ctx.channel.id == ID:
    # Code

is fine

#

somethings wrong the bit wont reply to my "what day is it"

slate swan
dull terrace
slate swan
#

No you didn't

#

Your if and your elif both work only for

Thank you for telling me!

slate swan
#

Then replace the text in your elif to be

What day is it

#

And replace in the .send() below the elif the message you want to send

#

Horrible stats tool

dull terrace
#

i imagine once i get past maybe 5k servers i would need to upgrade, but by then i should have a couple patreons

slate swan
#

yay krypton it worked i did it (we did it) tysm for the help

#

well i need to go to sleep i have school tmr and yet again tysm

dull terrace
#

hmm

#

should i be keeping my instance name private

obtuse blaze
dull terrace
#

windows

obtuse blaze
#

oh?

dull terrace
#

no reason why except laziness

obtuse blaze
#

im asking cause I don' have t3 free tier on windows

dull terrace
#

ohh my bad

obtuse blaze
#

t2

dull terrace
#

yeah

obtuse blaze
#

alr thank you bow

slate swan
#

Now if y'all don't mind I'll work on my projects CL4_PepegaHacker

obtuse blaze
#

ohhh I just saw

#

it gives us 750h of free

#

so only 31 days? or im being dumb bunFeelsdumb

dull terrace
#

per month

obtuse blaze
#

so we get 750 per month

dull terrace
#

you get one instance free basically

obtuse blaze
#

ah ic btw can I make you question about connection to it cause im having a problem that doesn't make sense dead

dull terrace
#

are you using windows?

obtuse blaze
#

mhm

#

im using RDC and it keeps giving connection error

dull terrace
#

did you download their rdp file to make sure you got details correct?

obtuse blaze
#

mhm

dull terrace
#

is the instance started?

obtuse blaze
#

yup

dull terrace
#

should see that, needs to have done the checks too

obtuse blaze
dull terrace
#

and you decrypted the password and used it to connect?

obtuse blaze
#

it doesn't even ask for it

#

error shows up even before login is asked

dull terrace
#

hmm maybe im forgetting a step, you might need to allow access, i thought that was done by default though

#

click on your instance, go to the security tab

#

click on the security group name that's linked

#

one of the rows should have this

obtuse blaze
#

looking for it 1 sec

dull terrace
#

with a source name and port

obtuse blaze
#

it has the default one

#

idk if this is correct but still not working

dull terrace
#

are you on the inbound rules?

obtuse blaze
#

mhm

dull terrace
#

that's very weird it has that by default on yours

obtuse blaze
#

ikr never seen this

dull terrace
#

i would delete that rule, you don't want all inbound traffic accepted

obtuse blaze
#

what should I put on source?

#

my ip only?

#

well it worked now laugh_cry

dull terrace
#

yeah, bare in mind that your ip can change every once in a while if you have a dynamic ip

obtuse blaze
#

tysm bow

slate swan
#

Wondering what that has to do with Discord bots development bravemmlol

dull terrace
#

np, took me hours to figure that out on my own with little experience in setting this stuff up

dull terrace
dull terrace
obtuse blaze
slate swan
#

Alternatively there is a thread in this channel for hosting

obtuse blaze
#

its still bot related- well nvm, im sry if it was annoying for you bow

slate swan
#

Quoting the channel description

For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.

#

There is a thread for bot hosting, it was not made for decorating

obtuse blaze
#

once again I already said im sry.. idk what you expect more with this? me kneeling or what

slate swan
#

its still bot related

You apparently still believe it belongs to this channel

obtuse blaze
#

And you still keeping typing DonoWall

slate swan
#

Why would I be disrespectful and not reply to your question?

obtuse blaze
slate swan
south coyote
#

how do you make a discord bot specifically a tipbot

primal token
#

Who krypton?

slate swan
#

yup

#

dude is a weirdo and has a massive ego

south coyote
#

can someone link me

primal token
south coyote
#

save the drama for yo mama

slate swan
#

i mean if another person is having issues with him then its something he is doing wrong

primal token
#

Because he's experienced and is ruthless doesnt mean he has an ego

slate swan
#

ruthless? nah straight disrespectful

bold surge
primal token
#

Well, if you think that you should report it to @novel apex

slate swan
#

you can know ur shit and not being a weird ab it

south coyote
#

anyways

primal token
#

I doubt you will get far as moderators havent muted or banned him

slate swan
#

he is just like half of the dpy staff lmao. all egotistical weirdos who think they know anything

#

and shame you if you say something they dont like

primal token
#

May i ask how the assumption of half of the staff in the dpy server are "weirdos"

south coyote
#

you realize you are committing slander right

#

can someone help me find information on building a discord tipbot that is compatible with avalanche tokens?

primal token
south coyote
#

im sure the feeling is mutual so quit acting like you are the better one

primal token
#

?

south coyote
#

he probably doesn't like you either jaymart

primal token
#

I think krypton doesnt even know who he is, from what I've seen

south coyote
#

so just leave each other alone and let it be

primal token
#

Yeah, i agree

slate swan
south coyote
#

this isn't a courtroom

#

jaymart you aren't helping your case

primal token
south coyote
#

please quiet down

primal token
#

If you feel that sure, but lets change topics

hollow quarry
#

this is enough, please stop being rude to people. if you have concerns about a user, DM them to @novel apex.

#

and please avoid using ableist language

livid kindle
#

guys i need your help , i live in iran and now they locked everything but I still can connect to discord web's voice channel but in app it stuck in RTC, is there a way that i could use to copy the ip that web version uses so i could paste it somewhere in app then maybe i can connect to voice channels (in app)?

#

like can i copy the .js file on web and paste it on app?

dry fox
#

is there discord library for python2?

wary shadow
#

Hopefully not. py2 is long dead.

dry fox
#

Yeah but it would really help my case because then i need to mess around with oauth (rather then borrowing already working from a friend)

tight obsidian
dry fox
#

basically simple for personal use discord bot communicating with my school's site

royal wind
#

Hello, I have a pretty general question:

It's been some time since I last worked on my super basic bot. I want to redo things from almost the ground. I am thinking of using database to track stuff like server pts, account id, warnings, etc. I am thinking of using SQL instead of online database like MongoDB. I have an old desktop that I plan to use for this server running 24/7. I will be writing using Python. I heard Python has built in SQL or something like that. Does that mean it's possible? Is there any good beginner tutorial for this?

sick birch
#

SQL is only the language, not the database and mongodb is not necessarily an online database (though the company does provide DaaS for you)

royal wind
#

But I believe database for discord bot should be relatively simple (adding entry if doesn't exist, modifying entry, deleting entry)

sick birch
#

You're right, though the first step should be to figure out exactly what you want

#

From what you've said earlier, I think an SQLite database along with aiosqlite is what you're looking for

royal wind
#

SQLite was actually the thing I used in class. I thought SQL is more popular, thus I wanted to go there. But if SQLite is perfectly fine, then that's even better

#

What is AIOSQLite? Is that a second type of database?

sick birch
#

There is no distinction between SQL and SQLite

#

SQLite is the "engine" while SQL is the interfacing language

#

Other databases also use SQL: PostgreSQL (colloquially known as "postgres"), MS SQL Server, MySQL, etc

#

All of these use SQL to interface with the engine

#

If you know SQL you can really work with all of these

sick birch
royal wind
#

Is SQL something like

CREATE TABLE {
....
}

FROM * SELECT ...

etc etc?

sick birch
#

Yup

#

Though I hate writing SQL queries

royal wind
#

Ok so let's say I want to use that. how do I incorporate it with Python language discord bot?

sick birch
#

I much prefer an ORM

#

Type safety and ease of use

royal wind
#

Do I use SQL syntaxes inside the Python IDE?

obtuse blaze
#

Robin since you here can I make 2 quick questions?

royal wind
sick birch
#

You'd use something like
sql.execute("Select * FROM table_name ...")

royal wind
#

Aah

sick birch
#

Given you have everything else set up properly

sick birch
royal wind
#

Ok, is there any specific module(s) I need to import? Is it just import sql?

sick birch
#

It's part of the stdlib

royal wind
#

Ah, ok. So I don't have to install the sqlite or something into the machine

sick birch
#

SQLite is pretty simple so it's just a database file

obtuse blaze
#

So I just adquire free tier AWS to host bot 24/7, and since I have host now I was thinking of switching for something else besides SQlite but idk what and if it's worth it what do you recommend? also is there a way to make bot auto update, cause I was using GitHub to keep track of updates etc but now that bot is hosted on VM i feel like drag and drop every update is kinda "not efficient"

royal wind
#

or did I just misremember it?

sick birch
#

And GitHub CI/CD pipeline for updates

obtuse blaze
#

RDBMS? ConfusedShock

royal wind
#

This was from my assignment. sqbpro

sick birch
#

Mouthful, I know

obtuse blaze
#

sheesh

sick birch
slate swan
#

why is commands a function

obtuse blaze
#

is it hard to set up?

sick birch
#

Not sure if you know this but file extensions don't mean a whole lot

sick birch
obtuse blaze
royal wind
#

But now you say that, it's confirmed

obtuse blaze
sick birch
royal wind
#

Thank you too Robin. very helpful

sick birch
#

My pleasure

slate swan
obtuse blaze
sick birch
slate swan
sick birch
#

It's probably shadowing from discord.ext import commands

sick birch
slate swan
sick birch
#

Yeah name clashing just use underscore as mentioned

royal wind
slate swan
royal wind
#

I need to remmeber that

slate swan
#

but i wan everyone to me avable to do/commands

sick birch
royal wind
sick birch
#

@client.command(name="commands")
async def _commands(...):

#

@slate swan ^

royal wind
#

When I started out doing discord bot, I remember the first tutorial that I followed was using client. But I found out that it was very limiting on what I could and could not do. Another example did it with ctx. What's the difference between these?

slate swan
sick birch
#

I hope you didn't copy paste that

slate swan
#

maby

#

im dumb ok

sick birch
sick birch
#

Remove the copy paste and edit your existing code so it looks similar

royal wind
#

So that's why bot can do lots more. Because it inherits everything from client + its own stuff

sick birch
royal wind
sick birch
#

Most of them are pretty bad

royal wind
#

Shot, I thought so

sick birch
#

See the pins in this channel for resources

royal wind
#

I kept jumping back and forth. It was so hard

slate swan
#

it works now ty @sick birch

sick birch
#

Np

wary shadow
#

A lot of what makes a discord bot is just knowing the basics of the language. Everything a bot does comes down to the usual handling data, conditionals, and loops.

royal wind
royal wind
#

Ah wtf, there's someone with name blablabla

#

Also, those of you who have Discord Bot deployed, I wonder how you guys deal with XP and level..

My first idea (and perhaps not good at all), is to keep track of ACCOUNT LEVEL that has ACCOUNT_ID, ACCOUNT_XP, and ACCOUNT_LEVEL. But I figure it's bad because ACCOUNT_LEVEL is just calculated ACCOUNT_XP.

My second idea was to go with ACCOUNT_ID and ACCOUNT_XP. But I wonder how can you make incremental XP requirements. Lv. 1 to Lv. 2 needs 100, but Lv. 2 to Lv. 3 needs 150. Lv. 3 to Lv. 4 needs 180, and so forth.

sick birch
royal wind
#

Hmm

sick birch
#

Find a pattern if you can

#

Eg each consequent level takes twice as much XP

royal wind
#

Let's say that the next level requires 25% more xp than the previous requirement

#

If I were to do it this way, I would still need to keep the base line (100XP). If a person just made it to 385XP. I would have to go from beginning:

385XP - 0XP = 385XP
385XP - <basereq>100XP = 285XP
285XP - <prevreq>*1.25 = ...

Do this on a loop until the XP would go below 0, then cancel.

#

Ok, I think I got it

sick birch
#

Actually mmm

royal wind
sick birch
#

No I think it's exponential

royal wind
#

It would've looked something like this

sick birch
#

How are you getting these numbers?

royal wind
#

That's starting xp + requirements to advance

royal wind
sick birch
#

What's starting xp?

#

I thought it was just the previous * 1.25

royal wind
#

So to get to Lv. 1, you need 0 XP (everyone starts at Lv. 1)

#

To be lv. 2, you need at least 100 XP (yeah, that's something I need to fix by the math screenshot)

#

To be Lv. 3, you need to have 225 XP (Lv. 2 starting being 100 and 125 XP requirements to advance)

sick birch
#

Ohh

royal wind
#

Requirement to advance is calculated from the previous requirement * 1.25

sick birch
#

I was only thinking of how much more you need

#

So it's cumulative

royal wind
#

Cumulative. Because the ACCOUNT_XP will only get bigger

sick birch
#

Ugh I was never good at math

royal wind
pliant gulch
#

Can you say the problem your having again? Just got on

sick birch
#

Not really a problem

#

We're brainstorming how to make an exponential leveling system

#

Trying to think of an equation that does it

pliant gulch
#

You would raise to X power

#

That would be exponential, sorta like a porabola

royal wind
pliant gulch
#

I don't think you'd want an exponential leveling system though

#

It'll get super super hard to level up the further you go

royal wind
amber ether
#

Hey guys. how do i make that so ex: i do /test id and if they do the same id It will send an Error Used Id?

sick birch
pliant gulch
#

Okay, then it would still be pretty simple though just raise it to a power

sick birch
#

The thing is its cumulative

#

So it needs to add the amount of XP needed for the last one

pliant gulch
#

Let's say you start off with Level X which needed 100 EXP, the next level would be Level z WITH 100**2

sick birch
#

Recursion maybe?

royal wind
#

It's more like a curve, but not exponential curve I say

sick birch
#

I think we can borrow the equation from compound interest and tweak

#

After all the scenarios are quite similar

#

Just instead of money its XP

royal wind
#

Right

#

isn't my approach more like compounding increment then?

pliant gulch
#

Okay, if your just multiplying by some number that would just be linear growth

pliant gulch
#

You have different types of exponential growth, linear, cubic, then exponential like x^2

uncut tendon
#

can someone help me whit my command? i have try in 4 hour i fix so u need a role to run a command but i want the bot to reply if u dont have the role how did i fix that?

pliant gulch
#

There is probably a few more that I'm not remembering

royal wind
pliant gulch
#

Yea, x^3

#

But cubic even though the power is higher, it grows slower than x^2

royal wind
#

Huh?

pliant gulch
royal wind
#

Since we're talking positive numbers only, I don't think cube can be beaten by power of two unless you're talking about that first X values

#

Ah yes

#

But as the x -> inf, it would overshoot it by a lot right

#

Now the question is, how can I make sure account_xp isn't updated if it was last updated within x seconds (basically cooldown for spammer to not get xp so fast)?

pliant gulch
#

You can probably use timedelta

royal wind
#

timedelta? Never heard of it before

#

You mean to literally put a last_update date?

#

To check if it's within x seconds?

pliant gulch
#

!e ```py
from datetime import datetime, timedelta

last_leveled_up = datetime.utcnow()
cooldown = timedelta(seconds=20)

if datetime.utcnow() + cooldown < datetime.utcnow():
print("Foo")

unkempt canyonBOT
#

@pliant gulch :warning: Your 3.11 eval job has completed with return code 0.

[No output]
pliant gulch
#

Basically, create a timedelta object, delta meaning difference right? So then you can add that offset to check it from the current time

royal wind
#

Okay, that's perfect, I can use that for a lot of things probably

pliant gulch
#

👍

royal wind
pliant gulch
#

It could be either < or > I forgot but you could probably figure that out

#

But I'm pretty sure to check if some timed passed it's passed < before

royal wind
#

Shouldn't this line comes from the databse btw?

#

datetime.utcnow() I assume would give us current time

pliant gulch
#

If your using a RDBMS they almost 100% have a timestamp data type or something similiar

royal wind
#

RBDMS? Relational B... Database Management System?

pliant gulch
#

datetime.utcnow() then do a query to append to your database at that location with TIMESTAMP for example

#

Like in PostgreSQl

royal wind
#

I'm planning to use SQLite

pliant gulch
#

Okay, you won't have a specific time data type in SQLite

#

But they give you time functions

#

So you'd just store via TEXT or something

royal wind
#

Yeah, I believe it's DATE type something like 2022-10-20 05:00:00

pliant gulch
#

ISO8601 Formatted

royal wind
#

But can the same command datetime.utcnow() process that information? Won't different format mess things up?

pliant gulch
#

There should be no problem if you format with ISO8601

royal wind
#

Okay

pliant gulch
#

!e ```py
import datetime; print(datetime.datetime.utcnow().isoformat())

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.

2022-10-21T00:00:32.584967
royal wind
#

All these things are all new territories for me.

fading marlin
#

is this for the leveling cooldown mentioned earlier?

royal wind
#

Ok, so I theoretically now know about:

Database to use (SQLite with DB Browser)
The database table for leveling (ACCOUNT LEVEL = {ACCOUNT_ID, ACCOUNT_XP, LAST_UPDATE})
The time method and verification method before adding XP

#

I should be able to make the leveling system now

fading marlin
#

why're you using a database to store the last time it was updated?

royal wind
pliant gulch
amber ether
#

Hey guys. how do i make that so ex: i do /test id and if they do the same id It will send an Error Used Id?

fading marlin
pliant gulch
#

!e ```py
import datetime; print(datetime.datetime.fromisoformat("2022-10-21T00:00:32.584967"))

#

What

royal wind
fading marlin
unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.

2022-10-21 00:00:32.584967
mighty pilot
#

anybody able to help me accomplish this? im currently using mysql.connector and not quite sure how i would open and close the connection in each command i want to use

pliant gulch
#

You'd need to populate somehow which makes no sense to store temp inside memory

royal wind
# fading marlin correct

Do you have any idea why I would prefer to use dictionary? I personally can't think of a reason why.. Unless it's to separate:

year : 2022
month : 10
...
}```

But I don't see the usability from using dictionary for this purpose
fading marlin
# pliant gulch That would make your data non-persistent now

why would you need the last time a message was sent to be persistent anyway? Sure, use a database to store user and levels, but not the last time a message was sent. It'll probably be quicker to just check if a key exists inside a dictionary rather than opening a connection

pliant gulch
#

If the bot turns off you lose all your cooldowns to the next lifetime

#

So now your cooldown doesn't work and people can spam to level up

#

Or at least once before a new cooldown is added

fading marlin
royal wind
#

Huh, I am not following that logic andy.

pliant gulch
#

Since the dictionary is in memory strictly for the lifetime of your bot there is no data persistence

royal wind
pliant gulch
#

Yea, meaning database is 100% way to go since it persists the data

mighty pilot
#

and he doesnt want that because then it wont prevent spamming when the bot restarts

royal wind
#

Right, but the thing that I was not following was the statement, "you lose all your cooldowns to the next lifetime"

Won't the cooldown be triggered again after the user sends a message? Because a new dictionary is to be created?

pliant gulch
#

I added that last part cause I just realised that too

royal wind
#

Ah, I understand now.

fading marlin
royal wind
#

Now the question is, why would Lee recommended using dictionary? Is it to reduce the amount of data stored?

fading marlin
royal wind
pliant gulch
#

There also has been some stuff with discord gateway based events using dynamic cooldown mappings via discord.py

#

But that's probably a whole other thing

mighty pilot
#

anyone have experience opening and closing mariadb connections inside a command?

fading marlin
royal wind
fading marlin
royal wind
mighty pilot
#

my situation is im trying to use a temporary table in mariadb to create a way to check rank in your server, and to effectively use temporary tables i need to close the connection, which means i will need to open the connection again when a message is sent or command is issued

so do i put my mysql.connector.connect(...) and define a cursor in each block then close at the end? or is there an easier way

royal wind
sick birch
#

Why do you need the date?

#

For what functionality, I mean

fading marlin
sick birch
#

heck what am I asking I'm supposed to help people with what they want to do not tell them to not do what they want to do

mighty pilot
#

lmao

royal wind
sick birch
#

I see

#

What I would do in this situation

#

Include last update on the database but on bot startup load it into cache

#

And then periodically dump to DB or on bot disconnect

royal wind
sick birch
#

This thing will run on each message, yes?

royal wind
royal wind
# sick birch This thing will run on each message, yes?

This runs on each person. If I send a message now, then under my ACCOUNT_LEVEL table at column LAST_UPDATE the message date would be recorded. If I send another message, and it's within 1 minute, I don't gain xp again. If you send a message 3 secs after I do, you still get message, then you get a LAST_UPDATE too

sick birch
#

You may as well be storing the users current XP in memory and perform the same bulk dump to DB

slate swan
pliant gulch
#
COOLDOWN = commands.CooldownMapping.from_cooldown(RATE, PER, commands.BucketType.member)

class Bot(commands.Bot):
  def __init__(self, *args: Any, **kwargs: Any) -> None:
    super().__init__(*args, **kwargs)

  async def on_message(self, message: discord.Message) -> None:
    cooldown_bucket = COOLDOWN.get_bucket(message)
    if retry := bucket.update_rate_limit():
      return # Don't give EXP
    
    member.author.give_exp()
``` A different way of fixing this problem I guess
amber ether
#

Hey guys. how do i make that so ex: i do /test id and if they do the same id It will send an Error Used Id?

pliant gulch
#

Instead of having a cooldown for leveling up, have a cooldown for getting exp

sick birch
royal wind
#

I probably should've specified that to avoid confusion.

pliant gulch
#

I don't know if this still works it's been like hella long time since I've used discord.py so this is basically off memory and some source diving

royal wind
#

The actual account level is mathematically calculated

pliant gulch
#

but face value it looks like it'll work

slate swan
royal wind
#

Okay, so it looks like I have all the recipes to make the level system

sick birch
#

in memory off memory

mighty pilot
#

id still go with a dictionary then just add and remove members from the dictionary as the cooldown is triggered with datetime.timedelta personally

royal wind
#

Thank you @pliant gulch @fading marlin @sick birch

pliant gulch
#

👍

mighty pilot
#

can i get help with mariadb connections now? blobgrimacing

sick birch
mighty pilot
#

i thought it might be better to ask here because im trying to open and close database connection inside of commands and on_message

#

so i can utilize temp tables

fading marlin
#

mariadb kinda sucks btw, consider using another db

mighty pilot
#

current setup: i connect to the database upon starting my bot and use cursor for whatever i need to do, the problem with this is that in order to use temp tables i need to close connection to automatically get rid of the table. then the connection isnt open again until the bot restarts

mighty pilot
#

theres 40 database interactions id have to change at this point

royal wind
mighty pilot
#

maybe later down the road i can change it up but right now ive got too much planned to start changing the entire structure ive got already

royal wind
#

This may seem silly, but I used to host my discord bot on repl.it. I just did import discord. Now that I'm hosting on my server (old desktop PC), I can't run import discord:

hushed galleon
#

repl.it has a feature that tries auto-installing third party packages based on the imports you write in your code

#

so for your server you'll have to manually install those packages

royal wind
#

I see

mighty pilot
#

you need to install any packages you use in your code to your pc

royal wind
#

I just did this on my PyCharm. However, it doesn't seem to do anything

#

It did download and install stuff, but I am still facing the same error

hushed galleon
#

have you set up a virtual environment for your project?

royal wind
hushed galleon
#

hm thats a weird place to put your script

royal wind
#

Is it?

#

I don't really understand what even VENV mean, so I might get that wrong. Could you explain?

#

While I'm just getting started

hushed galleon
#

virtual environments let you run projects with their own dependencies (i.e. packages) rather than installing packages globally to your system interpreter

#

e.g. one project might use discord.py while another uses disnake, and installing them in their own virtual environments means they wont interfere each other

royal wind
#

Ok, I understand that part now.

hushed galleon
#

so in your case it seems you have a virtual environment created

royal wind
#

Right

hushed galleon
#

i forgot how it interacts with pycharm and its builtin terminal, but assuming you want your packages inside that virtual environment, the idea would be "activating" your virtual environment so that pip will install to it and for py/python to have access to it

#

this is off topic so a help channel would be more appropriate for continuing the discussion

royal wind
#

Ok, let's move there

#

If you don't mind helping me

sick birch
#

A surefire way would be to add packages through pycharm's UI

#

oh didn't notice yall moved

royal wind
amber ether
#

how is it undefined

jaunty musk
#

Anyone know why this:
await message.channel.send(f'![logo](https://cdn.discordapp.com/emojis/230438859752603650.webp?size=128 "logo")')

is giving me this:
:logo:

When trying to get my bot to use custom emoji's?

amber ether
#

it will sednd the emoji

jaunty musk
#

its not...

amber ether
#

give ss

jaunty musk
amber ether
#

try not putting f

#

maybe

jaunty musk
#

it has the right perms

amber ether
jaunty musk
#

Yea that just breaks the code

amber ether
#

yep i dont know lot about py bc im a js dev

#

Anyone

chilly dove
#

first your token is visible and you need to reset and second you are importing that as cs so cloudscraper is not a variable

amber ether
#

OH SH

#

i forgot

chilly dove
jaunty musk
#

Now I'm dealing with this:
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

chilly dove
#

get_emoji shouldnt be returning that

jaunty musk
#

Oh I ended up just adding all the emoji's to my server itself just to not deal with custom emoji shit

chilly dove
#

well then without knowing that context of the forbidden error i cant help

slate swan
#

hello! i need help with this, im making a discord bot that allows you to talk as a member for fun from the terminal, to avoid tos, and a fun thing!
but i keep getting this 'str' error.

    await message()
TypeError: 'str' object is not callable```

code:

```py
@bot.command()
async def talk_enable(ctx):
    await ctx.reply("Successfully enabled! look in terminal :eyes:")
    await message()



async def message():
    xx = bot.get_channel(1031719193902592040)
    message = input("message: ")
    await xx.send(message)
    await message()
jaunty musk
#
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "Z:\Library\Projects\Code\freya\main.py", line 203, in on_raw_reaction_remove
    await payload.member.remove_roles(role)
AttributeError: 'NoneType' object has no attribute 'remove_roles'```
sick birch
#

aside from that, input() is blocking so it's not a good idea to use it in your bot

#

and from what i'm hearing the asynchronous solutions are pretty janky

slate swan
sick birch
#

it's still not going to be an ideal solution

sick birch
#

Might be an intents issue

jaunty musk
#

Would it be cool for me to post my entire code here? I'm just not really sure what to do. 😅

sick birch
#

No need, the issue is right there

slate swan
sick birch
#

that's up to you. You could make a command where users can broadcast their messages from one channel to another, e.g
!say #another-channel <message>

hushed galleon
#

@jaunty musk see the disclaimer for payload.member in the documentation:

#

!d discord.RawReactionActionEvent.member

unkempt canyonBOT
jaunty musk
#

What's a guild? This stuff is kinda confusing o.O

hushed galleon
#

a synonym for a discord server, you'll see it used often in discord bot development

sick birch
#

"server" has a different meaning when it comes to developing so they call it a "guild" to avoid confusion

jaunty musk
#

alright, sooo what should I be looking for... heh

sick birch
#

Only available if event_type is REACTION_ADD and the reaction is inside a guild.
Perhaps the reaction is coming from a DM?

hushed galleon
#

Only available if event_type is REACTION_ADD ...
given that you're using an on_raw_reaction_remove event, the payload wont have this reaction_add type which means member will always be None

sick birch
hushed galleon
#

the traceback says otherwise

sick birch
#

looks like they've already accounted for it by not using payload.member in on_raw_reaction_remove

#

ahh

hushed galleon
#

actually good point, the code seems to be outdated

sick birch
#

i saw

await payload.member.remove_roles(role)

and looked at the on_raw_reaction_add, my bad :p

#

though I don't see await payload.member.remove_roles(role) on line 203 though

jaunty musk
#

is there some better code to use 😬

hushed galleon
#

i assume that for-loop was your attempt at fixing the bug?

#

instead of that, you can fetch the member object from the guild instead

jaunty musk
#

honestly im just trying to hack some shit together tbh. It's hard to find updated python code for this imho. I'm not the best coder in the world

#

im a systems guy, not a coder haha

royal wind
hushed galleon
sick birch
jaunty musk
#

o.O

limber pagoda
#

/s = sarcasm?

jaunty musk
#

lol I kinda rely on Github Copilot. I'm dyslexic af so I'm super garbage at writing code.

hushed galleon
#

what have other people's experiences been with using copilot for discord bots/API?

sick birch
#

if i'm to guess it probably regurgitates shitty code it found off random github repos and youtube tutorials

chilly dove
hushed galleon
#

right, guild.fetch_member

#

its a bit of a necessity if the cache doesnt contain the member

chilly dove
#

why wouldnt the cache contain the member?

jaunty musk
#

so im trying to figure out how I should write this cause I'm a bit confused.

#
async def on_raw_reaction_remove(payload):
    if eligible_for_action(payload):
        role = interpret_emoji(payload)
        if role == None:
            return
        for member in client.get_all_members():
            if member.id == payload.user_id:
                user = member
        await user.remove_roles(role)
        print(
            f"The user {user.name} was removed from the role {role.name}")```
sick birch
#

you only need bot here

#

the others are for oauth apps

hushed galleon
# chilly dove why wouldnt the cache contain the member?

yknow what, i cant actually recall any source describing that the member cache can definitively leave out members from the cache, and i dont work with a large bot so i cant tell if there's a difference with the cache at scale

chilly dove
#

i think when you are working with large guilds then some members can not be in the cache but you should always do a check in the cache first before using a api call

hushed galleon
jaunty musk
#
async def on_raw_reaction_remove(payload):
    if eligible_for_action(payload):
        role = interpret_emoji(payload)
        if role == None:
            return
        for member in client.get_all_members():
            if member.id == payload.user_id:
                guild = bot.get_guild(payload.guild_id)
                member = await guild.fetch_member(payload.user_id)
        await member.remove_roles(role)
        print(
            f"The user {member.name} was removed from the role {role.name}")```
#

So like that?

hushed galleon
#

er no, you're mixing up the two solutions

jaunty musk
#

😅

royal wind
#

I heard there's an update for discord intents, anyone knows what's suitable for my code:

hushed galleon
#

the goal is getting the Member object corresponding to the person that removed their reaction so you can call remove_roles on them

hushed galleon
hushed galleon
#

depending on what your bot does, you might need members and/or presences enabled too

jaunty musk
#
async def on_raw_reaction_remove(payload):
    if eligible_for_action(payload):
        role = interpret_emoji(payload)
        if role == None:
            return
        guild = bot.get_guild(payload.guild_id)
        member = await guild.fetch_member(payload.user_id)
        await member.remove_roles(role)
        print(
            f"The user {member.name} was removed from the role {role.name}")```

Is this closer? Sorry, this is not my strong suit. 😛
royal wind
hushed galleon
#

yup that looks about right

#

commands.Bot is a subclass of discord.Client, so their example still applies

chilly dove
jaunty musk
#

should I use client.get_guild instead?
client = discord.Client(intents=intents)

chilly dove
#

applies to ALL

sick birch
jaunty musk
#

again, I'm dyslexic, not the best at understanding words and shit.

sick birch
#

not sure if the factory method accepts arguments

royal wind
chilly dove
royal wind
hushed galleon
jaunty musk
#

kk thought so

royal wind
#

So how should I fix it to avoid the privileged message content intent missing?

sick birch
#

You should also enable it in your dev portal

chilly dove
#

if you want you can do Intents.all()

jaunty musk
#

...

Traceback (most recent call last):
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "Z:\Library\Projects\Code\freya\main.py", line 189, in on_raw_reaction_add
    await payload.member.add_roles(role)
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 1014, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request     
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
2022-10-20 23:18:37 ERROR    discord.client Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event   
    await coro(*args, **kwargs)
  File "Z:\Library\Projects\Code\freya\main.py", line 202, in on_raw_reaction_remove
    await member.remove_roles(role)
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 1059, in remove_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "C:\Users\Gimmesamoa\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request        
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
sick birch
royal wind
hushed galleon
jaunty musk
#

That I can't figure out then... it has administer as well as all the other stuff

royal wind
#

Thank you it's online now.

hushed galleon
#

who's reacting, you? what role is it adding, and is that role above or below the bot's role?

#

oh and if its you, are you the server owner

jaunty musk
#

oh man

#

I think it was cause the role was at the bottom of the list

#

🙄

#

moved it up towards the top and it works now haha

hushed galleon
#

the bot's role was at the bottom? that would make sense

jaunty musk
#

yea, didn't know that it needed to be higher

#

makes sense tho

hushed galleon
hushed galleon
vast gale
#

i think it used to exist

#

i'm curious, why did you choose to switch back to discord.py?

royal wind
#

@hushed galleon Also, remember when I said it took a long time? I did this, and I noticed it took a LONG time from Importing modules to Modules imported successfully

vast gale
#

something which is basically impossible to develop against

#

wasn't sure if it was something we could change lol

royal wind
#

I have a question about discord bot + database (finally). First, do I need a dedicated Database cog to handle all the tasks? Say I have another cog file (level.py) that will communicate with database. In this instance, should I give the task over to independent database.py or just handle it inside level.py?

sick birch
#

So i'd extract all database functionality into it's own file

#

Properly typed and documented

amber ether
#

Guys why is it giving me this error? its already defined.

royal wind
# sick birch So i'd extract all database functionality into it's own file

Right, so let's say I have level.py where it's now time to increment ACCOUNT_XP by 3. If I were to distribute the database scripts, I would just do the script there, with many cog files importing sqlite3 module. But in this situation, since everything will be handled with database_manager.py, how do I write it inside level.py to tell it to use some modules in database_manager.py? Should database_manager.py even be a cog file or just normal Python file which will be imported by each individual module?

sick birch
amber ether
#

i cant show it

sick birch
royal wind
maiden fable
sick birch
sick birch
royal wind
sick birch
#

sure but that's not really an issue

maiden fable
sick birch
royal wind
#

Oh, so the database isn't always active. When that increment_xp function is called, then the database_manager.py will access the database.db and make the modification then exiting?

maiden fable
sick birch
royal wind
#

So the database_manager.py that has increment_xp() function will call another module/function?

sick birch
#

can I assume aiosqlite for the sake of brevity?

royal wind
#

If they're conceptually the same (only different syntax)

sick birch
#

yup

royal wind
#

Because I fear I might just gonna get confused.

royal wind
sick birch
#

so you'll probably just create the connection object in your setup_hook or equivalent, pass it into your Database class, which resides in the database_manager.py

royal wind
#

Wait wait, so in python, one .py file isn't a class on its own?

chilly dove
#

@royal windyou can also make it an extension and when the extension is loaded you add a db attribute to the bot instance which can contain a instance of a db class then you can run any function anywhere you have access to bot

royal wind
sick birch
#
class MyBot(commands.Bot):
  ...
  async def setup_hook(self) -> None:
    connection = await aiosqlite.connect(...)
    self.database_manager = DatabaseManager(connection=connection)

database_manager.py

class DatabaseManager:
  def __init__(self, *, connection: aiosqlite.Connection):
    self.connection = connection
  async def increment_xp(user_id: int, xp: int) -> int:
    # update database using `self.connect` here

@royal wind I know that might be a little bit, take your time to process it

amber ether
chilly dove
#

extensions are separate files that you can load into a bot which extends functionality of it

royal wind
chilly dove
#

look at this for an example

sick birch
sick birch
#

An extension is a collection of cogs

royal wind
#

Ah

sick birch
#

Though I'm not sure if it's the best for this usecase

sick birch
royal wind
#

While we're on the topic of cogs, is it okay if I were to use cog files to separate functionality (e.g. level.py is a cog file, economy.py is a cog file, etc)?

sick birch
#

yup that's how it should be

royal wind
#

Ok, just making sure I use it properly.

chilly dove
#

eh you probably right not the best thing to do

royal wind
flat pier
#

have you imported bloxflippredictor

amber ether
#

i did from {package} import * then i did import {package}

sick birch
# royal wind Ok, I've taken my time, and I have several questions: 1. What is `class MyBot`?...
  1. class MyBot is an extension of discord.Client, so it's client at the core but with a few things tacked on (e.g our setup hook). And yes, it's in the main.py. It replaces client = discord.Client(...) with client = MyBot(...) (sorry bad naming)
  2. No, database_manager.py is it's own helper file. Not a cog.
  3. Let's say you have an on message in a cog:
class Levelling(commands.Cog):
  def __init__(self, bot: MyBot) -> None:
    self.bot = bot
    self.database_manager = bot.database_manager

  @commands.Cog.listener()
  async def on_message(message: discord.Message) -> None:
    xp_gained: int = ... # let's say this is how much XP the user should gain
    new_xp = await self.database_manager.increment_xp(message.author.id, xp_gained)
    await message.channel.send(f"Hey, {message.author.mention}! You now have {new_xp} XP!")

Once again, take your time to understand it and let me know with any questions you may have

#

The great thing about this approach is all your database stuff is in one file

#

So if you ever need to change how anything related to your database works, you don't need to hunt down every time you change the database in every command and cog and change it

#

This is a fundamental concept of creating good, clean, maintainable code

dull terrace
#

It's costing me 4c in adverts to get one new user for my bot 7739monkathink if 1 in 300 people subscribe to my patreon for two months on average I'll earn my money back, think it's doable?

sick birch
#

That depends on your bot really, so only you can be the judge of that

royal wind
sick birch
#

Quality of the bot, and I don't just mean how many cool features it has, while that is a part of it

dull terrace
#

It's a game bot which has higher subscribe rates but idk if it has the longevity to keep people hooked long enough

sick birch
flat pier
dull terrace
#

I literally just made an update to it doge_kek

#

The update has doubled retention rates so far though, people are playing twice as long and coming back twice as much

flat pier
#

im not saying dont make updates, just dont do what some bots do and rewrite it for no reason and end up with a completely different bot from what the previous user base enjoyed, updates a great 👍 (should've worded this better but meh my brain is fried so sorry about that lmao)

dull terrace
#

I was exploring some other bots recently and the most crazy thing is the amount that have 100 slash commands

#

Impossible to tell what you're even supposed to do

royal wind
# sick birch 1. `class MyBot` is an *extension* of `discord.Client`, so it's client at the co...
  1. For this to happen, inside this Levelling.py, you must do import database_manager.py, right?
  2. Since you said MyBot class is an extension of discord.Client, the fact that you have that means you modify it. Do you just slap class MyBot(commands.Bot) line along with everything nested in it into your main.py? If the answer is yes, that means you're either defining non-defined setup_hook function or you're overriding the default setup_hook function. Is this assumption correct?
  3. Does the class name have to be MyBot? Is that something Discord determined or that's just something you come up with?
flat pier
dull terrace
sick birch
#

Those are the lines of interest

#

It's basically just a bunch of documentation and a pass

royal wind
#

Right, which means code-wise, it does not do anything.

sick birch
#

exactly

#

it's the user's job to override it with anything useful

royal wind
#

Now my next question is.

#

Unless you somehow specify that you have this class called MyBot or something I can call like CustomSetupHook since it's just random naming, how can you tell the system that this is meant to override that? or is it intelligent enough to tell since the name of the function setup_hook is the same?

sick birch
#

If it's anything else Python will think it's just some function you came up with, not an override

royal wind
sick birch
#

There is another method where you can use setuphook (which doesn't have to be called that) and not use a subclass though i don't recommend it:

client = discord.Client(...)
async def custom_name_setup_hook() -> None:
  ...
client.setup_hook = custom_name_setup_hook
sick birch
royal wind
#

Mine is setup this way. since someone says Bot inherits client, then I should still be able to do it

sick birch
#

But it works! And it's good!

sick birch
royal wind
#

OH right. My brain. My brain is still used to Java, so I thought we're passing commands.Bot parameter

sick birch
#

Ahaha, nah. We're just subclassing it

#

Or "inheriting" it for you java folks

shut rock
#

how do you add custom server emotes in embed?

#

i totally forgot

royal wind
#

Doesn't it mean my main.py will consist of import lines, the class MyBot and its content, and that's it?

#

But wait no. I need to find a way to invoke that class and execute it

sick birch
#
# import lines here

class MyBot(commands.Bot):
  ...

bot = MyBot()
bot.run()

simple as that

royal wind
#

I think I am a bit confused on Java vs Python right now. The class system is a bit weird. In Java, as far as I understand, MainClass.java will have one class

#

But in Python, it seems that main.py can have multiple classes

sick birch
#

You can have many classes in any one file

royal wind
#

Oh yeah yeah

#

I just happened to take "main" as an example of file name

shut rock
#

can i get help 😭

sick birch
#

Yup. In our case though we still only have one class per file

royal wind
#

Good clarification though to make sure it's proper concept

royal wind
shut rock
#

i don't exactly remember how

royal wind
sick birch
#

This is actually relevant with respect to extensions - one extension (a .py file) can contain multiple related cogs (ideally), that you can hot-reload at will

shut rock
royal wind
shut rock
#

i'm going to find that out

#

i'm using hikari so it's a bit different

royal wind
#

I don't think I have personally done it with embed, but I imagine it would be relatively straight forward. What is even hikari when I'm still strugglign with Python lmao

shut rock
#

Unresolved attribute reference 'emojis' for class 'BotApp'

sick birch
#

Yeah it's going to be wildly different in hikari

shut rock
#

yeah

#

that's what i'm struggling with

royal wind
flat pier
#

going off naming alone i assume client has no emotes, you'd still need a guild object to access that data

sick birch
shut rock
#

i know how to do it in normal discord.py just not hikari

royal wind
#

or it's still a python file, but acts as an extension?

flat pier
sick birch
royal wind
#

An extension is a Python file that contains a collection of cogs.
A cog is a collection of commands or event handlers.

economy.py is an extension.
class Economy is a cog. This is because it contains several collections of commands and event handlers (e.g. async def balance(), async def withdraw(), async def deposit())

sick birch
royal wind
#

Ok, that makes more sense now

#

So main.py is not an extension because it doesn't contain a collection of cogs, right?

shut rock
#

plus the doc is confusing, i don't think there is one for emotes anyways

sick birch
#

Again the distinction is important

#

We're only worried about it conceptually

sick birch
royal wind
#

I don't see async def setup(bot) function on my main.py. Unless, whatever I am about to write here inside main.py is considered one.

EDIT: That's not even async def.

shut rock
sick birch
#

well, panic in a reasonable manner. it'll tell you the file doesn't have an async def bot method

#

your main.py isn't an extension - it shouldn't. doesn't make much sense for it to be one

shut rock
sick birch
#

Or try your hand at the docs

tacit storm
# shut rock nobody answering 😭

If you already have a GatewayGuild object, you can call the function fetch_emojis which will return a sequence (or list) of KnownCustomEmojis (All emojis the server has) https://www.hikari-py.dev/hikari/guilds.html#hikari.guilds.PartialGuild.fetch_emoji https://www.hikari-py.dev/hikari/emojis.html#hikari.emojis.KnownCustomEmoji

using that returned Sequence/list, you can iterate through them

This is all assuming you have a GatewayGuild object already, if not use bot.rest.fetch_guild(guildid) to get one. https://www.hikari-py.dev/hikari/api/rest.html#hikari.api.rest.RESTClient.fetch_guild

#

I recommend going to the hikari support server for more questions like this as they will be able to help you better and more in depth and will also be able to explain the docs properly.

sick birch
#

Anyway @royal wind, I'm off for the night. If you've got any questions please do feel free to ping me and I'll answer them in the morning. Cheers 😄

royal wind
royal wind
tacit storm
#

same they get confusing at times

shut rock
#

they're so confusing

#

i know it's a simple piece of code

slate swan
#

yo can anyone help me

#

i am just wondering why my bot doesnt send the embed i have done nothing wrong in the code

slate swan
amber ether
#

why am i getting missing access?

slate swan
#

@frigid trellis can you help me?

#

!codeblock

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

chilly dove
#

@slate swancan you show where you create the embed instance and where you send it?

slate swan
#

i create the embed using python in vscode

chilly dove
#

well i will kinda need to see the code to know whats wrong

slate swan
#

ohhhh

#

ok

#

dm me

#

from cgi import test
from math import degrees
from multiprocessing.sharedctypes import Value
import site
import discord
import http
from discord.ext import commands

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

@bot.event
async def on_ready():

test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')

@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')

@bot.event
async def on_message(message):

if message.content == "What day is it?":
    test_channel = bot.get_channel(1032312979594682491)
    await test_channel.send("The day is the 21th")

if message.content == "Thank you for telling me!":
    test_channel = bot.get_channel(1032312979594682491)
    await test_channel.send("No Problem AnyTime :)")

    myembed = discord.Embed(title="Splunk", description="The bot is running", color=0x00ff00)
    myembed.add_field(name="Site", value="v1.0.0", inline=False)
    myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
    myembed.set_footer(text="This is a sample footer")
    myembed.set_author(name="Splunk")

bot.run('')

amber ether
#

Why am i getting Missing Access?

slate swan
#

like nothings wrong but i the embed wont be send

#

to the server

amber ether
#

bc u didnt send the embed

slate swan
#

but how do i do that

amber ether
#

await ctx.send(embed=myembed)

slate swan
slate swan
#

nvm

#

but whys it yellow under ctx

amber ether
#

After u said myebed.set_author(name="Splunk")

slate swan
amber ether
#

????????????????????????

slate swan
#

yea see this

amber ether
slate swan
#

ok

slate swan
amber ether
#

bc u didnt create a command

#

thats why i told u ur code is messed up

slate swan
#

ohhhhhhhhhh i am watching yt vid so thast prob why

#

and how do i make an command of what

#

see @amber ether name 'ctx' is not defined

#

nvm someone helped me fix it

#

ty

chilly dove
#

@amber ethermissing access? are you getting a error?

amber ether
amber ether
#

Earlier it was working now my bot is not turning on, getting missing access, cant use slash

chilly dove
#

can i see the traceback?

amber ether
chilly dove
#

well then idk without more context to the issue nothing i can help with

chilly dove
#

missing access could mean a variety of different issues without context there is nothing to do but speculate

amber ether
chilly dove
#

@amber etherare you sure that first the bot has the required permissions within the server and second that you are syncing the commands?

amber ether
#

I even used a alt to add AdminBot

chilly dove
#

can you send one of the commands here including the decorator

amber ether
#

when i change application off then on again

#

its shows for 1 second and after that gone????/

#

WTF weird

chilly dove
#

well once commands are synced it shouldnt matter if the bot is on or not should always show the command in the list

#

i would double check permissions as if both the bots are not showing up any commands there is something weird going on there

amber ether
#

but when i use JS it all works perfectly fine without errors

chilly dove
#

does the error happen when you sync?

amber ether
chilly dove
#

can i see full trackback?

amber ether
amber ether
#

Slash command not showing?

amber ether
#

OFC

vale wing
#

Raise the exception and give full traceback

#

Also you should really learn about cogs

vale wing
amber ether
obtuse blaze
slate swan
#

I think you can make something for bot to ignore itself or just make a ignore message count for bot

blazing star
#
async def streaming(ctx):
    await ctx.channel.send('What would you like to stream?')
    status = await bot.wait_for('message', check=lambda x: x.author == ctx.author)
    stream = discord.Streaming(
        name=status.content,
        url=''
    )
    await ctx.send('Streaming: ' + status.content)
    await bot.change_presence(activity=stream)``` it doesnt change the activity
rugged shadow
#

i think it's because you didn't set a url param

#

you have to put in a valid url

zealous jay
#

Why do I keep getting "unclosed client session" in my console

#

Could this be related to my bot getting ratelimited for some reason?

brazen raft
#

What's the traceback