#discord-bots
1 messages · Page 628 of 1
Are u in pycharm?
Yes
len(bot.guilds)
pls dont tell me to change from pycharm
Set a breakpoint at the start of the function and attach the debugger
No, pycharm is good
event is not being triggered.. also how do i attach debugger, i was curious about that earlier!
just use wait_for at this point
yeah fr. im gonna try this debugger thing first tho
U can just click the icon next to run icon, it looks like a bug
any chance you could send some general code for the wait_for ?
I click it and then what.. what is a breakpoint? is that the red circle on the side
Wait for will only let u react once and then it wont register reactions anymore
That's fine
It’ s in docs
Yes
Yeah i know it's in docs but it's confusing sometimes
bot.wait_for(event, check, timeout)
to wait for a message from a specific channel I would do
await bot.wait_for("message", check=lambda m: m.channel == some_channel_object, timeout=60)
It has an example for wait for
uh ok i set the breakpoint and now nothin is happening even though im running the command
what is lambda?
anonymous function
a function that doesn't have a name
Set a breakpoint b4 you run the command
basically a temporary function
does check have to be a function?
yes
Yes
I did?
Put it one line under
Will this debug the code from there on?
it wont debug, thats your job
No, this will stop the code there for you to manually go through it and debug it
U move through it using F8
you may change values of some variables, do stuff like running functions and then press c and hit enter to continue
or exit() will stop
Okay cool I used the word debug wrong
i'm scraping urban dictionary
here's my code :
query=input("Enter A Word : ")
data=requests.post(f"https://urbandictionary.com/define.php?term={query}").content
soup=BeautifulSoup(data,"html.parser")
for i in soup.find_all("div",class_="meaning"):
print(i)
and i'm getting :
<div class="meaning">A person who writes <a class="autolink" href="/define.php?term=funny" onclick="ga('send', 'event', 'Autolink', 'Click', "funny");">funny</a> and motivational <a class="autolink" href="/define.php?term=posts" onclick="ga('send', 'event', 'Autolink', 'Click', "posts");">posts</a> on <a class="autolink" href="/define.php?term=Facebook" onclick="ga('send', 'event', 'Autolink', 'Click', "Facebook");">Facebook</a></div>
how to get inner html of div and anchor tags?
i use a different lib so idk
but i have a unfinished project of it, i can give you want
oh wait
If the content is rendered dynamically, you wont get it
don't think that's related to discord bots
actually mine works fine, that was a different project
ik
Debugger gets to the async def on_raw_reaction_add(payload) line
Now u go from there
Press F8
Yeah then it stopped
Press F8 again
Like the debugger stopped going and the screen at the bottom lost all the variables in it
It completely ended but I can try again
Where did that happen
Guys does anyone know easy way to pass flags in command. i want to do something like this: b!search car --doorcolor black
use argparser
never used, how can I?
read its docs
plenty of tutorials out there
At the async def on_raw_reaction_add(payload) line...
Step 1: Read the docs
Step 2: if you dont have a clue what ur doing refer to step 1
Step 3: if you have a really specific problem that you can't find the solution of anywhere, only then should you ask for help
Put a breakpoint inside this event and remove all others then trigger this event
which rarely happens
Could it possibly be the decorator ive got in there?
Exactly
this channel would pretty much be dead if people followed that advice lol
LMFAOOO
okay fuck this on reaction add shit. lets try wait for
isnt reaction add an event and wait_for waits an event
happens a lot if you're trying to use something that isn't properly documented or doesn't have many users
i just hit ctrl and press the object and read the sourcecode if that happens to me 
I click F1
what does it do
And download sources
Displays docs
yes
morning everyone
Gm
morning
So how would I get the (user) parameter if I'm in the DM channel?
are we doing wait_for()? brilliant.
user parameter?
elaborate
Bro 😭
lol
Fuck ima go kill myself brb
and you cant get anything
Pls
through DM channels
🙏
FUCK man I AM reading it
unless the bot is there
Ok chill
then why do you feel the need to ask
everything is documented
U ONLY DECIDED TO GO READ IT NOW 😭 😂
Because this shit like the word coroutine makes little sense to me
wait_for() <<<<<<<<<<<< READ THE DOCS
Bro do you know how many tabs of the docs I got open???
google it
then learn what it means my dude
then read articles on it
🤣
I'm still learning, and sometimes YOU guys can simplify and explain this shit the easiest!!!
Why did u go into asynchronous programming if coroutines dont make sense to u
you're gonna have to learn to be independent
And then if i don't understand something, I can continue to ask questions and possibly understand it further
THEN WHAT is this DISCORD server for?!?!?!?!!?!
helping people with problems and not helping them with literally every single thing they don't know
for the dumb people to help them until they are independent
Man I've learned a LOT from asking questions in here. I've read docs, and when I come across something that confuses me, I ask in here
Honestly I just wanna give him the snippet at this point
you should have googled but ok
LMFAOOO
if you don't understand it you must first try to see if you can learn it online before asking questions about it
Sorry I'm not god at coding rn, I started like a week ago
Hahaha
why are you trying to make discord bots
I'm farther into it than you thinK
get the basics covered first
so tell me, what are dictionaries?
what is async?
you couldn't tell what an attribute was a while ago lol
Ur saying ur doing asynchronous programming a week into coding?
BRO WHAT 🤣
and what do you call the things?
💀
fuck man let me go take a class on it rq
funny
Whats difference between class and class instance?
I'm just learning this in my spare time, that's why it's hard to remember what everything is called
tell me the difference between these two:
class foo(object): ...
class foo(): ...```
you need to learn tuples, arrays, variable, asyncio, functions....
or a class variable and an instance variable
I would believe a class variable is when you define it and an instance would be the unique variable that is created whenever you create an instance of that class
I dont use them much *cough *
is that right?
Also learn about abstract classes and design patterns
it shows that you're not very familiar with these things
unique variable? *attribute
class variable
ayo wtf
fuck man i knew i should have said attribute
🤦🏼♂️
but if i did and it was wrong i figured you'd have the same reaction
🤦♂️
attributes are basically class variables, and what they are calling an unique variable is called an instance
just learn basic python
ok
Ok bye. I wont come back here until I've mastered it. Just means this project that has been a lot of fun for me will have to wait a long time
hello
im trying to store a really long multi-nested dictionary into the db in replit but its giving me 'circular reference detected'. anyone know what that is
ok
class Beginner:
IQ = 0
kazido = Beginner()```
here `kazido` is an instance of `Beginner`
i built a discord both with over 250 commands? is that a big thing?
ok
Why do you guys have to be so mean
LMFAOOO 😭
I'm just asking questions so i can understand what I don't better
we're not being mean we're trying to help you
That is too much
im explaining
😭
You're being very mean while trying to "help" me
you forgot __init__
because you're lazy and can't be bothered to read the docs
???????
it's already documented
you dont need an init
Are you targeting me here =D
wait rly? I put that in everytime
now you need to learn python -_-
yes lol
its not necessary
Not necessary
damn
nah 💀
no lol
This ain't even all my tabs. I've been reading docs all day bro
Yea u r hehe
I put __init__ even when I don't need it just because it looks nice
My book was lying to me all this time
I mean they look hot in PyCharm
<@&831776746206265384>
THANK YOU HOLY FUCK!
i 100% respect that and I love you as a person
My frustration
!mute 584662127470575616 Investigating.
:x: The user doesn't appear to be on the server.
What do u put inside it?
Thanks!
but you need it
nothing
LMFAOOO not even a pass?
Ofc they ignore it tho because they are already engineers
of course I put a pass
the things you want to do when someone tries to make an instance of the class basically
I don't ignore the docs
No, you ignore what that guy just said
like declaring attributes
you dont need an init lol
I refer to it when I need it
This here
I think they were asking what I put in it if I don't need it
oh lol
My book was lying to me
No I meant, what does he put in it, he said he makes constructors when he doesn’t need them
haha nothing go brrrr
ok i hate to be this guy but
@velvet tinsel You ignore this
!ot
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
oh yeah i had to reread the conversation
would this be right embed.add_field(name='Creation Date', value=int(guild.created_at.timestamp(f"%a, %#d %B %Y @ %H:%M:%S %p (<t:1601130860:R>)"))? im just trying to make it show when the bot joined each server cuz its in multiple servers and obviously those would be different dates and not just a year ago and idk how to do that
I actually did respond but ok
No, you said "I don't ignore the docs"
that's a fact, I don't ignore it
the docs are the class lol
See? You don't actually care that what he brought up was valid and so you just make a "funny" comment
It's very helpful for ME at least to come in here and ask questions when I can't 100% understand what is happening when I look at the docs or watch videos on what I'm trying to do
Store the timestamp on when bot joined into a server
look my guy just go get familiar with python
timestamps?
any one have code for help command bot ?
please can you go to an off-topic
Id prefer to help/ignore instead of checking someone's knowledge , just saying
no
just subclass commands.MinimalHelpCommand
idk i got from the official dpy server, and they really didnt help
we're not gonna spoonfeed you any code
I'm NOT ASKING YOU TO
I'll read it
Wdym?
how old are you
curious
trying to be spoonfed but we're not going down there
I'm 18 and college is stressing me out and I just wanna learn some code to have fun
||oh no oh no oh nono no ||
I don't have all the time in the world to learn python aside everything else that is going on. Which is why I come here to ask questions. And half of you act so high and mighty cause you already know everything there is to know
anyways
God I'm tilted now.
!ot before kazido lets out everything
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
its alright homotrollius has a small pp
Nah, I'm going to a help channel. Shoulda done this a long time ago XD
small pp'd dudes were considered intelligent among the greeks
💪
My dick is 8 inches hard
if u dont have to use lube u aint doing it right
Okay yall can chill a bit
ok we are going in a wrong direction now
!shh
✅ silenced current channel for 4 minute(s).
Some reminders:
Insulting anyone is not ok, especially for being a beginner.
You are free not to answer any questions you don't want to; no one is forcing you to respond.
The topic here is discord bots. Keep your comments on-topic and appropriate.
If you have a problem with another user, contact the moderators. You can always open a @novel apex.
!unshh
✅ unsilenced current channel.
use bot, not client
you defined the var bot for your Bot object
Who?
tnx
I'm out of here
how i can create command for my bot
kazido , could you mention me in the help channel you occupied , if any
!d discord.ext.commands.Bot.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
basically py @bot.command() , with an async function with ctx as its first parameter
Where did u get client from?
where ctx is commands.Context
yea , was about to say that
thanks
!d discord.Member.joined_at and ctx.me returns the bot's member object, so it will be ctx.me.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
hello, i am trying to show the data which i fetch from an api in the form of pages
could anybody help me out ?
i know how to make pages(paginators) manually
jesterbot is a discord-bot coded in discord.py with over 180 commands and 15 cogs. - JesterBot/Paginator.py at main · CaedenPH/JesterBot
this is a pretty decent paginator if I do say so myself...
not amazing, but good at a lowish level
looking back on it now, i see a bunch of errors
but it works
you just have to replace the emojis
from core.utils.utils import thecolor from core.utils.emojis import LOCATIONemojis as l
these
I’m back
I think my WiFi sucks
Nothings loading
Has it just been empty after Caeden sent his paginator?
ur wifi sucks
im not gonna deal with this today
nvm, why have u indented the function?
please go learn python first
it literally says what u did wrong in the error
You would do @commands.command in a cog only, not for your main file
In a main file assuming your bot instance is bot, you would use the @bot.command() decorater
So remove the class SomeCommands... and remove where you do def setup(bot)....
so what would remain is the @bot.event part where you are doing on_ready and change the @commands.command() decorator for your ping command to @bot.command(). And remove self from the arguments for the command since it's not a cog @slate swan
@bot.event
async def on_ready():
#something
@bot.command()
async def ping(ctx):
await ctx.send(f"Pong! {round(bot.latency) *1000}ms")
👍🏼
yeah and also in case you didn't know, the !resources command has useful documentations for beginners
cool, I'd still recommend them to first understand the basic python syntax to make life easier for them
I agree
uhmm yeah the !resources command has some of the documentations on basic python and it's better to guide a beginner there instead of saying "go learn basic python first" or whatever (i'm just saying, not trying to start anything here)
yeah that's my bad
Infernum is noob dev
there's honestly no need for that
That’s mean and rude
Infernum is obviously better than you
Don’t be mean to him.
you are very noob than inferum
@bot.group()
async def buy(ctx):
await ctx.send('Provide A Valid Item Name')
@buy.command()
async def bluticket(ctx):
conn = sqlite3.connect('test.sql')
c = conn.cursor()
amount = 150
player = ctx.author
c.execute(f"UPDATE data SET balance = balance-{amount} WHERE ID = {player.id}")
conn.commit()
conn.close()
await ctx.send('Item Purchased Successfully')
when i use !buy bluticket it says "item purchased succesffully" but also "provide a valid item name"
Do you want me to ping a mod?
?
lets not do this? i feel like I already said that was my mistake?
2 conflicts in 1 day
Or this will turn into a battleground
What’s a bot.group?
You gotta be kidding me, is here still a some sort of fight ;-;
I forgor
LMFAOOO lets talk about fav flowers or something
Thankfully not.
Or stay on topic
good
ohh its those people who dont know anything about python but still have an attitude like Guido van Rossum
🤷♂️
But no conflicts
I will leave if that happens
Any ideas to make for me bot?
basically @bot.group means like
anythin defined in bot.group is a group command means it can also have args
thats why in the command of bluticket it has @buy.command not @bot or client.command
Make a command that checks if ctx.me.bot is True
I think I alrd have that or smth similar
also put @bot.group(invoke_without_command=True) as the decorator
its just its sending the output of bot.group as well as buy command
Also, don't connect to your database on each command. Keep a connection throughout your bot.
Possibly because something triggered it
U gotta set some parameter, look it up in docs, I’ m not sure what It’ s called
oh thank you
That^
its now sending 1 output when 1 command i used
@slate swan yeah read this too
so it works?
i guess it was considering bot_invoke_command=False which was triggering it
Use a connection pool @slate swan
🤷♂️ not the expert here
i know i am explaing
any education is useful in future
I’ll do background work
okay
Which db are u using
It’s what I do when I don’t know tf what’s happening
the local sqlite3 database
This is true. However there’s a limit, you cannot just come into this server or rather this chat with 0 to No python or programming knowledge at all and expect for everything to go well. Especially the people who come in here with that lack of knowledge and expect spoonfeeding. Us just giving them code will not help them at all but more so hurt them by confusing them if they don’t know what anything does. Even the maintainer of discord.py Danny expects people who use his library to have an intermediate understanding of python and object oriented programming. The limit I mentioned earlier correlated with what I just said. However, if you come in here willing to learn and understand what we tell you then you will be fine and more likely to be helped than people who just want a discord bot and want people to write code for them without them even wanting to understand or learn anything.
cool do you know how to make a connection throughout your bot to the DB?
amogus
Try to see if there is an orm for this db
amogus
Probably better to use connection pool or an orm
@slate swan Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
lol
nop I actualy read main topics of the sqlite docs and saw a tutorial upon sqlite3
Object-Relational Mapping? ok sqlite has it
Yes, I think sqlalchemy could work
thanks for help guys
Np
Something like this will suffice too
bot.db = bot.loop.run_until_complete(aiosqlite.connect("the_db_name"))
U only wanna have 1 connection?
Look how u indented it
!indents @slate swan reading this would be useful too!
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
what do you mean by this?
oh okay i will try that
something is wrong
Like u can use a connection pool and have multiple connections ready w/o having to create em constantly
oh wait its replit
lmao
what do you mean? With the line I sent, you can have a connection throughout your bot meaning for any command you can access the database by doing bot.db instead of making a new connection
best discord py toturial
you can use that too, there are more than one ways to do it
?
It’ s inefficient to only have one connection
where you learn discord.py ?
Docs
everyone learn from docs
!d docs
You're correct, but it's also important how you broach the topic of someone not having enough foundational Python knowledge. Just saying "go learn basic Python" is dismissive and doesn't really communicate very well what the person in question is lacking. You can phrase it in a nicer way and provide the resources they need to get up to the level they need. And if someone is not listening despite this, it's important not to lose your patience and become abusive through frustration. You can always step away or message @novel apex and ask staff to step in if the person is being disruptive.
some from tutorial
Hey dementati
That is docs on how to document ur code 😂
Dpy docs are best docs out there
Fair.
Hello.
Question dementati: Do you know databases with dpy?
I know databases and I know dpy, to some extent.
bot.db = bot.loop.run_until_complete(aiosqlite.connect("the_db_name"))
``` is this a okay way to keep a connection to a DB?
i tried doing that , it can often be a recurring
If you do this you will have to access db by doing bot.db and then u will have to write a sql query, right?
yes ofc
since you use aiosqlite , you may use the async with connect() method
Hello
so this is inefficient?
Someone tried to convert me into Christianity
So you will only be limited to sql databases, or even to this specific database, right?
!ot
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
discussion about discord bots basically
I see
I’ m tryna tell the dude bout data access object
I didn’t know that
alright thanks
It's not , but doing multiple things with the same connection can be problematic
saving_data/sqlite3_usage.py lines 38 to 46
async def create_database():
async with aiosqlite.connect('animals.db') as connection:
async with connection.cursor() as cursor:
await cursor.execute(
'''
CREATE TABLE IF NOT EXISTS animals
( user TEXT , animal TEXT)
'''
)```
You can try something like this
U should learn that
Yes I’m going now
oh no the one i was using for a connection to a db throughout the bot so i dont need to keep making a connection for each command
Lets say u use ur approach, and someday u decide u wanna switch to mongo, what do u do?
I see , you can just make a function which connects to the database and return the cursor
I love the docs
yeah they're great
it would be used everywhere ¯\_(ツ)_/¯
Like, u use single connection all over the code
So if u ever wanna switch to mongo
U gotta fix whole code
why switch to mongo when postgresql exists
i have no clue what that's about
I just gave example
It's easy to migrate from Sqlite to psql
Mhm
Also if you have a production app with millions of users and billions of data u wont be using postgres
Ud be using nosql
postgres supports noSQL too , as for production it's highly preferred
fuck all this shit just tell me which one i should go with
if you are cool with dictionaries , mongodb is a good choice
Do yk outfit7?
Talking tom company
Yea
Companies like instagram , Spotify and Netflix use postgres fyi
Can we change bot presence to none??
What to do to remove bot's activity??
ofcourse
Yes, It’ s because It’ s better for their use case and postgres is scalable enough
Don't put anything in the first place
Playing streaming watchin listening
It will have no activity by default
You're giving it one, remove that part
I mean I am giving it but later if I enter remove status command, it would remove it
It's faster than mongo too
So it's not removing?
I havent tried ._.
show that command
ok wait
wait I said I haven't tried
just asking if it can be removed
No its not, nosql can have billions of entries and will work the same as if it had one, sql has certain limit to where it will start working noticeably slower
so we just need to dopy await client.change_presence(activity=None) right??
Or just dont do anything, it wont have activity by default
Did you not just read what he just said.
it have the activity but if I want to remove I run the command
He said he’s going to initially have one and remove it later with a command.
Yea
Ohhhh
Also 1 thing, if I have set a tasks.loop(minutes=30) Is there a way to call it before 30 minutes??
Huh
it gets called for the first time when the bot starts
You can just call the task as a function too
how??
Change minutes=.....
How do i make a 3 space command such as
!buy golden ticket?
i used bot.group to make 2 space
!buy gticket, but how I make it into 3?
@ext.tasks.loop(minutes=1)
async def task()
#code``` If you ju:st do `await task()` IT gets called
Command groups
No... don't do that
huh
Just use (ctx,*, argument)
\👍
Does he need command with spaces or arguments with spaces?
@slate swan
yea
I mean he wants to write !buy golden ticket
soo i add it in the bot.group or the normal command?
Normal command with two args should suffice ngl
He said 3 space command so I assumed he needed a command w spaces 😂
Why two args?
!buy is the parent command and all the items to buy are subcommands ig lol
For golden and ticket?
No no read what he said @slate swan
I read that
golden ticket is one item tho.
One item.
(ctx, *, item)
read their 3rd line
Ah, my bad
wait look at dis
@bot.group()
async def hm(ctx):
await ctx.send('hm')
@hm.command()
async def helo(ctx):
await ctx.send('yo)
this makes
!hm helo
Okay idk what you want to do lol
i want to make
!hm helo bruh
Mby he has a command buy-gold-ticket or something
command
I wasn't here for a while nothing changed lol
yes you are correct
So you can use consume rest?
Make 2 command groups ig
i want to make a command like
!buy golden ticket
Nested command group
like another group for word golden?
Yea, if u rly wanna include spaces
I dont think aliases attribute lets u put in spaces
should i use
if message.content.startswith('!buy golden ticket')?
No
oh
Just use this
@slate swan
Just go w nested command groups
As the arguments
ohhh
so the bot will match the arg provided by the author?
The command is called buy golden ticket, golden ticket isnt an argument
What
guys. what coding excercises can I do to get better
From where are you getting this?
Projects
I cant make a single code without searching it up
#discord-bots message
@cedar stream
He said it
No one can
so you cant make a command line for your discord bot without searching it up?
fx
Wym?
Like u will always have to look something up
like @commands.command() async def join(self,ctx): if ctx.author.voice is None: await ctx.send("Du skal sjovt nok være i en voice channel") voice_channel = ctx.author.voice.channel if ctx.voice_client is None: await voice_channel.connect()
like this
Not this necessary, but no one can code w/o looking stuff up
It’ s part of the process
I know, but making a discord queue is too hard for me. I dont understand
So what can I do just to get better at making code lines
Music bots are hard to make yes
it depends
on what type of bot, is the bot using files or using youtube api to play
Everything depends
Code a lot
I use ydl
if its a file then its pretty simple if its using a command which search youtube to play then its hard
But Idk what to code
can you tell me what is ydl? never heard about it
youtube dl
Make a simple bot with simple dashboard that u run locally for example
dashboard of what
That doesn’t make difference
Make a dashboard for the bot
Like literally anything
Just code a lot and ull gain experience
it does i have made a bot which play from sound files it was easy using ffmpeg
Can you show me what a bot dashboard looks like? @cedar stream
Google mee6
The site it will take u on is a dashboard
But that one is complex and has a whole team working on it
basically a dashboard is like a site but in discord you have to use command in dashbaord users can do manually
oh you want me to make a website?
Well anything
U can make a mobile app
so you make a website with python?
Or game
I thought you only could make websites with html
U can if u want to
That is frontend
There is more to web applications than html
you can do anything with python, it will be a little slow tho
This is not on topic
so hello
hecker here
how do i master making discord bots and proudly displace the supreme carl bot
this seems to be incorrect way to get a role, why? ```py
role = await ctx.guild.get_role(self.default)
you dont await a get_role
oh
hello so i needed some help i wanted my bot to create the highest role in the server (as he is the administrator) and then give it to himself is it possible by any means?
we were talking about dashboards
it was just a refrence
@slate swan How can I make a command so the user input b!image <text> -u <user>
text is a string and user is a discord member
async def cmd(ctx , text , user : discord.Member)``` should work
text is not of 1 letter
text is like a full sentence
what's the part tho
wdym?
*-U part
-u is like a flag
it will tell the bot that a user:discord.Member is entered
why dont you reverse the command order , like mention the user first and text later?
but I want to make it so that if the user is none, then the user is ctx.author
Use an or statement
??
!e
a = None
b = a or "a is none"
print(b)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
a is none
I am not refering to that
see
What are you referring to then
use Union
How?
bruh
you mean py user:discord.Member=None?
async def command(ctx , user: typing.Union[str . discord.Member] , text):```
and then you can check if user variable is a discord.Member or not
What does it do??
it allows you to take both string and Member values for the user variable
!d typing.Union
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
just use | if your using 3.10
Oh and what if the user have to enter:py b!help 1 -u whois abcd
I want to put 1 and abcd in variable A and whois in variable B
A is a list
@cedar stream Is there other small bot projects I can start on instead of a dashboard?
how to see number of animated emojis in a server?
iterate through the guilds emojis, check if its animated
!d discord.Guild.emojis
All emojis that the guild owns.
!d discord.Emoji.animated
Whether an emoji is animated or not.
^^
also why does the documentation get deleted after a couple of seconds
I didn't click the reaction
I mean animated emojis capacity
the limit for the server
oh
yeah, if no result is found and if not a reply then it deleted after umm 10 secs iirc
property emoji_limit: int```
The maximum number of emoji slots this guild has.
hm idk by default it's 50
you could check for the guilds boosts and add them though
no its okay but thanks
hey guys, How do I make a about respond to 2 different thing in one command block
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith['Hello', 'hello']:
await message.channel.send('Hello')```
I made a string, but it doenst work
use tuple
tuple?
if message.content.startswith(('Hello', 'hello')):
oh, why does [] not work?
class tuple([iterable])```
Tuples may be constructed in a number of ways:
• Using a pair of parentheses to denote the empty tuple: `()`
• Using a trailing comma for a singleton tuple: `a,` or `(a,)`
• Separating items with commas: `a, b, c` or `(a, b, c)`
• Using the [`tuple()`](https://docs.python.org/3/library/stdtypes.html#tuple "tuple") built-in: `tuple()` or `tuple(iterable)`...
because you're subscripting it
not calling the startswith
yes (if I don't misunderstood)
!e
print("hi".startswith(["1", "2"]))
@visual island :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: startswith first arg must be str or a tuple of str, not list
Yes, just recreate any bot
*misunderstand
ignore my grammar
U can buy a licence where u get everything from jetbrains
what is the ratelimit for adding emojis
yeah 
I forgor 💀
why it trow an error :
An error occurred: Command raised an exception: UnboundLocalError: local variable 'qr' referenced before assignment
qr was defined somewhere else
nope
qr = ...
def func():
qr = ...
``` something like this happened
okie
huh?
help py @Blank.command(aliases=["phc"]) async def phcomment(ctx, user: typing.Union[str, discord.Member], *, text=None): await ctx.message.delete() if text is None: text="I like it very much" if type(user)==str: text=f"{user} {text}" user=ctx.message.author name=user.display_name image=str(user.avatar_url) url=phcomment_gen(name, image, text) try: file=io.BytesIO(requests.get(url).content) await ctx.channel.send(file=discord.File(file, 'ph.png')) except Exception: await ctx.channel.send(url)
Even if I mention a user, it still think its a string
?
.
okay so no []?
No
okay ty
icy gave an example already smh
guys
I jsut wnated it to get confirmed, because you usually use [] when you are typing a list, from what I heard.
why do you need union?
try putting discord.Member first then str
just do ```py
async def phcomment(ctx, member: discord.Member, *, text)
i want to accept member and if author dont type member then user is author, and the text he typed in the user arg will be added to the text arg
async def phcomment(ctx, member: discord.Member = None, *, text = None):
member = member or ctx.author
# stuff you did earlier
Just do typing.Optional
hm
optional\🤔
so confused
or yeah Optional works too
trypinf
well, if you wanted to do !phcomment hello and !phcomment @kayle#6872 hello it'd both work if you used Optional ig
btw
this worked
!import os
can we actually have another argument after providing a default value to an arg?
!e py def foo(a=None , b): pass
no
I forgot to change it lol
ah
is there an async time module?
hi
hi
asyncio
time?
asyncio has sleep attribute which is async
do you mean for the time.sleep?
@visual island it still dont work
nah not to sleep to get the time
show code
oh use datetime then
I'm HAPPY 😀 😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀
time.time wont be blocking
oh thxx
wut icy said
ty
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith(('inshallah', 'Inshallah')):
await message.channel.send('SIIIIIUUUUUUUU')```
@visual island
the number of emojis say you're way too happy
!ot <=
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
Hi
Whats wrong
yes
it doenst work
👍
Whats the error
Guys, i have one unusual problem
its from a meme btw lmao
that should work though
you cannot have a list/tuple in startswith , it needs to be a string
you can
you can
I use cogs
I have tried that
oh?
but it doenst
search up str.startswith on google
no errors?
nope
yea sorry , actually it can be a tuple
how are you sending the message?
in the chat on my server?
if that is what you mean
yes
yes
wait wait wait. Cant you have more command blocks where to bot responds
like I have two identical bots, the difference between is just what I say in the chat and what it responds with.
so in the first its "Inshallah" respond: "SIIIIIIIIUUUUUUUUUUU"
and in the second block its "okay lets go" respond: "youtube link"
or I could just send the block
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('inshallah'):
await message.channel.send('SIIIIIUUUUUUUU')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('okay lets go'):
await message.channel.send('https://www.youtube.com/watch?v=AWM5ZNdWlqw')```
@visual island
Ok the problem is in cogs. I want to get the guild on the initialization step:
Like this:
1. def __init__(self, bot):
2. self.bot = bot
3. self.guild = self.bot.get_guild()
But there is one problem, when i use get method to get the guild (line 3) method returns me None, not guild I want to find.
The only solution was to use:
await self.bot.fetch_guild()
Okey, i right its the only way to correctly get it, if you know how to do it another way, tell me, it will initially change root of the problem.
But my solution is async method,
i cant use await in __init__().
I also tried to use asyncio
I worked with loops, my code looked like this:
1. def __init__(self, bot):
2. self.bot = bot
3. loop =asyncio.get_event_loop()
4. self.guild=loop.run_until_complete(
asyncio.create_task(
self.bot.fetch_guild()
)
)
But i’ve caught an exception with request lib, i find it is in some special methods in library, i think that my tryings to use asyncio don’t correspond with these methods.
I need in a solution. I dont wanna add attributes to cog by using on_ready event
you can do that
well its only one of the blocks that work
and there is no error. Should I send the whole code?
no, you can only have 1 same event, just use if-elif
so the problem is the get_guild returns None, or the exception in request lib?
just add another if..
where in the code
below your first if statement
First and the solution to use asyncio makes tge second
My goal is to get tge guild in init
the first issue is probably due to cache is not filled yet
Any way
Tell me how
@client.event
if async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('okay lets go'):
await message.channel.send('https://www.youtube.com/watch?v=AWM5ZNdWlqw')```
you need to wait until the bot is ready, where do you have load_extension?
like this
cogs have an async method that gets called on load called cog_load iirc
I load all extentions then i run the bot
run it, then load extension
Ok
sorry, but I dont understand
if statement1:
...
elif statement2:
...
ahhhh
you can add load_extension in on_ready but be sure that you handled if the extension has been loaded
elif equals
else:
if
also what you mean by request lib is aiohttp probably?
didn't someone tell you to learn python yesterday lol
random_status_status=True
@Blank.command(aliases=["rs"])
async def random_status(ctx):
await ctx.message.delete()
if random_status_status==False:
random_status_status=True
await ctx.channel.send("Random statuses are now turned on", delete_after=2.0)
await change_activity()
if random_status_status==True:
random_status_status=False
await Blank.change_presence(activity=None)
await ctx.channel.send("Random statuses are now turned off and the status have been reset", delete_after=2.0)```
When I print it, it shows true but when this command is ran, then it shows random_status_status referenced before assignment \😢
start again then
@slate swan please help
why would it turn off in the first place
Any error in console?
no
What did you type when it stopped?
while True:
if time.strftime("%H:%M:%S")=="12:30:00":
await channel.send("Time ees 123000")```
would this crash my bot?/
I don't think so but IDK if we can use infinite loop in on ready
it ran for a bit then crashed for no reason
idk bro then, try asking professional
while True is blocking, but with async function inside it, it will be asynchronous. But in your case there, youre putting the async function inside an if statement where it should be in the outest indentation
the whole thing was inside on)_ready btw
inside while True?
yes
what difference wuld 0.01 make
No need
why
Because they're already yielding to the event loop in the while loop
yielding to the event loop?
A very short space of time
do you mean because of the on_ready async func?
Well first of all they should post the error they get when their bot crashes instead of us guessing what the problem is
@glass rock
This will keep sending the message over and over and over again
0.016 bpm? cool
Need help
variable scope issue
!botvar use this instead
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
I still dont understand
Well, is this wrong then? ```@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith('inshallah'):
await message.channel.send('SIIIIIUUUUUUUU')
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith('okay lets go'):
await message.channel.send('https://www.youtube.com/watch?v=AWM5ZNdWlqw')```
@minor panther
2 on messages cannot be in the program
how do u reset the nick
await mem.edit(nick=None)```
thank you. Well thats why only one of the them is working
ty
spoonfeed bad
i was doing it wrong
:\
no error tho thats the issue im not dumb
so I need to make strings or tuples right?
You can do if else
!e
a = 1
def b():
print(a) # global variable defined line 1 get to be a local variable in function b
a = 2 # trying to set local variable but local variable exists already which is what we defined above
b()
@visual island :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 3, in b
004 | UnboundLocalError: local variable 'a' referenced before assignment
o
I know what if else is, but how excatly should I set it up?
if message.content==("Bla bla"):
#do stuff
elif message.content==("Not Bla Bla"):
#do stiff```
why is it a tuple
okay I see
cuz strings dont work for some reason
it should
@visual island How to overcome this error??
spend some time reading that
But my variable is not a bot variable
Also this is different
then make it?
Nah bro I can't do something i know that I don't know 😶
please help with this
oh understood a bit
kekw didnt saw last line
idek who tf can explain it more well than that
what is the error
^
okay i will try to explain
Wait wait its said
Local variable random_status_status referenced before asignment
Why didn't it took the global variable??
random_status_status=True
@Blank.command(aliases=["rs"])
async def random_status(ctx):
await ctx.message.delete()
if random_status_status==False:
random_status_status=True```
here before defining the command you declared the variable, and now,
```py
if random_status_status==False:
random_status_status=True```
You're trying to make it a local variable, in the second line, and just before that you're also trying to get its value
U gotta put global keyword in front of it if u want to take it as global
!e
print(v)
v = 1```
@sullen shoal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'v' is not defined
this is somewhat like that
but because its already defined, it wont show this error
What happened
you may either declare it a global or go with the good method which is using the bot or cog class
ok so let me declare it global
!botvar 🥺
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Bad choice but ok. Just put global keyword in front of it
Breh
Inside the function
really bad ugly dumb choice
It’ s his decision 🤷🏼♂️
bruh, there's a reason I used the bot var tag
They ignored it completely
thx its working
;-;
whats the reason?
chat looking cool
How is it looking?
i aint showing, its too good
So that u don't use globals 🤦
Okay
!globals also
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
👍 I don't use it anywhere else
Also this is not working: py await Blank.change_presence(activity=None)
That should remove the activity, no?
is there a more professional way to run discord bots than just ssh'ing into your vps, git cloning the repo, putting ur token in the config file with vim, and then doing python3 bot.py in a tmux session
cus thats why i do lol and idk if thats a bad thing
A systemd file?
Where do u host it?
i use time4vps which is in germany
Not removing the activity
I’ m not sure, check It’ s docs for vps
Idk any better ways tbh
what moderation commands I should add to my bot? I have basics done
Ik gcp has some stuff that makes it easier but I never looked into it
Idk, slowmode, mute
Add automod
Just copy em of dyno and mee6
I don't know what commands they even have
Censored words? You would need to use a db tho
alrd existing, as well: anti spam, filtters for invites, words and few other things
Look it up
Spam detection
if the mod forgets to add the member to kick or ban, it should default to the mod
wont that be great
LMFAOOO
I have as well implemented that once
No, it should default to ur bot
nah
Do you log all mod actions?
Then make a dashboard where u can view the logs
Guys can we remove the activity status of bot??
