#discord-bots
1 messages · Page 895 of 1
Guessed as much (no offense)
Id suggest you try working through some tutorials over the fundamentals, then coming back. Itll save you a world of pain lol
Honestly yeah, you can solve trivial problems like this within minutes and move on and spend your time on more interesting problems
they have fallen into the discord.py tutorial trap 
Yeah. You have good ideas it seems, you just need to learn how to tell the computer about them
Happens way too much
Hi could anyone help me out. What is the chepeast option to run several discord bots. Currently have them on separte Heroku accounts and I am able to run one per account for free. But are there any other paid but cheap or free alternatives to Heroku?
Definetely, it's more about translating the solution in your head to code
AWS would be your best bet
Run multiple discord bots within one machine, dockerize it if you want
i've tried doesnt help me
Just runing them on a micro instance
Yes, micro instances will work fine
!resources has some nice stuff
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
And the micro instances aren't all that expensive so it's perfect
So is this how everyone runs their bots or locally? I find Herokus paid plans to be ridiculsy expensive. Unless you are profiting of these its not worth paying for the service.
I host multiple applications of mine on AWS, yes
Honestly i just have a spare old laptop lol
||railway.app|| 
I use their S3 for file storage related to my bot, a domain for the bot, and host the bot itself & the web dashboard on the ec2, and also have a postgres database on the machine as well and an API that acts as a middleman between postgres and the bot
Ok will try that out, I'm bored of creating burner accounts on Heroku for each new bot 😅
Yep, makes a world of difference
All for 3 bucks?
isn't AWS paid?
Or is that an S not a $
About 10 for the VPS, $12/year for the domain
I have a Raspberry Pi might look up to see if I can probably just host them there. Do bots consume a lot of processing power around how many do you think I would be able to run off a Pi with 4gb of ram
Yeah that's an S, S3 for simple storage services
Read it as an $3, mb lol
Oh yeah a raspberry pi will do nicely
Actually had mine running on the rpi until I got the S3 & domain hosting, at that point i was like screw it might as well keep everything on aws
Depends on how much your bot does ig
Yeah also a good alternative
If we say your bot is in a few guilds with not much traffic, you can run up to 10
Just pulling api's
Ngl idk if its cuz im broke but i prefer just using my own machine, seems more secure
If it's mostly I/O stuff like apis like you said, you can run a good but, perhaps up to 15
I don't know about secure
Higher upkeep, less secure than professionally provided hosting services
Nice not bad. Thanks for the info.
How’s that?
I mean there's a reason a majority of the internet is run on things such as AWS, google cloud hosting, microsoft azure, etc
If they didn't provide some of the most top notch security they wouldn't be used
guys better to use javascript or python for discord bot
I mean how would it not be secure to have smth running on my local network? No one else rlly uses it
From a logical standpoint, probably javascript but from a library standpoint definetely python. Just personal preference at the end of the day
whats ur personal prference
I mean we’re in a python discord, so we’ll say python lol
Think about your regular old commercial router vs an industry standard routers on massive datacenters
Mine? javascript, more specifically typescript
ok is there any tutorial for python discord bots
But don't go off doing what I do just because I do it
or javascript discord bots
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Any? Yes. Any good one? Havent found one lol
ok what abt javscript
Well it isnt on yt, so that adds like 10 points to credibility lol
Yes, syntax is very similar to browser JS though
k
It's also pinned
And it was created specifcally to address many flaws found in youtube tutorials which is great
I swear, a good discord bot tutorial on yt is harder to find than women in cs
Though people still gravitate towards youtube tutorials which really drives me up the wall especially when they have things like client = commands.Bot(...)
Yikes
hmm
I wish you luck
thanks so good helpers UwU ; D
Thank you!
Rust seems to be popping off right now
That, one of the C-langs, knowing Node.js/TS is always, knowing at least one of all of those is imporatnt
Very fast compiled language, lot of talk about it recently and seems like people love it
Sure, C/C++ is good
Doing game dev will help you hone your C skills since UE uses C++ and Unity uses C# iirc
How fast on a scale of c to python?
c to python lmao
Universal speedometer for languages XD
😔
Interesting
Rust is mostly just a memory safe C anyways
Borrowing concept is very cool though
Same with lifetimes
The name makes it sound so old and outdated lol
I heard it can equal or be faster than C
Dang
Their discord server as a channel for #os-dev like we do for things like #discord-bots
just goes to show how fast it is
Feel like ima become an old relic before i even finish learning python if i dont learn rust now lol
Yeah been wanting to but way too lazy you know
🗿
i think i've done nothing but help out here the entire day today
depends on the methods as some methods that are got inherited from C to python are faster than native python so i doubt its faster than C
¯_(ツ)_/¯
It can be if you optimize it
native python faster than c idk
I meant rust than C
If you were running discord bots in C vs python vs rust it's going to be relatively the same (largely depending on bot ofc)
prob
they spend like 90% of the time waiting around
lol
if ctx.channel.id != 1234567890:
return
Put this in your on_message to effectively bar any commands in specific channels from being passed into command handlers at all
client.load_extension(f'cogs.{filename[:-3]}')
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 623, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.botinfo' raised an error: TypeError: cogs must derive from Cog``` any one what this means?
ohh it suppose to say Cog instead cog
Um is that selenium
Okay major problem with that
selenium won't work with discord bots since selenium is blocking and discord.py is asynchronous
It's difficult to get selenium to work with discord.py
quite difficult indeed
It seems to
If you turn on logging it'll start spitting errors saying the event loop is getting blocked
You can't heartbeat the server when the event loop is blocked
no heartbeat gateway = big disconnect
Sleep Robin 👀
big disconnect = big sad
😅
for filename in os.listdir('./Cogs'):
if filename.endswith('py'):
client.load_extension(f'Cogs.{filename[:-3]}')```
give it a few hours
Make sure your cogs look like this:
class MyCog(commands.Cog): # THIS IS VERY IMPORTANT!!!!!!
...
Sure, do as okiimii said and put it in your on_message
Yessir

@event_decorator
async def on_message(m):
if something:
return
# everything else
Rip, I'm out of my mind I'mma just go
in your case something you wanna check if the message is from a certain channel
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 618, in _load_from_module_spec
setup(self)
File "c:\Users\thoma\Desktop\discord server bot\Cogs\botinfo.py", line 42, in setup
bot.add_cog(Cogs(bot))
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 505, in add_cog
raise TypeError('cogs must derive from Cog')
TypeError: cogs must derive from Cog
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\thoma\Desktop\discord server bot\Bot2.py", line 26, in <module>
client.load_extension(f'Cogs.{filename[:-3]}')
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 623, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.botinfo' raised an error: TypeError: cogs must derive from Cog```
Same
U didn't do class Something(commands.Cog):
send pls easy python game from discord bot
youre probably trying to load a class or a cog thats not from the same fork
Or that, yea
Sure, check the channel ID of the sent message vs maybe a list of channel IDs you don't want the bot to work in
uwa?

Yea*
is your bot made in disnake?
Chads use bot.dispatch with on_message :D
Yes that botinfo cmd yes
Chads write their bots in assembly
Easy then
Chads use binary to send API requests
Just compare the ID of the channel message was sent in to 942234501642338314
if message.channel.id == id:
. . .
message.channel.id == 942234501642338314 perhaps
?
Feel free to ping me. I'm off tomorrow and will probably be here
So?
Unfortunate, I wish you luck
@slate swan

You said if am using disnake i said yes
show your bot file and your cog file
Are you using "only" Disnake?
Because you error says you're using discord.py
and discord.py
no you can't do that. Choose 1
Do i need to uninstall discord.py?
Hi can anyone help me with something

i am working face recoginition project i want to display details from csv file
Migrate from discord.py to Disnake
Change all discord to disnake
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="*")
client.remove_command('help')
@client.command()
async def funfact(ctx):
await ctx.author.send('In 1980, a Las Vegas hospital suspended workers for betting on when patients would die.')
your issue?
Is this any errors. because its showing for me
dotn see any thing wrong
!p
if drinks != None:
for your_drinks in drinks:
drinks_cost = drinks.count("small")*2 + drinks.count("medium")*3 + drinks.count("large")*3.5 + drinks.count("tub")*3.75
pizza_cost = len(pizza)*13
for toppings in pizza:
toppings = pizza.count("pepperoni")*1 + pizza.count("mushrooms","olive")*0.5 + pizza.count("ham")*1.5 + pizza.count("anchovy")*2
if wings != None:
for wings_cnt in wings:
wings_cost = wings.count("10")*5 + wings.count("20")*9 +wings.count("40")*17.5 +wings.count("100")*48
if coupon != None:
total = (drinks_cost + toppings + pizza_cost+wings_cost)*106.25/100 - (drinks_cost + toppings + pizza_cost+wings_cost)*(1-coupon)
else:
total = (drinks_cost + toppings + pizza_cost+wings_cost)*106.25/100
return total```
Converting to "int" failed for parameter "pep_number".
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
Except for the error when the user's dms are off
Hey @swift quiver!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
#bot-commands
should remove the help command in the constructor and use only one pair of quotes but yeah i see nothing wrong
same error
where? when it fails to dm a user?
no, when I try to run it it gives an error that i cant share through hastebin and here
does anyone know if slash commands are removed or smth?
You can share with hastebin....
No? Slash commands still exist
Replit: Updating package configuration
--> python3 -m poetry install
Installing dependencies from lock file
SolverProblemError
Because botname depends on discord-py-slash-command (^2.0.4) which doesn't match any versions, version solving failed.
at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes
exit status 1
Replit: Package operation failed.
No? I can run slash commands just fine. In fact this message was used with a slash command ¯_(ツ)_/¯
I keep getting this error
no i cant
/shrug
and it's causing my entire bot to stop
Remove your token and try it again
That's not "slash commands"
It's just a bad 3rd party library people used for making slash commands In Discord.py
Replit
Which is now outdated
oh do u know how I can remove this cuz I need the bot to get back up
🗿
Use discord.py master branch or some fork to make slash commands
It's replit no
Nah, the discord-py-slash-commands library is dead
not related to replit
Nope
Replit does have that issue
Ive gotten that issue before
Tried to remove the discord.py library
And was stuck like that for hours
Just randomly went way after some time and i could finally remove discord.py
theres no token
Well I doubt hastebin would be giving you that error
can i just send u it in dms
DMs are closed sorry
If you send it here and it has a valid token, discord should automatically reset your token
The library is deprecated, it's Discord-py-interactions now
that's why it says no version matching found.
And yea replit has that bug when you don't configure your poetry yourself
Hi, I'm trying to develop a bot that will join a voice channel, detect voices from users, and then play an mp3 file when it detects the voice. I just started learning how to make discord bots and I'm not quite sure what to do next
These "plugins" for components and slash commands were really only temporary while everyone was scrambling after discord.py was discontinued, I think now that many of the forks are stabilized and have their own implementation, including discord.py, there's no reason to use any of these "plugins"
https://paste.pythondiscord.com/deyalufotu can anyone help me
are you talking about playing a specific sound for a specific person?
I don't think discord.py has the ability to recieve voice just yet
no, a sound for everyone
It is dispatched to you though (i think)
well, it doesn't have to necessarily understand what the voice is saying
its more like "if there is a user speaking in voice chat" play mp3
on_voice_status_update() is an event perhaps
Actually I don't think that tells you when someone stops/starts talking
Oh shit sorry i thought it was the other problem
https://paste.pythondiscord.com/deyalufotu Can anyone help
yeah its joining related
So if someone joins the voice channel, the bot should play an mp3?
no, if someone speaks
Cause i was only looking at this
Don't think you can detect that
Thought it was that bug
aww really?
there is no way to check if a user is speaking in vc?
Doubtful
How does the voice chat highlight thing work. The one that lights green whenever you speak in voice chat
could that be a workaround?
That won't help either, no
Wish I could help but it seems to be a discord limitation
Though one of my friends was experimenting and he was able to get some raw data through the websocket indicating if someone was talking or not
Looks like a windows error, I'm not experienced with windows so unfortunately no
Uh alr.
What's your discord.py version? @swift quiver
possible 
why does the payload use an int is it so it has boolean values?

maybe because it seems to have a value of 1 when speaking which 1+ is True so idk maybe
maybe
He showed me this as well
@stiff kayak if you're still interested might be worth looking into this
they left?
They're still here
@has_role() check
Can I put in the ID?
Let me check the docs
Mhm
Yeah looks like you can
Errr
Yeah Okay, Thank you
@client.command()
@commands.has_role(950040612625842186)
async def add_money(ctx, user = discord.Member, amount=None):
if amount == None:
await ctx.reply("**__INVALID AMOUNT__**, Please use `ayo add_money [user] [amount]`")
return
else:
users = await get_bank_data()
users[str(user.id)]["wallet"] += amount
with open("mainbank.json",'w') as f:
json.dump(users,f)
await ctx.reply(f"Successfully added {amount} to {user.name}'s wallet")```
@sick birch What's wrong, I don't get it
*__Ping me with ans please__*
is there any error?
I need to see an error to figure out what's wrong
user = discord.Member
make it user: discord.Member
@sick birch :white_check_mark: Your eval job has completed with return code 0.
True
yeah it does, but it isnt a good way
Hm alright
using is is always preferred
Ye that's what i was thinking
not sure how lmao
Ash
one compares ids while one compares value not sure how one is always preferred
Cz PEP 8

Just telling ¯_(ツ)_/¯
no pep8
#internals-and-peps for talks (:

Stop sending emojis in every message of yours, it's irritating asf
make me
hes a kid, its a phase
bro youre like hunter you guys act so mature when your 1 year older like bro what💀
i mean hunter is mature and hes cool but thats not the point, the point is youre a kid as well 
How do I make it so it’s a custom role instead of the everyone role
I am just telling u to stop using emojis in every single message. It is good u have nitro, but this isn't the correct channel to flex it. There are ot channels too
pip install -U wavelink
❤️
(:
im not flexing my emojis i just use them so people know/how to take my point
I don't wanna continue this argument, but u using these emojis in every message just makes u look like a small kid
i couldnt care less how people think about me lol
My bot take nearly 12 minutes to trigger the on_ready event. When I try debugging it is loading every users (users kept increasing) Is it because it is in a few servers so It is taking so long ? is this normal or is there a way to fix this ?
more info:
RAM : 8GB
SERVER : 500
USERS : 200K
Wym server 500?
guilds*
Shouldn't take 12 min tho
My bot is in 130 servers, takes like 1-2 min
Check yr internet
How do you countdown
is it because i am using autoshard ? could that be case ?
4000/4000 up/dw
Idk, could be
It is super annoying when restarting bot I want a way to fix this 😭
Try removing auto sharded bot
but on my alts which have 40 servers it only takes 30 secs 🤔
Sure I will try to remove auto sharded
thank you
use discii instead
?
did you restart your editor?
yeah
Seems like a wrong Python version has been selected
hm i have py 3.10
what to do
visual studio code? or normal visual studio
Oh hmm. At the bottom bar, mind showing yr selected Python version?
Normal one
oh ok
f1 -> select interpreter
Shī Tsū* 
I cba to edit that, thanks
Anyone doing commissions for discord bots?
!rule 9
cant help
Oh crap
Well could you do it for free?
it's a simple bot, ig, i just want it where if someone types in a certain command it responds with something
Why do u even need someone to make such an easy bot :[
want to look cool that the server has their own private bot 
not being rude or anything
lol
I meant, just ask here how to make such a command instead of paying anyone else to do solol
no comments
There are already numerous spoonfeeders here 🤣
lmao
Does the same job, but for free
Stating facts
True true
So basically, I've been trying to get commands to work with perms and the roles who have that permission are defined (by ID) in a seperate file. But whenever I try to use the command it comes back with "You are missing at least one of these roles insert IDs".
Currently looks sort of like this:
from sys import prefix
import discord
from discord.ext import commands
from env import KICKPERMS, PREFIX, TOKEN
client = commands.Bot(command_prefix = PREFIX)
@client.event
async def on_ready():
print("Bot is ready")
#Kick command
@client.command()
@commands.has_any_role(KICKPERMS)
async def kick(ctx, member : discord.Member, *, Reason=None):
await member.kick(reason = Reason)
await ctx.send(f'User {member.mention} has been kicked for {Reason}')
And this is my second file
TOKEN="x" # bot token
PREFIX="." # prefix for commands
KICKPERMS = 95139573945034754, 951394182705053706
um
async def claim(name, code):
async with aiosqlite.connect('database.db') as db:
name = str(name)
code = str(code)
cur = await db.execute(f"UPDATE CODES set {code} = 1 WHERE NAME = ?", (name,))
await db.commit()``` why unrecognized token :V
discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '(95139573945034754, 951394182705053706)'
The error
WE HAVE LONGED IN
Traceback (most recent call last):
File "main.py", line 54, in <module>
keep_alive.keep_alive()
AttributeError: 'function' object has no attribute 'keep_alive'
host my bot on repl.it but its showing error
r e p l i t
i hate unrecognized token error
it worked now
It should be *KICKPERMS inside the @commands.has_any_role()
@commands.has_any_role(*KICKPERMS)
g a r b a g e
agreed verified
help?
discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)
What is this error?
You're my god
why unrecognized ;-;
Repl or Visual Code Studio for discord bot?
after making a dc bot now wandering whr the messages that the bot receving?
?
what.....
the msges u do personally to bot, where can i see them
in dms
my dms wont show what the bot is receiving
still dont understand wht you're asking
How can I make the bot auto leave a server then blacklist the server i.e not let it join anymore
You could make the bot auto add the DMs to a text file or send the DM to a channel?
help
!d disnake.Guild.leave and store the guild id and check everytime your bot joins a guild
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild.delete "disnake.Guild.delete").
to_leave = client.get_guild(id)
await to_leave.leave()```
imagine spoonfeeding 
Ok ty
Imagine (still need to store it in a db lmao)
not a big deal
Told u many people do the job for free 👀
still need help
Wym
the error:
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: unrecognized token: "3025P"```
3025P is the value of variable "code"
i want to make a discord bot but idk all the discord commands... where can i learn it all?
but-
the last time i use f-sdtring that work :V (idk u join or not but here blacktarsier and 1 more guy i forgor debating that f string problem)
client async and all that
i guess..
i tried doing it with c# cuz ik it better but i want to do it with python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ok thx
well, i wanna add claim code system, i use a single table with users ID and columns with codes
no, i use CODES as table name
ok :V
wut
🗿 huh
do u mean by what thing i passed in variable code?
🗿 what
use elifs?
ok, here's the one in main.py
@bot.command()
async def claim(ctx, code):
name = ctx.author.id
if code in codes:
await database.claim(name, code)
await ctx.send(f"used code {code}!")
else:
await ctx.send("lol, code is unavailable")```
???
bruh
!claim code
???? that's a variable dude
Code is a string.
So you'd do !claim blahblahblah
code = blahblahblah for example
Is what I'm understanding
:v ok, thanks for explaining
@small igloo
Can you give an example code?
the random string one :V
me create
i create code to claim
m a n n u a l l y
🗿 how i am supposed to explain
"CODE", "3025P"
]``` the "codes" from ```py
@bot.command()
async def claim(ctx, code):
name = ctx.author.id
if code in codes:
await database.claim(name, code)
await ctx.send(f"used code {code}!")
else:
await ctx.send("lol, code is unavailable")``` example of code: `3025P`
and what happens when they claim one
that's the function of py async def claim(name, code): async with aiosqlite.connect('database.db') as db: name = str(name) code = str(code) cur = await db.execute(f"UPDATE CODES set {code} = 1 WHERE NAME = ?", (name,)) await db.commit() code, set the value to 1 in the database
send message
Ok, anything else?
database thing
Ok, so when the code is claimed, it sends a message and updates the db?
f string in sql execute statement? cur = await db.execute(f"UPDATE CODES set {code} = 1 WHERE NAME = ?", (name,))
why is there f string in SQL query? (non relevant to that error)
how do i make these type of buttons
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
eh wait
It's a drop-down menu
select
?
yes
Do not:
cursor.execute("SELECT * FROM table_name WHERE value = {}".format('peepeepoopoo'))
Do:
cursor.execute("SELECT * FROM table_name WHERE value = ?", ('peepeepoopoo',))
Consider: if a command accepts user input, and they input True; DROP TABLE table_name- The resultant query with format is:
SELECT * FROM table_name WHERE value = True; DROP TABLE table_name which has obvious results.
Utilizing your SQL library's sanitization methods prepares the statement and exclusively inserts the values, without editing the query.
Note postgresql uses $1, $2, ... for value substitution, mysql, %s, so make sure you know your DB!
https://xkcd.com/327
consider reading this
lol
? won't work with column names
btw if like dat, so i can do
async def claim(name, code):
async with aiosqlite.connect('database.db') as db:
name = str(name)
code = str(code)
cur = await db.execute("UPDATE CODES set ? = 1 WHERE NAME = ?", (code,name))
await db.commit()``` huh?

that's a column name oh
why are you creating a connection to your db everytime the command is ran
idk lol :v
use an open connection attached to a bot var

h o w
!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!
wdym how
instead of the string for that variable, you can have a connection...
depends on how you want to use it.
me use different file for main and database editing
have you tried reading this
no, but he tried deleting it for sure 
:vvvv
yes
thats just an OOP concept, you can add your own attributes to a class and access them anywhere within the class
wait, i can do filename.bot.varname??
yes
!e ```py
class MyClass:
...
c = MyClass() # as in bot = commands.Bot
c.db = "my database connection" # make a connection, attach it to the bot
print(c.db) # and its now one of the bot's atrributes
@slate swan :white_check_mark: Your eval job has completed with return code 0.
my database connection
ow ok
similarly py bot.database = #connecting to db and accessing it with bot.database wherever you want
now what is the connection between it and my db problem :V
nothing
it's just... bad to connect to the db each time you need something
you are making connection with the database everytime you perform an operation, which is both memory and speed wise bad
its like, you are moving things in-and-out of a room , and everytime you go inside the room you open the door and close it again when moving out.
:vvvvvvv ok
then i am funny 🤣
what was your initial problem tho
token error in
async def claim(name, code):
async with aiosqlite.connect('database.db') as db:
name = str(name)
code = str(code)
cur = await db.execute(f"UPDATE CODES set {code} = 1 WHERE NAME = ?", (name,))
await db.commit()``` the code part
is the code "3025P"?
yes\
if so, you can't have column names starting with a number
sadge, ok then
what if P30S25
that would do
ok then :V
you can also do _3025P
that worked! ggty
how can i make 'can't mute/ban a moderator' error
any ideas?
from discord.ext import commands, tasks
from discord.ext.commands import MissingPermissions, CheckFailure, MemberNotFound
class Moderation(commands.Cog, name="moderation"):
def __init__(self, bot):
self.bot = bot
@commands.command(name="kick", description="Foloseste .kick pentru a dat kick unui membru.")
@commands.has_permissions(ban_members = True)
async def kick(self, ctx, member : discord.Member, *, reason=None):
await member.kick(reason = reason)
await ctx.channel.send(f'{member.mention} has been kicked by {ctx.message.author.mention} for reason of: {reason}!')
await member.send(f" You have been kicked from: {guild.name} reason: {reason}")
@kick.error
async def kick_error(self, ctx, error):
if isinstance(error, MissingPermissions):
await ctx.reply("You don't have permission to kick members.")
if isinstance(error, MemberNotFound):
await ctx.reply("Member not found.")
def setup(bot: commands.Bot):
bot.add_cog(Moderation(bot))
if the target user you are trying to ban has mod role, don't ban it
Can you repeat?
So eh, if the member you are trying to ban has any mod role send error message, is this what you want?
yes
oh wait
@commands.has_permissions(ban_members = True) i have to change this to a have role and then what
You can also make custom check, or just write if statement in your code to check it.
how can i make that
thats my last question
if member.top_role >= ctx.author.top_role:
await ctx.send(f"You can only moderate members below your role")
return
like that?
Basically a function that takes a ctx as argument and returns commands.check
def my_check():
def inner(ctx):
return modrole in ctx.author.roles
return commands.check(inner)```
And then uh
@commands.command()
@my_check()
async def some_mod_command(...)```
I don't really remember cause I use cog checks
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
Yeah this is correct
Afaik you can't parse args to checks so the only way would be checking that inside of a function
i need help. i cant make my discord.py economy bot work with sqlite. im very desperate and need help: this is my code btw
@client.event
async def on_ready():
client.database_connection = await aiosqlite.connect("money_data.db")
db = client.database_connection
cursor = await db.cursor()
await cursor.execute("""CREATE TABLE IF NOT EXISTS money_data(
num INTEGER NOT NULL PRIMARY KEY user_name TEXT,
balance INTEGER,
user_id INTEGER NOT NULL
)""")
await db.commit()
print("Ready!")
@client.command(aliases=["balance", "bal"])
async def show_balance(ctx):
db = client.database_connection
USER_ID = ctx.message.author.id
USER_NAME = str(ctx.message.author)
await cursor.execute(f"SELECT user_id FROM money_data WHERE user_id=(USER_ID)")
result_userID = await cursor.fetchone()
if result_userID == None:
await cursor.execute("INSERT INTO money_data(user_name, balance, user_id)values(?,?,?)",(USER_NAME, START_BAL, USER_ID))
await db.commit()
await ctx.send("Hi, you're a new user and you need to register/nTo register execute the command one more time!")
else:
await cursor.execute(f"SELECT balance FROM money_data WHERE user_id={USER_ID}")
result_userBal = await cursor.fetchone()
await ctx.send(f"{USER_NAME}'s balance!/n/nMoney:/n$(result_userBal[0])")```
sigh
- Make a connection to the database throughout without connecting to it each time
- Don't use f-strings in operations
how do i make it so its connected all the time?
also what kind of string should i use then?
replace
await cursor.execute(f"SELECT balance FROM money_data WHERE user_id={USER_ID}")
with
await cursor.execute("SELECT balance FROM money_data WHERE user_id=?", (USER_ID,))
like you did before
Do not:
cursor.execute("SELECT * FROM table_name WHERE value = {}".format('something'))
Do:
cursor.execute("SELECT * FROM table_name WHERE value = ?", ('something',))
Consider: if a command accepts user input, and they input True; DROP TABLE table_name- The resultant query with format is:
SELECT * FROM table_name WHERE value = True; DROP TABLE table_name which has obvious results.
Utilizing your SQL library's sanitization methods prepares the statement and exclusively inserts the values, without editing the query.
Note postgresql uses $1, $2, ... for value substitution, mysql, %s, so make sure you know your DB!
^
why do i get this error? The check functions for command reload_cog failed. and how can i solve in in on_command_error? in disnake
why not just fix the check functions, otherwise your command will never work
wdym?
the check functions are failing for the command, there must be something wrong with them
does it work otherwise?
Why not use f strings EDIT: I’ve read the code
in the check, am checking if the user of the command is a owner, and when i use the command (am the owner) it shows no error, but when someone else uses it, it shows the error
the code:
async def cog_check(self, ctx: commands.Context):
if not await self.bot.is_owner(ctx.author):
await ctx.reply(
"Only the Members of Dev Team are allowed to use this command!!"
)
return False
return True
Just use commands.has_any_role?
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
also it does sends the Only the Members of Dev Team are allowed to use this command!! message when a non owner uses it @slate swan
so where's the error?
it also prints the error, after showing the message
oh ic
I recommend you to use @commands.is_owner and add error handler. Something like thispy cog_check.error async def cog_error()
👍
......?
wait nothing i will delete that
didnt got you...
That's a thing? Idk
!d discord.ext.commands.Cog.cog_command_error
await cog_command_error(ctx, error)```
A special method that is called whenever an error is dispatched inside this cog.
This is similar to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") except only applying to the commands inside this cog.
This **must** be a coroutine.
This? 👀
For example```py
@commands.command()
@command.is_owner()
async def hello(self, ctx):
await ctx.send("hey")
@hello.error
async def hello_error(self, ctx, error):
... ```
Why local error handler, just why 
Idk i just prefer that
🤓
umm......
Eh u dont get it
lets not use local handlers...
hi, why does my code not work? Im using a .ini file as config file but I only get errors when I try to run it and I have tried to print the token and that works, it does print the correct token
config.ini
[Bot]
TOKEN = 'BOT_TOKEN'
# Config File
file = 'config.ini'
config = ConfigParser()
config.read(file)
bot.run(config['Bot']['TOKEN'])
Error:
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.ilure: Improper token has been passed.
Get a new token
the token's not correct?
I have tried it, just 1 min ago
Its a bot token
then it should work
but it doesnt.....
:| eeh
maybe the token got regenerated?
@maiden fable
Just use @commands.is_owner deco then
Do one thing
nope, I just generated a new token and it does the same thing
what?
Print the token, and paste it here BUT remove the part after the 2nd period in the token... That's one of the most important part of the token, so there won't be any chances of token leak by this way
Did u see the new system?
actually got the solve
but why do I have to paste it here even if it is not the whole token... how would that help?
Yup
Hmm well... try putting the token directly. Then, does it work?
discord gettin stronger
Meh, useless changes. They should focus on bringing context menus to mobiles first
yea it does work if I put the token directly there
agreed
That's.... weird
BTW, may I ask why r u using an ini file?
I mean, most people use env files and such
well is there a reason I shouldnt use ini? It is just that file Im used to
Is json better than yaml?
Ah, gotcha. Was just asking since not many people use ini
Weird... it should work, I mean
Can u try running it again? The bot
And r u sure u r parsing the correct ini file? (In case there are multiple ini files)
just same error and I only have 1 .ini file
sigh
maybe I should just try to use .env instead, Ig
Ash, Saad, got any ideas?
But it should work tbh
Same, but since they are saying that it's printing the correct token, it should work
yea its weird... it should work
have you double checked that the token is correctly parsed by printing it?
I mean, a few people before too have used ini files
I've seen alot of ppl using ini files for gta sa moding
yea... the token is correct and I have generated new tokens multiple times if it was something wrong with the token
ini files are used by most games as config files, not only mods, not a new thing
Ic ic
if it worked fine pasting the token into your code then its very likely something happened during parsing
Hey @maiden fable! 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://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
it's half token
shrug
ODAwOTc4yMjI1MzkxNjU2.YAZ_.TO8k7-5suwuHU0pls
There
Is yr token also like this, but longer?
even decades ago its been used by windows itself lol but after a while microsoft created Registry Editor
It should have 2 periods
Oh, never knew that
it looks like that, not longer or so
wow i just realized that
Should be of like, around 50 chars
i have an OG token
The first part refers to the Bot ID
The second part refers to the datetime at which it was generated
The third part is a super duper secret discord authentication code
yea.... there is nothing wrong with the token...
ThTs how @unkempt canyon also decides if a token is fake or not
X5q2IQ how tf will this help as datetime ( its an used token aka not vaild token )
smh my brain
i can relate
after a session of reading the new dpy docs that brain will be gone ngl
the new dpy is super hard
to understand
The new dpy docs looks like disnake docs
Yep they added alot of stuff
i mean the new features
True
like CommandTree
Have you tried printing config['Bot']['Token']?
just this
Wut does that do?
iirc its to make slash commands and app commands
Ohh
Agreed
I believe that uhm alot of forks of dpy are going to shutdown
Ig🤷🏾
i dont think so
if the forks are easier to use then the main lib i will say majority will switch
Yep
this emoji looks funny lmao
It's converted to base64
Same with Bot ID
sus
@bot.comand()
async def feed(ctx):
food = ["cheese","burrito","taco","popcorn","burger","chocolate","cookie","sushi","spaghetti","bread","noodle","eggplant","peach"]
re2 = ["Ben liked that a lot","Thank you","Ben didn't like that","More? please?","more","Ben wanted to eat something else..","im already full!","Tasty!","yummy","delicious!","blehh","no"]
await ctx.send(embed=emb)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content in ["cheese","burrito","taco","popcorn","burger","chocolate","cookie","sushi","spaghetti","bread","noodle","eggplant","peach"]
msg = await bot.wait_for("message",check=check)
if intmsg.content == food:
await ctx.send(random.choice(re2))
else:
await ctx.send("What? thats not even in the fridge....")
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
how do i fix the error
I physically can't edit your code to the correct form
Just align it
If I can call it that
okay
But uh you know about python indents right?
yes i do,just forgot about that because i didn't code for days because of exam
@bot.comand()
async def feed(ctx):
food = ["cheese","burrito","taco","popcorn","burger","chocolate","cookie","sushi","spaghetti","bread","noodle","eggplant","peach"]
re2 = ["Ben liked that a lot","Thank you","Ben didn't like that","More? please?","more","Ben wanted to eat something else..","im already full!","Tasty!","yummy","delicious!","blehh","no"]
await ctx.send(embed=emb)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content in ["cheese","burrito","taco","popcorn","burger","chocolate","cookie","sushi","spaghetti","bread","noodle","eggplant","peach"]
msg = await bot.wait_for("message",check=check)
if msg.content == food:
await ctx.send(random.choice(re2))
else:
await ctx.send("What? thats not even in the fridge....")
@vale wing is it aligned now?
Wrong
msg = ... must be in the code block
and the if statement too
@slate swan what code editor do you use
seems like notepad)
Really
idle is a thing too
b64encode
Well I am guessing this is replit
notepad ofc
lol
xd
It is a text editor, not an IDE BTW
!d discord.Message.jump_url
property jump_url```
Returns a URL that allows the client to jump to this message.
Ty
Np
Hey,
I want to use my Discord Bot on multiple servers. But there is a big Problem I have to solve.
Its a game Bot and if you would start a game on different servers at the same time, they would interfere with each other, which would be really bad.
Is there a way to avoid this easily? Or do I have to check every Input for its origin?
if the game is started through a command, you should try to stick inside that scope by using methods like client.wait_for(), that way you dont need an always running event handler
wait_for provides a check parameter you can use to only receive messages from a specific member/channel
yes its started through a command, but a lot of stuff is happening in "on_message".
It should be possible to play this game at the same time at different servers without problems, would this be possible?
yeah wait_for makes that pretty clean to do
that would be amazing.
While playing I am saving data in files (and later in a sql database), could this be a problem?
though if your games are long-running (to the point where you store sessions in a database) then event handlers would be easier
one game is like 15min
Which way is easier to learn and which is easier to expand later on? 🙈
i think wait_for is both easier and simpler than running an on_mesaage, but it wont be suitable for listening to messages across bot restarts
there's an example on how to use it in the docs
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
It returns the same args, which that particular event takes
This sounds very specific. When the game starts, The bot will start a "guessing" game and everyone has to write there guesses until someone got the right one (or the time runs up).
Its easy with on_message -> just check if the words are correct.
Would this be possible with "wait_for"? And does "wait_for" replaces "on_message"?
just check for the right word in the wait_for's check function
click on the hyperlink in the tag and see some examples for yourself
okay I will. If this works you saved me soo much time haha
you pass the check function to your wait_for and it will only pass if what the check returns is either an object or a True type bool
But this sounds like I can only start one game in general.
let me read the doc. for a moment
no, wait_for is still asynchronous
you can have a dozen commands all running their own wait_fors
yeah thats exactly what I need. Sorry one more question to clarify.
I have a variable which contains all people who send words in.
Would this variable be unique for each Server or would it be a mix from everywhere? (If I understood correctly, it would be unique for each Server right?)
yeah every time the command is run, you're creating new variables in that scope

how do i make this list of available options on slash command?
The current version of the bot is (for me) quit big and cointains multiple commands, functions and a lot of stuff is going on in "on_message" and "@tasks.loop() async def send_message():"
And this is all needed to run a game. Do I have to recode everything then?😅
if you're doing a guessing game or something along the lines yes you should, you can probably do it in just one method
well, there's always a better way to do what you did
Yeah absolutely and it was one of my first projects in general. But I think recoding everything would take just soo much time.
programming is all about taking time and have patience
don't seem right to me either
every programmer should have patience i.e getting an error and not freaking out
the import nextcord line already
depends on the library you use that provides slash commands, you should check their documentation
Thanks for your help guys. Not completely sure what to do now, but way smarter then before
json for db?
How do I make a bot join the vc Im currently on. I have all the intent stuff done

XD
get channel
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
ty
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
but still, how to get the channel..... ctx.author.smth?
ctx.author.voice.channel
sooo
!d discord.Member.voice
property voice```
Returns the member’s current voice state.
await ctx.author.voice.channel.connect()
@bot.command(name = 'join')
async def joinvc(ctx):
vc = ctx.author.voice.channel
await vc.connect()
is that right?
not needed var
ohk
@cold sonnet help meh
lemme get on that computer real slow
no
so disconnecting?
await ctx.guild.me.disconnect()
This no spaghetti
.
Hahaha
yeah, you can use any
but where problem
ok
hunter no ask help long time
hunter forget how ask
Got confused with InteractionResponse and InteractionResponseFollowup
or whatever its called 🤷
dunno what those are
!d disnake.InteractionResponse
class disnake.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://docs.disnake.dev/en/latest/api.html#disnake.Interaction.response "disnake.Interaction.response").
New in version 2.0.
Nvm I get it now, thanks meh
you're welcome
this is what happens when u open your bot's source after months
view=CommandsView(
[
CommandsDropdown(
bot=self.bot,
placeholder="Message Commands",
type_of_commands=self.bot.message_commands,
custom_id="msg_commands",
is_owner=False
),
CommandsDropdown(
bot=self.bot,
placeholder="Text Commands",
type_of_commands=self.bot.commands,
custom_id="text_commands",
is_owner=False
),
CommandsDropdown(
bot=self.bot,
placeholder="User Commands",
type_of_commands=self.bot.user_commands,
custom_id="user_commands",
is_owner=False
),
CommandsDropdown(
bot=self.bot,
placeholder="Slash Commands",
type_of_commands=self.bot.slash_commands,
custom_id="slash_commands",
is_owner=False
)
],
inter
)
```looks bad, use for loops, they cool
How tf do u expect me to use for loop here
now wait a damn minute
Hunter forgot how to ask questions cz he is the one who answers questions
view=CommandsView(
[
CommandsDropdown(
bot=self.bot,
placeholder=f"{stuff} Commands",
type_of_commands=self.bot.message_commands,
custom_id=f"{stuff.lower()}_commands",
is_owner=False
)
] for stuff in ("Message", "Text", "User", "Slash"),
inter
)
nah this no
Uhhhhh
Lmao
I'm on the right path
Okay
current_uploads = data[str(ctx.author.id)]['total_uploads']
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str``` what do i do
newOptions = [
SelectOption(
label=str(day)
) for day in range(days+1)
]
this was my code in another bot
so I was right the first time
Mind rewriting my bot for me?
view=CommandsView(
[
CommandsDropdown(
bot=self.bot,
placeholder=f"{stuff} Commands",
type_of_commands=self.bot.message_commands,
custom_id=f"{stuff.lower()}_commands",
is_owner=False
) for stuff in ("Message", "Text", "User", "Slash")
],
inter
)
!rule 9
heheeee
Never said I am gonna pay u
paid work of 0$
Gonna give u premium oxygen 😉
view = CommandsView(
[
CommandsDropdown(
bot = self.bot,
placeholder = f"{stuff} Commands",
type_of_commands = self.bot.message_commands,
custom_id = f"{stuff.lower()}_commands",
is_owner = False
) for stuff in ("Message", "Text", "User", "Slash")
],
inter
)
```ain't this pep8er
Sorry, went to edit some more things
Anyways, its ot 🤷
def not
aka me

Hm?
why did you deleted the msg
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: UnsupportedOperation: not readable help
with open('uploads.json', "w") as f:
data = json.load(f)
You can't read from it without read perms
Yea, u gotta do r
When you specify w it doesn't even load the contents into memory
"w" means write
^w^
np
lets say i have a command
async def command(ctx, one_arg):
pass
is there a way to make it so that while calling, all other args get ignored
!command onearg ignored_arg
without going and adding *arg to it?
You can assign parameters to None, so if the user would send them they became what the user sent, otherways they're None
hey guy can some help me with opencv puttext display ui
optional arguments
I believe that's not what they asked
They want the command to still work if more than required arguments are given
is what I figured
yes
WTF?
then no
like i got 20 commands, i dont wanna be adding *args to each of them
*args refers to a unknown amount of arguments which returns a tuple
can multiple things be saved in one saving thingy in json ? so its like test: "1" "2" "3" ?
current_urls = data[str(ctx.author.id)]['urls']
updated_urls = f"{current_urls}" + url
``` cuz this is just saving it inside the used ""
list
how i do that
umm... {"test": ["1", "2", "3"]}
and how do i make my bot save it like this? lol
save it as an int
so the list has ints and not strings that are ints
this is the default behavior for commands actually, the ignore_extra parameter for command() defaults to True
he asked it like strings
i want it to save strings
fair point but im not sure if its still a correct way
what i want to save is links lol
data[str(ctx.author.id)]['urls'] = [url]
``` does this work
thats what i want to do if there are no urls in it lol
yes, why not
wait can i just send my code to someone to help me with it? :-:
just use len
json 
!e print(len({1: 2}))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1
yea, json i dont use sql or anything atm.
im confused can someone just look at my code
havent you been given answers already?
thanks 👍🏻
!e print(not {})
@buoyant quail :white_check_mark: Your eval job has completed with return code 0.
True
will always give true as an empty dict is False
ik
just saying to everyone lol
ahh
with open("uploads.json", "r") as f:
data = json.load(f)
if str(ctx.author.id) not in data:
data[str(ctx.author.id)] = {}
data[str(ctx.author.id)]['total_uploads'] = 1
data[str(ctx.author.id)]['urls'] = [url] #hope this works
with open("uploads.json", "w") as f:
json.dump(data, f, indent=2)
current_uploads = data[str(ctx.author.id)]['total_uploads']
current_urls = data[str(ctx.author.id)]['urls']
updated_uploads = current_uploads + 1
updated_urls = f"{current_urls}" # i want it to save another url seperated
data[str(ctx.author.id)]['total_uploads'] = updated_uploads
with open('uploads.json', "w") as f:
json.dump(data, f, indent = 2)
```where do i do what lol i marked it with "#"
try it out
i want it to save another url seperated
save another URL then?
the same way you saved the URL
so i just do this bruh or what
havent really used that stuff
bruh
.. what?
thats how i saved a url
u told me to use it again
data[str(ctx.author.id)]['urls'].append("new url here")
The "urls" key stores a list, so you can just append a new one like that.
updated_uploads = current_uploads + 1
updated_urls = data[str(ctx.author.id)]['urls'].append(url)
data[str(ctx.author.id)]['total_uploads'] = updated_uploads
data[str(ctx.author.id)]['urls'] = updated_urls
``` like this ? :)
No
append changes list
that will overrite the old key
it returns None
updated_uploads = current_uploads + 1
updated_urls = data[str(ctx.author.id)]['urls'].append(url)
data[str(ctx.author.id)]['total_uploads'] = updated_uploads
data[str(ctx.author.id)]['urls'] = updated_urls
with open('uploads.json', "w") as f:
json.dump(data, f, indent = 2)
``` thats the whole thing btw lol
what do i have to change ?
data[str(ctx.author.id)]['urls'].append(url)
and delete updated_urls =
and this too data[str(ctx.author.id)]['urls'] = updated_urls
You don't need to use the return value of append. Just call append and you're done - you can dump it to a file.
help im confused :(
append modifies the list in-place rather than returning a new one
can someone edit my code? im really confused rn...
how are you confused?
my brain is small
Where did you define data?
why do you have ```py
data[str(ctx.author.id)]['urls'] = updated_urls
sec i sent wrong code
with open("uploads.json", "r") as f:
data = json.load(f)
if str(ctx.author.id) not in data:
data[str(ctx.author.id)] = {'total_uploads': 1, 'urls': [url]}
data[str(ctx.author.id)]['total_uploads'] += 1
data[str(ctx.author.id)]['urls'].append(url)
with open('uploads.json', "w") as f:
json.dump(data, f, indent=2)
learn python first pls
with open("uploads.json", "r") as f:
data = json.load(f)
if str(ctx.author.id) not in data:
data[str(ctx.author.id)] = {}
data[str(ctx.author.id)]['total_uploads'] = 1
data[str(ctx.author.id)]['urls'] = [url] #hope this works
with open("uploads.json", "w") as f:
json.dump(data, f, indent=2)
current_uploads = data[str(ctx.author.id)]['total_uploads']
current_urls = data[str(ctx.author.id)]['urls']
updated_uploads = current_uploads + 1
updated_urls = data[str(ctx.author.id)]['urls'].append(url)
data[str(ctx.author.id)]['total_uploads'] = updated_uploads
data[str(ctx.author.id)]['urls'] = updated_urls
with open('uploads.json', "w") as f:
json.dump(data, f, indent = 2)
This is why I hate json, it turns into [] and str() hell
data[str(ctx.author.id)]['urls'] = updated_urls
``` why do you need this
cuz i thought its correct
:(
Perhaps consider using a database?
^
!d discord.User.status
!d discord.Member.status
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
i did that once, i dont like it cuz it didnt work lol
How would it not work
Remove it, and do you know what overwriting means
don't spoonfeed, they will never learn that way
and what do i do in the
current_uploads = data[str(ctx.author.id)]['total_uploads']
current_urls = data[str(ctx.author.id)]['urls']
updated_uploads = current_uploads + 1
updated_urls = data[str(ctx.author.id)]['urls'].append(url)
data[str(ctx.author.id)]['total_uploads'] = updated_uploads
data[str(ctx.author.id)]['urls'] = updated_urls
problem is im learning since about 8 months and im still getting confused easily, once i get examples my brain works again smh
its this:
data[str(ctx.author.id)]['total_uploads'] += 1
data[str(ctx.author.id)]['urls'].append(url)
- why does time matter? It doesn't take long to get good at python, it's one of the easiest languages to learn
- you mean getting spononfeeded?
why does it save it 3 times lol
cause variable url didn't change
with open("uploads.json", "r") as f:
data = json.load(f)
if str(ctx.author.id) not in data:
data[str(ctx.author.id)] = {'total_uploads': 1, 'urls': [url]}
data[str(ctx.author.id)]['total_uploads'] += 1
data[str(ctx.author.id)]['urls'].append(url)
with open('uploads.json', "w") as f:
json.dump(data, f, indent=2)
current_uploads = data[str(ctx.author.id)]['total_uploads']
current_urls = data[str(ctx.author.id)]['urls']
data[str(ctx.author.id)]['total_uploads'] += 1
data[str(ctx.author.id)]['urls'].append(url)
with open('uploads.json', "w") as f:
json.dump(data, f, indent = 2)
and that means ?
'urls': [url] first time
data[str(ctx.author.id)]['urls'].append(url) second time
data[str(ctx.author.id)]['urls'].append(url) third time
oh i think i did something wrong
!resources :)
what do i have to do help :(


