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.
1 messages · Page 110 of 1
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.
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
This?
It says to pack your code in a message like that:
```py
python code here
```
ohhhhh
ok
didnt work
@client.listen()
AttributeError: 'Client' object has no attribute 'listen' this comes upp
why do you have 2 on_message
Oh yeah, use
from discord.ext import conmands
bot = commands.Bot(...)
use an elif block
i am getting dizzy
Then replace all mentions of client to bot and remove the
client = ....
line
where do i put that
Replace
client = discord.Client(...)
with that
but i have to do client
But remove it
ok
so i remove all client and replace them with bot
No reason to use client in your case
Exactly
Then .listen() stuff will work
ok
actually, there's no point in using bot here
, they're not using some spaghetti commands, and having 2 listeners is just pointless
so what wa sthat elif
and where do i put it
a combination of else and if
ohhh so where do i put it
if message.content == "...":
# ...
elif message.content == "...":
# ...
that's some basic python logistics...
but huh where do i put it
but i am a noob
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
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
so i remove one on_message and dont remove one
Might be worth knowing kore python before doing a bot just as side note
Just keep one yeah
tackling discord bots probably isn't the best project to start with then
ik but i really want to do it
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 == "...":
# ...```
ik
```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
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!
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
why did you see it?
Remove one and keep only one
The bot removed your message and clearly said you posted a bot token
but it removed pretty quickly for me
ik
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
You are missing the import and the bot creation is wrong
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
That and the other lines below it
Just keep bot.run(...) at the bottom
so i change if to elif and await to elif
right?
await to elif
?
yea should i remove await and then add elif
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
yea
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
Your second message
yea i will start learn tmr or in 2 days
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('')
ohhhhh so its already imported
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
ok
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
bot was working last night for some reason doesnt work
all the code is the same from last night
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
For another channel, you need either the name or the ID of that channel and get a channel object from that
i fixed the eror
You need to provide
bot = commands.Bot(command_prefix="something here", intents=...)
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'
if ctx.channel.id == your_id:
# your code
Like that?
discord.Intents.all()
where
That will execute the code below if the command has been executed in the channel with that ID
You fixed it, that's fine
sry for ping but quick question you recommend VM or lightsail? on aws surely I didn't pinged wrong person to ask this before
nvm
And it's okay?
You need
bot = commands.Bot(command_prefix="something here", intents=discord.Intents.all())
instead of what you had previously
where do i provide it
ohhhhhhhhhhhh
Well, that's not what you want
Mb !=
== => !=
That's what i want
Oh wait
I misspleded
Ye
You want to execute commands only if it's in that specific channel?
krypton
Yes
Yeah then
if ctx.channel.id == ID:
# Code
is fine
somethings wrong the bit wont reply to my "what day is it"
Yeah as I said, you need to add that in the elif now
I use EC2 t3 micro for a bot of mine that has 1.5k servers and it handles it with about 5% of the cpu used, that one comes free for a year
but i did at the bottom like you said
No you didn't
Your if and your elif both work only for
Thank you for telling me!
so VM alr thx
yea i saw that
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
i imagine once i get past maybe 5k servers i would need to upgrade, but by then i should have a couple patreons
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
And don't forget https://www.pythondiscord.com/resources/ :)
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
yes ty
oh icic you using linux im assuming ?
windows
oh?
no reason why except laziness
im asking cause I don' have t3 free tier on windows
ohh my bad
t2
yeah
alr thank you 
Now if y'all don't mind I'll work on my projects 
basically one month of computing, so if you start a ton of ec2 you'd end up getting charged
per month
so we get 750 per month
you get one instance free basically
ah ic btw can I make you question about connection to it cause im having a problem that doesn't make sense 
are you using windows?
did you download their rdp file to make sure you got details correct?
is the instance started?
yup
and you decrypted the password and used it to connect?
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
looking for it 1 sec
with a source name and port
are you on the inbound rules?
mhm
that's very weird it has that by default on yours
ikr never seen this
i would delete that rule, you don't want all inbound traffic accepted
Create security groups to control the network traffic that can reach your Amazon EC2 instances.
yeah, bare in mind that your ip can change every once in a while if you have a dynamic ip
tysm 
Wondering what that has to do with Discord bots development 
np, took me hours to figure that out on my own with little experience in setting this stuff up
discord bot ʰᵒˢᵗᶦⁿᵍ
its for host bot

smh only bad thing about this free stuff is that pc is laggy af 
Channel is for bot development if you read the description of it
Alternatively there is a thread in this channel for hosting
its still bot related- well nvm, im sry if it was annoying for you 
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
once again I already said im sry.. idk what you expect more with this? me kneeling or what
its still bot related
You apparently still believe it belongs to this channel
And you still keeping typing 
Why would I be disrespectful and not reply to your question?

yea i have that dude blocked we should just report him at this point
how do you make a discord bot specifically a tipbot
Who krypton?
can someone link me
I wouldnt say that from what I've seen
save the drama for yo mama
i mean if another person is having issues with him then its something he is doing wrong
Because he's experienced and is ruthless doesnt mean he has an ego
ruthless? nah straight disrespectful

Well, if you think that you should report it to @novel apex
you can know ur shit and not being a weird ab it
anyways
I doubt you will get far as moderators havent muted or banned him
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
May i ask how the assumption of half of the staff in the dpy server are "weirdos"
you realize you are committing slander right
can someone help me find information on building a discord tipbot that is compatible with avalanche tokens?
Knowing your stuff and being ruthless isnt really being weird, i see it allot in the programming community across platforms, doesnt mean its correct but thats just how people behave
im sure the feeling is mutual so quit acting like you are the better one
?
he probably doesn't like you either jaymart
I think krypton doesnt even know who he is, from what I've seen
so just leave each other alone and let it be
Yeah, i agree
yeah he does lmao i have him blocked for a reason
I do know the feeling as some experienced developers help you in a weird manner but lets change the topic
please quiet down
If you feel that sure, but lets change topics
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
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?
is there discord library for python2?
Hopefully not. py2 is long dead.
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)
can you explain in more detail what you're trying to do?
basically simple for personal use discord bot communicating with my school's site
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?
I think there's a bit of a misconception here between SQL and "online database like mongo"
SQL is only the language, not the database and mongodb is not necessarily an online database (though the company does provide DaaS for you)
Probably yes. I'm currently taking basic of database class, and I start to learn a little bit, but just a little bit.
But I believe database for discord bot should be relatively simple (adding entry if doesn't exist, modifying entry, deleting entry)
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
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?
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
It just lets you interface with an SQLite database asynchronously
Is SQL something like
CREATE TABLE {
....
}
FROM * SELECT ...
etc etc?
Ok so let's say I want to use that. how do I incorporate it with Python language discord bot?
Do I use SQL syntaxes inside the Python IDE?
Robin since you here can I make 2 quick questions?
Probably, but for now, as a complete beginner, I think I'll stick to one slowly until I understand before moving on
You'd use something like
sql.execute("Select * FROM table_name ...")
Aah
Given you have everything else set up properly
Fire away
Ok, is there any specific module(s) I need to import? Is it just import sql?
import sqlite3 if it's not in a discord bot
It's part of the stdlib
Ah, ok. So I don't have to install the sqlite or something into the machine
SQLite is pretty simple so it's just a database file
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"
Also when you say this, why isn't the file .sqlite but .sql?
or did I just misremember it?
Use AWS RDBMS
And GitHub CI/CD pipeline for updates
RDBMS? 
This was from my assignment. sqbpro
Relational database management system
Mouthful, I know
sheesh
Doesn't really matter
why is commands a function
is it hard to set up?
Not sure if you know this but file extensions don't mean a whole lot
Most things on AWS are a royal pain in the ass to set up
alr I will give a look into it thank you
I have a suspicion that that's the case
But now you say that, it's confirmed
imma try it ig tysm
Hmm..?
Thank you too Robin. very helpful
My pleasure
it works if i just set it as commannd
do like _commands
The name of the function?
that would work but i dont want to type /_commands
It's probably shadowing from discord.ext import commands
Pass in name="commands" into the decorator
commands get connected with this
Yeah name clashing just use underscore as mentioned
Ah, is this to make sure only admins can do specific things like ban or the like?
then i would need to do /_commands
I need to remmeber that
yeah
but i wan everyone to me avable to do/commands
Not if you pass in name kwargs
@royal wind To specify role permission for a method
Oh btw robins
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?
invalid syntax
I hope you didn't copy paste that
bot is a subclass of client which means bot has everything client had and more. With bot it makes it easy to create commands and whatnot
It was just meant to show where the name kwarg goes
Remove the copy paste and edit your existing code so it looks similar
Ah ok. Thank you. Back then, I was so frustrated because nobody really explained what the difference. They only said to use specific method to start an easy bot
So that's why bot can do lots more. Because it inherits everything from client + its own stuff
Yeah tutorials often do that, I don't recommend them
Do you know a channel that has pretty good tutorial for discord bot?
Most of them are pretty bad
Shot, I thought so
ok tysm
See the pins in this channel for resources
I kept jumping back and forth. It was so hard
it works now ty @sick birch
Np
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.
Ok, thank you
I can see that. But until now I only start taking advanced class with python. Like, it's the first time I understood what that @blablabla mean. Then again, my understanding is still very limited. I believe my code from like a couple months ago was just pure spaghetti code. I'm trying to straighten all of them (at least many of them if all isn't possible)
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.
Exactly. Store XP and calc level from it
This is a bit of math
Hmm
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
Sounds like a simple linear equation
Actually mmm
Is it possible to not make it linear?
No I think it's exponential
It would've looked something like this
How are you getting these numbers?
That's starting xp + requirements to advance
That's just manually calculated using hand
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)
Ohh
Requirement to advance is calculated from the previous requirement * 1.25
Ugh I was never good at math
So you can be good at programming and not with math?
There's hope for me
Can you say the problem your having again? Just got on
Not really a problem
We're brainstorming how to make an exponential leveling system
Trying to think of an equation that does it
It was a problem. Now no longer. At least hopefully. If you see me popping back, then it's because it's still a problem.
It was related to how to make dynamic xp requirement instead of just "every 100xp, raise level by one" thing
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
True, but I think it'll be fine if I can put some reward system that's pretty beneficial (and I can think of some since it's related to MMO game)
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?
Isn't that the point
Okay, then it would still be pretty simple though just raise it to a power
The thing is its cumulative
So it needs to add the amount of XP needed for the last one
Let's say you start off with Level X which needed 100 EXP, the next level would be Level z WITH 100**2
Recursion maybe?
Oh, no no. I'm not doing THAT kind of exponential. It's just whatever requirement from previous level multiplied by 1.25 (25% increment in requirements)
It's more like a curve, but not exponential curve I say
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
Okay, if your just multiplying by some number that would just be linear growth
Yep, thanks for verifying.
You have different types of exponential growth, linear, cubic, then exponential like x^2
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?
There is probably a few more that I'm not remembering
Cubic is just exponential, but with 3 instead of 2 right?
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)?
You can probably use timedelta
timedelta? Never heard of it before
You mean to literally put a last_update date?
To check if it's within x seconds?
!e ```py
from datetime import datetime, timedelta
last_leveled_up = datetime.utcnow()
cooldown = timedelta(seconds=20)
if datetime.utcnow() + cooldown < datetime.utcnow():
print("Foo")
@pliant gulch :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Basically, create a timedelta object, delta meaning difference right? So then you can add that offset to check it from the current time
Ah, makes sense.
Yeah. I thought timedelta was just some module name that's encompassing ALL time related stuff in Python
Okay, that's perfect, I can use that for a lot of things probably
👍
@royal wind To give "cooldown" for an action
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
Shouldn't this line comes from the databse btw?
datetime.utcnow() I assume would give us current time
If your using a RDBMS they almost 100% have a timestamp data type or something similiar
RBDMS? Relational B... Database Management System?
datetime.utcnow() then do a query to append to your database at that location with TIMESTAMP for example
Like in PostgreSQl
Yes
I'm planning to use SQLite
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
Yeah, I believe it's DATE type something like 2022-10-20 05:00:00
ISO8601 Formatted
But can the same command datetime.utcnow() process that information? Won't different format mess things up?
There should be no problem if you format with ISO8601
Okay
!e ```py
import datetime; print(datetime.datetime.utcnow().isoformat())
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
2022-10-21T00:00:32.584967
All these things are all new territories for me.
is this for the leveling cooldown mentioned earlier?
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
why're you using a database to store the last time it was updated?
If I don't store when the xp was last updated, how can I know if it was within spam zone (e.g. within 5 seconds)?
Oh, yea the time can be turned back into a datetime instance which you'll need
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?
use a dictionary for that instead, it'll probably save you time. And perhaps use time.time() instead of timedelta
!e ```py
import datetime; print(datetime.datetime.fromisoformat("2022-10-21T00:00:32.584967"))
What
Isn't dictionary a data structure inside Python and not the database?
save the somewhere, and check if they're the same?
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
2022-10-21 00:00:32.584967
correct
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
That would make your data non-persistent now
You'd need to populate somehow which makes no sense to store temp inside memory
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
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
Not the time a message was sent, the most recent time a user has leveled up
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
ah, sorry for my misunderstanding then
Huh, I am not following that logic andy.
If you use a dictionary to store the cooldown times, it'll disappear when your bot shuts off
Since the dictionary is in memory strictly for the lifetime of your bot there is no data persistence
Right, that makes sense. Because the information isn't in physical layer, but only stored in RAM
Yea, meaning database is 100% way to go since it persists the data
and he doesnt want that because then it wont prevent spamming when the bot restarts
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?
Or at least once before a new cooldown is added
I added that last part cause I just realised that too
Ah, I understand now.
doesn't that mean that the user will be able to gain xp from spam right until the last part, when they're about to level up?
Now the question is, why would Lee recommended using dictionary? Is it to reduce the amount of data stored?
I initially recommended it because it was quicker if you were storing the last time a user sent a message (spam detection system-thing). However, if you're going to be storing the last time a user leveled up, then it'd be best to use a database. Thought I'm not quite sure why you'd do that in the first place
I was not thinking of storing last_update for user level up. I was using it for when the last message was sent by that user.
I'm not sure exactly what the algorithm does for their case but. All I know is setting a cooldown and adding a check to prevent leveling up would work
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
anyone have experience opening and closing mariadb connections inside a command?
if you're going to check when was the last time a user sent a message, using a dictionary to store user id and time would probably serve you better than connecting to a database and checking stuff there. In that case, you wouldn't need the data to be persistent either way, because it's just spam
Right... but say the scale is pretty big, won't it occupy lots of memory?
Note: not that my server is big. This is just hypothetical question because I am also learning how to program a good software
depends on how you access the data on the dictionary, and you could probably dynamically remove the users from the dictionary
On the database?
Or in mem
No, he was suggesting me to use memory-based Python's dictionary to keep track of user's last sent msg date
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
Hmm, ok. I guess it's fine using memory for now. I guess even in real world, when situation changes, things get changed anyway
hmm
Why do you need the date?
For what functionality, I mean
^ that's the other thing, you'd probably be better off using time.time() instead of an actual date
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
lmao
Let's say I want to make sure user only gets XP once every minute. If they send 2 messages within 1 minute, Only the first one counts.
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
"not tell them to not do what they want to do"
OMG I love you for this. So many 'tutors' blast newbies for doing things wrong by giving super brief but hard to understand explanation and just disappears. People learn from mistakes too
This thing will run on each message, yes?
That makes sense too.
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
You may as well be storing the users current XP in memory and perform the same bulk dump to DB
this is what I do. It works pretty well
Yeah, good idea
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
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?
Instead of having a cooldown for leveling up, have a cooldown for getting exp
Good solution without storing any data
thisssszzzs
Oh yeah, I don't even have ACCOUNT_LEVEL attribute. ACCOUNT_LEVEL is a table name
I probably should've specified that to avoid confusion.
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
The actual account level is mathematically calculated
but face value it looks like it'll work
it does. I currently use something similar for presence updates event
Okay, so it looks like I have all the recipes to make the level system
funny joke
in memory off memory
id still go with a dictionary then just add and remove members from the dictionary as the cooldown is triggered with datetime.timedelta personally
Thank you @pliant gulch @fading marlin @sick birch
👍
can i get help with mariadb connections now? 
I would say it might be more suited for #databases but we just had a long conversation with @royal wind about databases here so I guess I can't say that lol
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
mariadb kinda sucks btw, consider using another db
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
im already 500 lines of code into this bot im not changing now lol
theres 40 database interactions id have to change at this point
Bro, I can feel that 💀
Though I am now revamping my code
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
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:
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
I see
you need to install any packages you use in your code to your pc
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
have you set up a virtual environment for your project?
hm thats a weird place to put your script
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
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
Ok, I understand that part now.
so in your case it seems you have a virtual environment created
Right
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
The pycharm terminal should have the venv activated by default
A surefire way would be to add packages through pycharm's UI
oh didn't notice yall moved
Yeah, was suggested to move. Anyway, I think the error is fixed now that @hushed galleon helped me. Thanks
how is it undefined
Anyone know why this:
await message.channel.send(f'')
is giving me this:
:logo:
When trying to get my bot to use custom emoji's?
wdym??
it will sednd the emoji
its not...
give ss
it has the right perms
.
Yea that just breaks the code
first your token is visible and you need to reset and second you are importing that as cs so cloudscraper is not a variable
@jaunty musktry using this https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_emoji then use the is_usable method on it to make sure you can actually use it then you can string the instance to the get correct output that can be used in a message
Now I'm dealing with this:
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
get_emoji shouldnt be returning that
Oh I ended up just adding all the emoji's to my server itself just to not deal with custom emoji shit
well then without knowing that context of the forbidden error i cant help
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()
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'```
you'd still be breaking ToS
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
yes i know, i was gonna do another solution, by using it in cogs because its alot cleaner, and better.
it's still not going to be an ideal solution
payload.member was not found for whatever reason
Might be an intents issue
Would it be cool for me to post my entire code here? I'm just not really sure what to do. 😅
No need, the issue is right there
so how do i go around from that?
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>
@jaunty musk see the disclaimer for payload.member in the documentation:
!d discord.RawReactionActionEvent.member
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
What's a guild? This stuff is kinda confusing o.O
a synonym for a discord server, you'll see it used often in discord bot development
"server" has a different meaning when it comes to developing so they call it a "guild" to avoid confusion
alright, sooo what should I be looking for... heh
Only available if event_type is REACTION_ADD and the reaction is inside a guild.
Perhaps the reaction is coming from a DM?
Only available if event_type is REACTION_ADD ...
given that you're using anon_raw_reaction_removeevent, the payload wont have this reaction_add type which means member will always be None
i believe the error is in on_raw_reaction_add
the traceback says otherwise
looks like they've already accounted for it by not using payload.member in on_raw_reaction_remove
ahh
actually good point, the code seems to be outdated
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
is there some better code to use 😬
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
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
This is my discord bot life LMAO. That's why my code looked like mummies
e.g. py guild = bot.get_guild(payload.guild_id) member = await guild.fetch_member(payload.user_id) await member.remove_roles(...)
simple solution: delete the whole thing and re-write it in rust ||/s||
o.O
/s = sarcasm?
lol I kinda rely on Github Copilot. I'm dyslexic af so I'm super garbage at writing code.
what have other people's experiences been with using copilot for discord bots/API?
if i'm to guess it probably regurgitates shitty code it found off random github repos and youtube tutorials
uhh bot.fetch_member isnt a thing and shouldnt be using fetch if you can help it
right, guild.fetch_member
its a bit of a necessity if the cache doesnt contain the member
why wouldnt the cache contain the member?
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}")```
so how should I add this? 
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
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
well itd be in your on_raw_reaction_remove event, replacing the code you have that's setting the user variable
if only discord.py had a getch method :(
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?
er no, you're mixing up the two solutions
😅
I heard there's an update for discord intents, anyone knows what's suitable for my code:
the goal is getting the Member object corresponding to the person that removed their reaction so you can call remove_roles on them
this example does entirely that in two lines, so there's no need to have a for-loop going through every user
usually the default intents + message_content (since you're using commands.Bot) is sufficient
depending on what your bot does, you might need members and/or presences enabled too
you must pass in intents as of 2.0 https://discordpy.readthedocs.io/en/latest/migrating.html#intents-are-now-required
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. 😛
It's using discord clients, i'm not using that
yup that looks about right
commands.Bot is a subclass of discord.Client, so their example still applies
should I use client.get_guild instead?
client = discord.Client(intents=intents)
applies to ALL
Can I do this this way instead?
not if you want message contents
again, I'm dyslexic, not the best at understanding words and shit.
not sure if the factory method accepts arguments
I'm confused now. How should I do it? It used to not be like this
yup that gets you the default with the exception of the privileged ones
thats how you defined your client so sure, that would replace bot
kk thought so
So how should I fix it to avoid the privileged message content intent missing?
Yeah intents have become required in 2.0 to get users to actively think about their intents and deciding rather than letting the bot do it for them
intents = discord.Intents.default()
intents.message_content = True # important
client = discord.Client(intents=intents)
You should also enable it in your dev portal
if you want you can do Intents.all()
...
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```
Where
Bot
Found it, thank you
apparently the bot doesnt have permissions to add the role to whoever added the reaction
That I can't figure out then... it has administer as well as all the other stuff
Thank you it's online now.
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
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
the bot's role was at the bottom? that would make sense
robin with the sacred power of using reactions in #discord-bots >.>
my last occurrence has been with someone asking for help with copilot-generated aiohttp code that made a request to a "/v10/users/@me/library" endpoint, mistakenly thought it was a user-account endpoint until i realized it probably doesnt exist
i think it used to exist
i'm curious, why did you choose to switch back to discord.py?
fanboyism
@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
ah :^)
something which is basically impossible to develop against
wasn't sure if it was something we could change lol
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?
The way I'd do it, is you will eventually have more than one cog using the database, yes?
So i'd extract all database functionality into it's own file
Properly typed and documented
Guys why is it giving me this error? its already defined.
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?
why are those crossed out? it'd be very helpful to know which variables are not defined
its a package that i crossed out
i cant show it
Right, so let's say I have level.py where it's now time to increment ACCOUNT_XP by 3
In my database.py file, I'd have this:
def increment_xp(user_id: int, xp: int) -> int:
""" Increments a user's XP points in the database and returns the new XP """
raise NotImplementedError
So inside level.py, when it's time to call the increment_xp function, how would it do it?
Damn, what an important and complex piece of code
Just increment_xp(ctx.author.id, 3), for instance
oh shut up you
This would mean I have to import database_manager right on the level.py file?
sure but that's not really an issue
You're Welcome 😄
your*
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?
You are*
You might want to make it so that you have a database class that manages it's own internal connection objects
Could you elaborate more?
So the database_manager.py that has increment_xp() function will call another module/function?
can I assume aiosqlite for the sake of brevity?
If they're conceptually the same (only different syntax)
yup
Because I fear I might just gonna get confused.
Ok, that's fine.
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
Wait wait, so in python, one .py file isn't a class on its own?
@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
I am completely lost with this suggestion. What do you mean by extension?
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
Anyone please
extensions are separate files that you can load into a bot which extends functionality of it
I am trying to understand it right now
look at this for an example
Not sure about this one. You want to be able to hot-reload extensions whenever, but you don't want to keep making new database connections
That sounds like cogs.
The two are very closely tied
An extension is a collection of cogs
Ah
Though I'm not sure if it's the best for this usecase
This is the most common method I see or the one that makes the most sense
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)?
yup that's how it should be
Ok, just making sure I use it properly.
eh you probably right not the best thing to do
Ok, I've taken my time, and I have several questions:
class MyBot? Is that your main.py?database_manager.py is not a cog file, correct?level.py, on the line where I would increment the XP, how should I tie it together with these?have you imported bloxflippredictor
nvm
i did from {package} import * then i did import {package}
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)database_manager.py is it's own helper file. Not 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
It's costing me 4c in adverts to get one new user for my bot
if 1 in 300 people subscribe to my patreon for two months on average I'll earn my money back, think it's doable?
That depends on your bot really, so only you can be the judge of that
Yes, which is what I really want to do. Clean, organized, and avoiding spaghetti as much as possible. I'm still trying to understand it
Quality of the bot, and I don't just mean how many cool features it has, while that is a part of it
It's a game bot which has higher subscribe rates but idk if it has the longevity to keep people hooked long enough
Take your time. I'd rather you understand it fully
people will love anything that doesn't have stupid updates that change what the user liked (unless it was broken)
I literally just made an update to it 
The update has doubled retention rates so far though, people are playing twice as long and coming back twice as much
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)
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
Levelling.py, you must do import database_manager.py, right?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?MyBot? Is that something Discord determined or that's just something you come up with?usually they start off with a tutorial or something to make it easier to get into but yea i get that its like trying to use dank memer when you've never touched a discord bot sometimes tbh
I'm not gonna say which, but one bot had tons of commands and then I did /help and it sent me three pages of embeds to read
async def setup_hook(self) -> None:
pass
MyBot is something I came up withThose are the lines of interest
It's basically just a bunch of documentation and a pass
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?
Actually the name of the class can be whatever you want. The actual method name, setup_hook, has to be the same
If it's anything else Python will think it's just some function you came up with, not an override
Right, okay I understand. So since this is in your main.py, then at some lines, you have to invoke this class too right?
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
yes, it's similar to doing client = discord.Client(...) but you'd instead do client = MyClient(...) or whatever you called the class
Mine is setup this way. since someone says Bot inherits client, then I should still be able to do it
If you did
class MyBot(commands.Bot):
...
MyBot would inherit commands.Bot which inherits discord.Client.. weird, right?
But it works! And it's good!
You could replace this with something like
class MyBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix="!", intents=intents)
OH right. My brain. My brain is still used to Java, so I thought we're passing commands.Bot parameter
IF I use it this way...
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
# import lines here
class MyBot(commands.Bot):
...
bot = MyBot()
bot.run()
simple as that
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
can i get help 😭
Yup. In our case though we still only have one class per file
Good clarification though to make sure it's proper concept
Oh, I know the answer to this
replace 'Cash' with the name of the emoji
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
yes but it needs to be in an embed
Since you have the object containing the custom emoji, can't you just put it normally?
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
Unresolved attribute reference 'emojis' for class 'BotApp'
Yeah it's going to be wildly different in hikari
1 .py file contain multiple related cogs. In other words, one cog file (level.py), contain multiple cogs inside??? I'm not following that
going off naming alone i assume client has no emotes, you'd still need a guild object to access that data
I'm trying to think of an example. More times than not you won't need multiple classes per file. What I mean is that one extension (level.py) (the differentiation is important) can contain multiple cog classes
yeah i can't find it anywhere in the hikari discord server
i know how to do it in normal discord.py just not hikari
COG refers to a class that handles specific task for Discord bot.
filename.py (aka python file) is referred to as extension?
or it's still a python file, but acts as an extension?
https://www.hikari-py.dev/hikari/index.html i'd try searching the docs rather then the server
A cog is a collection of commands and events
An extension is a collection of cogs. It's also just a python file
spot on
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())
you hit the nail on the head once again, my friend
Ok, that makes more sense now
So main.py is not an extension because it doesn't contain a collection of cogs, right?
nobody answering 😭
plus the doc is confusing, i don't think there is one for emotes anyways
Well an extension, conceptually, is a collection of cogs (or just one). But discord.py doesn't know that - so technically a cog is a python file with an async def setup(bot): function
Again the distinction is important
We're only worried about it conceptually
discord.py is worried about it technically
Unfortunately Hikari users are far and few between, so support is a bit thin. I'm afraid it may take a while
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.
yeah there's a bunch of people in here who know hikari so i'll just have to wait
a setup function is what makes a regular python file an extension
without it discord.py will panic
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
do you know anyone who know's hikari? or should i just keep opening help channels
None, sorry. Best bet is to open a help channel and wait
Or try your hand at the docs
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.
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 😄
Right, so my understanding of it being not an extension is correct.
Thank you! I probably will. Writing the code to avoid as much spaghetti and using proper convention and clean is hard as hell
i hate the docs
SO MUCH
same they get confusing at times
yo can anyone help me
i am just wondering why my bot doesnt send the embed i have done nothing wrong in the code
can you help me?
why am i getting missing access?
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 swancan you show where you create the embed instance and where you send it?
why?
i create the embed using python in vscode
well i will kinda need to see the code to know whats wrong
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('')
Why am i getting Missing Access?
..
bc u didnt send the embed
how sit messed up
where do i put that
nvm
but whys it yellow under ctx
After u said myebed.set_author(name="Splunk")
yea ik but whys my ctx yelllow
????????????????????????
just try and run the bot
ok
but it still doesnt send my embed
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
@amber ethermissing access? are you getting a error?
yeah thats my error
prob watch more tut
Earlier it was working now my bot is not turning on, getting missing access, cant use slash
can i see the traceback?
i cant bc i closed vscode for some reason
well then idk without more context to the issue nothing i can help with
man fu
missing access could mean a variety of different issues without context there is nothing to do but speculate
Even a Verified bot cant use Slash wtf
@amber etherare you sure that first the bot has the required permissions within the server and second that you are syncing the commands?
yes!!
I even used a alt to add AdminBot
can you send one of the commands here including the decorator
when i change application off then on again
its shows for 1 second and after that gone????/
WTF weird
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
but when i use JS it all works perfectly fine without errors
does the error happen when you sync?
ig yea
can i see full trackback?
Dms
Slash command not showing?
OFC
What lib
nvm
sry for ping, is there any guide on how to set up this?
I think you can make something for bot to ignore itself or just make a ignore message count for bot
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
Why do I keep getting "unclosed client session" in my console
Could this be related to my bot getting ratelimited for some reason?
What's the traceback