#discord-bots

1 messages · Page 895 of 1

somber sky
#

barely lol

sick birch
#

Guessed as much (no offense)

oblique laurel
#

Id suggest you try working through some tutorials over the fundamentals, then coming back. Itll save you a world of pain lol

sick birch
#

Honestly yeah, you can solve trivial problems like this within minutes and move on and spend your time on more interesting problems

boreal ravine
oblique laurel
#

Yeah. You have good ideas it seems, you just need to learn how to tell the computer about them

sick birch
#

Happens way too much

woven ingot
#

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?

sick birch
sick birch
#

Run multiple discord bots within one machine, dockerize it if you want

woven ingot
sick birch
#

Yes, micro instances will work fine

boreal ravine
#

you didn't learn properly

oblique laurel
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

sick birch
#

And the micro instances aren't all that expensive so it's perfect

woven ingot
sick birch
#

I host multiple applications of mine on AWS, yes

oblique laurel
boreal ravine
#

||railway.app|| dehd

sick birch
#

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

woven ingot
sick birch
boreal ravine
#

isn't AWS paid?

oblique laurel
#

Or is that an S not a $

sick birch
woven ingot
sick birch
oblique laurel
sick birch
#

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

oblique laurel
sick birch
#

If we say your bot is in a few guilds with not much traffic, you can run up to 10

woven ingot
oblique laurel
#

Ngl idk if its cuz im broke but i prefer just using my own machine, seems more secure

sick birch
sick birch
#

Higher upkeep, less secure than professionally provided hosting services

woven ingot
sick birch
#

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

raven owl
#

guys better to use javascript or python for discord bot

oblique laurel
#

I mean how would it not be secure to have smth running on my local network? No one else rlly uses it

sick birch
raven owl
#

whats ur personal prference

oblique laurel
sick birch
sick birch
raven owl
#

ok is there any tutorial for python discord bots

sick birch
#

But don't go off doing what I do just because I do it

raven owl
#

or javascript discord bots

sick birch
oblique laurel
raven owl
#

ok what abt javscript

sick birch
raven owl
#

do i have to learn node js

#

or javascript only

oblique laurel
sick birch
raven owl
#

k

sick birch
#

And it was created specifcally to address many flaws found in youtube tutorials which is great

oblique laurel
#

I swear, a good discord bot tutorial on yt is harder to find than women in cs

sick birch
#

Though people still gravitate towards youtube tutorials which really drives me up the wall especially when they have things like client = commands.Bot(...)

oblique laurel
#

Yikes

raven owl
#

\u001b[{text};{red}m

#

?

sick birch
#

hmm

raven owl
#

got exam now bai

#

english

sick birch
#

I wish you luck

raven owl
#

thanks so good helpers UwU ; D

sick birch
#

Thank you!

raven owl
#

what language do you think i should learn after pythin

#

i am learning from a book

sick birch
#

Rust seems to be popping off right now

raven owl
#

ik a little js

#

rust is a language?? what does it do i am noob

sick birch
#

That, one of the C-langs, knowing Node.js/TS is always, knowing at least one of all of those is imporatnt

sick birch
raven owl
#

ok so next i learn javascript and node

#

then rust then c

#

something c

sick birch
#

Sure, C/C++ is good

#

Doing game dev will help you hone your C skills since UE uses C++ and Unity uses C# iirc

raven owl
#

ooo

#

better ue or unity

sick birch
#

Hard to tell

#

Both are used widely

oblique laurel
final iron
#

c to python lmao

oblique laurel
#

Universal speedometer for languages XD

final iron
#

😔

pliant gulch
#

To the C side

#

It’s even being used for speed important tasks such as kernels etc

oblique laurel
#

Interesting

pliant gulch
#

Rust is mostly just a memory safe C anyways

#

Borrowing concept is very cool though

#

Same with lifetimes

oblique laurel
#

The name makes it sound so old and outdated lol

sick birch
oblique laurel
#

Dang

sick birch
#

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

oblique laurel
#

Feel like ima become an old relic before i even finish learning python if i dont learn rust now lol

sick birch
#

Yeah been wanting to but way too lazy you know

oblique laurel
#

I just have no free time lol

#

i say as i chat in this server

final iron
#

🗿

sick birch
#

i think i've done nothing but help out here the entire day today

slate swan
#

¯_(ツ)_/¯

sick birch
#

It can be if you optimize it

slate swan
#

native python faster than c idkhmmcat

sick birch
#

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)

slate swan
#

prob

sick birch
#

they spend like 90% of the time waiting around

slate swan
#

lol

slate swan
#
if ctx.channel.id != 1234567890:
    return
sick birch
jade tartan
#
    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?
sick birch
#

Well it kinda says it right there

#
cogs must derive from Cog
jade tartan
#

ohh it suppose to say Cog instead cog

sick birch
#

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

maiden fable
#

Sleep Robin 👀

sick birch
#

big disconnect = big sad

sick birch
jade tartan
#
for filename in os.listdir('./Cogs'):
    if filename.endswith('py'):
        client.load_extension(f'Cogs.{filename[:-3]}')```
sick birch
#

give it a few hours

sick birch
#

Sure, do as okiimii said and put it in your on_message

#

Yessir

maiden fable
sick birch
#
@event_decorator
async def on_message(m):
  if something:
    return
  # everything else
maiden fable
#

Rip, I'm out of my mind I'mma just go

sick birch
#

in your case something you wanna check if the message is from a certain channel

jade tartan
#
  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

maiden fable
lofty dagger
#

send pls easy python game from discord bot

maiden fable
#

Robin gonna help u with it, thanks

slate swan
maiden fable
#

Or that, yea

sick birch
#

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

slate swan
slate swan
maiden fable
slate swan
maiden fable
jade tartan
#

Yes that botinfo cmd yes

sick birch
#

Easy then

maiden fable
sick birch
#

Just compare the ID of the channel message was sent in to 942234501642338314

maiden fable
sick birch
#

message.channel.id == 942234501642338314 perhaps

jade tartan
#

?

sick birch
#

Feel free to ping me. I'm off tomorrow and will probably be here

jade tartan
#

So?

sick birch
#

Unfortunate, I wish you luck

jade tartan
#

@slate swan

slate swan
jade tartan
#

You said if am using disnake i said yes

slate swan
#

show your bot file and your cog file

slate swan
slate swan
jade tartan
slate swan
#

no you can't do that. Choose 1

jade tartan
swift quiver
#

Hi can anyone help me with something

slate swan
sacred blaze
#

i am working face recoginition project i want to display details from csv file

slate swan
#

Migrate from discord.py to Disnake
Change all discord to disnake

swift quiver
#
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.')
slate swan
swift quiver
#

Is this any errors. because its showing for me

slate swan
#

dotn see any thing wrong

mint tangle
#

!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```
unkempt canyonBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

#
Command Help

!pep <pep_number>
Can also use: get_pep, p

Fetches information about a PEP and sends it to the channel.

slate swan
#

Except for the error when the user's dms are off

unkempt canyonBOT
#

Hey @swift quiver!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
slate swan
swift quiver
ivory shadow
#

does anyone know if slash commands are removed or smth?

slate swan
#

You can share with hastebin....

slate swan
ivory shadow
#

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.

sick birch
ivory shadow
#

I keep getting this error

swift quiver
sick birch
#

/shrug

swift quiver
ivory shadow
#

and it's causing my entire bot to stop

sick birch
slate swan
slate swan
#

Which is now outdated

ivory shadow
#

oh do u know how I can remove this cuz I need the bot to get back up

supple thorn
#

🗿

slate swan
#

Use discord.py master branch or some fork to make slash commands

ivory shadow
#

unfortunate

#

cuz I tried deleting the package and I keep getting

supple thorn
#

That error randomly comes and goes

#

Good luck

ivory shadow
#

rlly?

#

okay thank you i'll just hope it's fixed tmrw

#

tysm

slate swan
#

not related to replit

supple thorn
#

Replit does have that issue

#

Ive gotten that issue before

#

And was stuck like that for hours

#

Just randomly went way after some time and i could finally remove discord.py

swift quiver
sick birch
#

Well I doubt hastebin would be giving you that error

swift quiver
#

can i just send u it in dms

sick birch
#

DMs are closed sorry

#

If you send it here and it has a valid token, discord should automatically reset your token

supple thorn
#

I saw

slate swan
#

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

stiff kayak
#

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

sick birch
#

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"

swift quiver
vagrant lodge
sick birch
stiff kayak
sick birch
#

It is dispatched to you though (i think)

stiff kayak
#

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

sick birch
#

on_voice_status_update() is an event perhaps

#

Actually I don't think that tells you when someone stops/starts talking

supple thorn
swift quiver
stiff kayak
sick birch
stiff kayak
#

no, if someone speaks

supple thorn
sick birch
supple thorn
#

Thought it was that bug

stiff kayak
#

there is no way to check if a user is speaking in vc?

sick birch
#

Doubtful

stiff kayak
#

How does the voice chat highlight thing work. The one that lights green whenever you speak in voice chat

#

could that be a workaround?

sick birch
#

That won't help either, no

stiff kayak
#

aww

#

Welp, thanks anyways.

sick birch
#

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

slate swan
#

oof

sick birch
#

Looks like a windows error, I'm not experienced with windows so unfortunately no

swift quiver
#

Uh alr.

slate swan
slate swan
boreal ravine
slate swan
boreal ravine
#

maybe

sick birch
sick birch
boreal ravine
#

they left?

sick birch
#

They're still here

cold oyster
#

Erm

#

How do I make a command which can only be used be a specific role

#

;) help

cold oyster
#

Oh Yeah! I forgot, Thank you!

cold oyster
sick birch
#

Let me check the docs

cold oyster
sick birch
#

Yeah looks like you can

cold oyster
#

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__*
torn sail
#

is there any error?

sick birch
slate swan
#

make it user: discord.Member

sick birch
#

Also does == None work?

#

!e

x = None
print(x == None)
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

True
slate swan
sick birch
#

Hm alright

slate swan
#

using is is always preferred

sick birch
#

Ye that's what i was thinking

slate swan
slow fog
#

Ash

slate swan
#

one compares ids while one compares value not sure how one is always preferred

maiden fable
slate swan
maiden fable
#

Just telling ¯_(ツ)_/¯

slate swan
#

no pep8AG_Angry

maiden fable
slate swan
maiden fable
#

Stop sending emojis in every message of yours, it's irritating asf

manic wing
slate swan
#

i mean hunter is mature and hes cool but thats not the point, the point is youre a kid as well AG_Angry

formal basin
#

How do I make it so it’s a custom role instead of the everyone role

slate swan
#

i have python 3.10 but i have this issue

maiden fable
maiden fable
slate swan
maiden fable
#

(:

slate swan
maiden fable
slate swan
oblique adder
#

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

oblique adder
maiden fable
#

Shouldn't take 12 min tho

oblique adder
#

ikr

#

but idk why it takes that long

maiden fable
#

My bot is in 130 servers, takes like 1-2 min

maiden fable
teal bloom
#

How do you countdown

oblique adder
#

is it because i am using autoshard ? could that be case ?

oblique adder
maiden fable
oblique adder
#

It is super annoying when restarting bot I want a way to fix this 😭

maiden fable
#

Try removing auto sharded bot

oblique adder
#

but on my alts which have 40 servers it only takes 30 secs 🤔
Sure I will try to remove auto sharded

#

thank you

manic wing
#

use discii instead

oblique adder
slate swan
#

@maiden fable

#

help

slate swan
slate swan
maiden fable
# slate swan

Seems like a wrong Python version has been selected

slate swan
#

what to do

maiden fable
#

What's yr IDE?

#

VSCode?

slate swan
#

looks like sublime ngl

#

Visual Studio 2019

#

@maiden fable

brittle axle
maiden fable
#

Oh hmm. At the bottom bar, mind showing yr selected Python version?

maiden fable
brittle axle
maiden fable
#

Rip idk how to set the Python version in it

#

Does it have a command pallete?

slate swan
maiden fable
#

Uhh, yea that. Thanks for telling

#

@slate swan try doing what, uhh, Shi Tsu said

maiden fable
#

I cba to edit that, thanks

slate swan
#

Anyone doing commissions for discord bots?

slate swan
unkempt canyonBOT
#

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

slate swan
#

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

maiden fable
#

Why do u even need someone to make such an easy bot :[

slate swan
#

not being rude or anything

#

lol

maiden fable
#

I meant, just ask here how to make such a command instead of paying anyone else to do solol

maiden fable
#

There are already numerous spoonfeeders here 🤣

slate swan
#

lmao

maiden fable
#

Does the same job, but for free

maiden fable
slate swan
#

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
small igloo
#

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

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

small igloo
small igloo
slate swan
#

it worked now

supple thorn
#
@commands.has_any_role(*KICKPERMS)
slow fog
small igloo
lost vine
#

discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)
What is this error?

slate swan
#

Repl or Visual Code Studio for discord bot?

#

after making a dc bot now wandering whr the messages that the bot receving?

slate swan
slate swan
#

my dms wont show what the bot is receiving

slate swan
modest plover
#

How can I make the bot auto leave a server then blacklist the server i.e not let it join anymore

modest plover
slate swan
unkempt canyonBOT
#

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").
small igloo
slate swan
modest plover
#

Ok ty

modest plover
slate swan
maiden fable
small igloo
#

the error:

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: unrecognized token: "3025P"```
#

3025P is the value of variable "code"

surreal palm
#

i want to make a discord bot but idk all the discord commands... where can i learn it all?

small igloo
#

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)

surreal palm
#

client async and all that

small igloo
#

use what then ;-;

#

lul ok

surreal palm
#

i guess..

#

i tried doing it with c# cuz ik it better but i want to do it with python

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

surreal palm
#

ok thx

small igloo
#

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?

small igloo
# small igloo 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

modest plover
#

Code is a string.

#

So you'd do !claim blahblahblah
code = blahblahblah for example

#

Is what I'm understanding

small igloo
#

:v ok, thanks for explaining

modest plover
#

@small igloo
Can you give an example code?

small igloo
#

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

modest plover
#

Ok, anything else?

small igloo
modest plover
#

Ok, so when the code is claimed, it sends a message and updates the db?

heavy folio
tawdry perch
#

why is there f string in SQL query? (non relevant to that error)

obsidian ledge
#

how do i make these type of buttons

heavy folio
#

!d discord.ui.Select

unkempt canyonBOT
#

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.
heavy folio
#

eh wait

modest plover
#

It's a drop-down menu

heavy folio
#

select

heavy folio
#

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

visual island
#

? won't work with column names

small igloo
small igloo
heavy folio
#

that's a column name oh

boreal ravine
heavy folio
#

use an open connection attached to a bot var

boreal ravine
small igloo
slate swan
unkempt canyonBOT
#

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!

heavy folio
#

wdym how

slate swan
#

instead of the string for that variable, you can have a connection...

#

depends on how you want to use it.

small igloo
heavy folio
slate swan
#

no, but he tried deleting it for sure kek_sympathy

small igloo
slate swan
#

thats just an OOP concept, you can add your own attributes to a class and access them anywhere within the class

small igloo
visual island
#

yes

slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

my database connection
small igloo
slate swan
#

similarly py bot.database = #connecting to db and accessing it with bot.database wherever you want

small igloo
#

now what is the connection between it and my db problem :V

visual island
#

nothing

heavy folio
#

it's just... bad to connect to the db each time you need something

slate swan
#

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.

small igloo
#

:vvvvvvv ok

slate swan
#

what was your initial problem tho

small igloo
# slate swan 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
visual island
#

is the code "3025P"?

small igloo
visual island
#

if so, you can't have column names starting with a number

small igloo
small igloo
slate swan
#

that would do

small igloo
#

ok then :V

visual island
#

you can also do _3025P

small igloo
wanton veldt
#

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))
tawdry perch
wanton veldt
#

Can you repeat?

tawdry perch
wanton veldt
#

yes

#

oh wait

#

@commands.has_permissions(ban_members = True) i have to change this to a have role and then what

tawdry perch
#

You can also make custom check, or just write if statement in your code to check it.

wanton veldt
#

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?

vale wing
#

Basically a function that takes a ctx as argument and returns commands.check

vale wing
#
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

unkempt canyonBOT
#

@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").
vale wing
#

Afaik you can't parse args to checks so the only way would be checking that inside of a function

regal cove
#

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])")```
spring flax
#

sigh

#
  1. Make a connection to the database throughout without connecting to it each time
  2. Don't use f-strings in operations
regal cove
regal cove
dusky pine
spring flax
# regal cove also what kind of string should i use then?

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!

dusky pine
#

^

regal cove
#

i am so confused

#

i will look over this and try to fix it all thank u

opaque tiger
#

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

slate swan
slate swan
# opaque tiger wdym?

the check functions are failing for the command, there must be something wrong with them

#

does it work otherwise?

slate swan
opaque tiger
# slate swan why not just fix the check functions, otherwise your command will never work

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

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@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")
opaque tiger
opaque tiger
slate swan
#

oh ic

slate swan
#

👍

#

......?

regal cove
#

wait nothing i will delete that

maiden fable
#

!d discord.ext.commands.Cog.cog_command_error

unkempt canyonBOT
#

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.
maiden fable
#

This? 👀

slate swan
# opaque tiger didnt got you...

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):
... ```

maiden fable
#

Why local error handler, just why lemon_pensive

slate swan
#

🤓

slate swan
#

Eh u dont get it

opaque tiger
#

lets not use local handlers...

slate swan
#

Y not??idk

surreal sierra
#

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'

main.py

# 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.
opaque tiger
#

the token's not correct?

surreal sierra
slate swan
#

Is it bot token or an acc token?

surreal sierra
#

Its a bot token

slate swan
#

then it should work

surreal sierra
#

but it doesnt.....

slate swan
#

:| eeh

opaque tiger
maiden fable
surreal sierra
surreal sierra
maiden fable
#

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

opaque tiger
surreal sierra
#

but why do I have to paste it here even if it is not the whole token... how would that help?

maiden fable
maiden fable
slate swan
maiden fable
surreal sierra
maiden fable
#

BTW, may I ask why r u using an ini file?

#

I mean, most people use env files and such

surreal sierra
slate swan
#

Is json better than yaml?

maiden fable
#

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)

surreal sierra
maiden fable
#

sigh

surreal sierra
#

maybe I should just try to use .env instead, Ig

maiden fable
#

Ash, Saad, got any ideas?

maiden fable
slate swan
#

Eh nope

#

i've never used ini.

maiden fable
#

Same, but since they are saying that it's printing the correct token, it should work

surreal sierra
hushed galleon
#

have you double checked that the token is correctly parsed by printing it?

maiden fable
#

I mean, a few people before too have used ini files

slate swan
surreal sierra
maiden fable
hushed galleon
#

if it worked fine pasting the token into your code then its very likely something happened during parsing

unkempt canyonBOT
#

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!

maiden fable
#

lemon_pensive it's half token

hushed galleon
#

shrug

maiden fable
#

ODAwOTc4yMjI1MzkxNjU2.YAZ_.TO8k7-5suwuHU0pls

There

#

Is yr token also like this, but longer?

slow fog
maiden fable
#

It should have 2 periods

surreal sierra
oak warren
maiden fable
oak warren
#

i have an OG token

maiden fable
# oak warren wow i just realized that

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

surreal sierra
maiden fable
#

ThTs how @unkempt canyon also decides if a token is fake or not

oak warren
#

smh my brain

slate swan
oak warren
#

to understand

slate swan
slate swan
oak warren
#

i mean the new features

slate swan
oak warren
#

like CommandTree

vocal snow
oak warren
slate swan
oak warren
#

iirc its to make slash commands and app commands

oak warren
#

you cant use the disnake way to do it

#

and i find the disnake way easier

slate swan
#

I believe that uhm alot of forks of dpy are going to shutdown

#

Ig🤷🏾

oak warren
#

i dont think so

#

if the forks are easier to use then the main lib i will say majority will switch

slow fog
maiden fable
#

Same with Bot ID

slow fog
slate swan
#
@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....")
vale wing
#

You forgot the indent

#

And they are messed up as I can see

#

!indents

unkempt canyonBOT
#

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

slate swan
#

how do i fix the error

vale wing
#

I physically can't edit your code to the correct form

#

Just align it

#

If I can call it that

slate swan
#

okay

vale wing
#

But uh you know about python indents right?

slate swan
#

yes i do,just forgot about that because i didn't code for days because of exam

gaunt ice
#

when i am runnig this

slate swan
#
@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?

vale wing
#

msg = ... must be in the code block

slate swan
#

and the if statement too

vale wing
#

@slate swan what code editor do you use

buoyant quail
#

seems like notepad)

vale wing
#

Really

slate swan
#

idle is a thing too

maiden fable
vale wing
slate swan
maiden fable
#

lol

buoyant quail
#

xd

maiden fable
#

It is a text editor, not an IDE BTW

inner wing
#

How get message link from message obj?

hushed galleon
#

!d discord.Message.jump_url

unkempt canyonBOT
inner wing
#

Ty

alpine furnace
uncut zephyr
#

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?

hushed galleon
#

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

uncut zephyr
uncut zephyr
hushed galleon
#

yeah wait_for makes that pretty clean to do

uncut zephyr
#

that would be amazing.
While playing I am saving data in files (and later in a sql database), could this be a problem?

hushed galleon
#

though if your games are long-running (to the point where you store sessions in a database) then event handlers would be easier

uncut zephyr
#

one game is like 15min

#

Which way is easier to learn and which is easier to expand later on? 🙈

hushed galleon
#

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

unkempt canyonBOT
#

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**...
maiden fable
#

It returns the same args, which that particular event takes

uncut zephyr
# unkempt canyon

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"?

cold sonnet
#

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

uncut zephyr
#

okay I will. If this works you saved me soo much time haha

cold sonnet
#

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

uncut zephyr
#

But this sounds like I can only start one game in general.
let me read the doc. for a moment

cold sonnet
#

no, wait_for is still asynchronous

hushed galleon
#

you can have a dozen commands all running their own wait_fors

uncut zephyr
#

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?)

hushed galleon
#

yeah every time the command is run, you're creating new variables in that scope

cold sonnet
#

depends

#

where do you create the var

slate swan
#

if its empty yeah it would make an instance

#

if its in the method*

cold sonnet
scarlet rune
#

how do i make this list of available options on slash command?

uncut zephyr
#

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?😅

slate swan
#

if you're doing a guessing game or something along the lines yes you should, you can probably do it in just one method

cold sonnet
#

well, there's always a better way to do what you did

uncut zephyr
slate swan
#

programming is all about taking time and have patience

cold sonnet
#

don't seem right to me either

slate swan
#

every programmer should have patience i.e getting an error and not freaking out

cold sonnet
#

the import nextcord line already

hushed galleon
uncut zephyr
#

Thanks for your help guys. Not completely sure what to do now, but way smarter then before

cold sonnet
#

json for db?

jolly basalt
#

How do I make a bot join the vc Im currently on. I have all the intent stuff done

maiden fable
#

Okay so

#

I think I myself need some help understanding my totally-not-copied code

cold sonnet
jolly basalt
#

XD

cold sonnet
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

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").
jolly basalt
#

ty

maiden fable
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the 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.

maiden fable
#

Don't mind the spaghetti I am cooking

jolly basalt
#

but still, how to get the channel..... ctx.author.smth?

maiden fable
jolly basalt
#

sooo

maiden fable
#

!d discord.Member.voice

unkempt canyonBOT
maiden fable
#

await ctx.author.voice.channel.connect()

jolly basalt
#
@bot.command(name = 'join')
async def joinvc(ctx):
  vc = ctx.author.voice.channel
  await vc.connect()

is that right?

cold sonnet
#

not needed var

jolly basalt
#

ohk

maiden fable
#

@cold sonnet help meh

cold sonnet
#

lemme get on that computer real slow

maiden fable
#

No

#

Get REAL FAST

cold sonnet
#

no

maiden fable
#

Dude its just a simple question regarding interactions

#

@cold sonnet 🥺

cold sonnet
#

you lost me at the word spaghetti

#

now I'm on my pc

jolly basalt
maiden fable
slate swan
maiden fable
#

This no spaghetti

jolly basalt
cold sonnet
maiden fable
#

Hahaha

slate swan
cold sonnet
#

but where problem

jolly basalt
#

ok

maiden fable
#

Oh wait

#

Nvm, I am just being stupid

cold sonnet
#

hunter no ask help long time
hunter forget how ask

maiden fable
#

Got confused with InteractionResponse and InteractionResponseFollowup

#

or whatever its called 🤷

cold sonnet
#

dunno what those are

maiden fable
unkempt canyonBOT
#

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.
maiden fable
#

Nvm I get it now, thanks meh

cold sonnet
#

you're welcome

maiden fable
#

this is what happens when u open your bot's source after months

cold sonnet
#
                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
maiden fable
#

How tf do u expect me to use for loop here

cold sonnet
#

now wait a damn minute

maiden fable
cold sonnet
#
                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

maiden fable
#

Uhhhhh

cold sonnet
#

wait a minute

#

BRUH

maiden fable
#

Lmao

cold sonnet
#

I'm on the right path

maiden fable
#

Okay

desert badger
#
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
cold sonnet
#
        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

maiden fable
#

Mind rewriting my bot for me?

cold sonnet
#
                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
                )
cold sonnet
unkempt canyonBOT
#

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

cold sonnet
#

heheeee

maiden fable
#

Never said I am gonna pay u

cold sonnet
#

paid work of 0$

maiden fable
#

Gonna give u premium oxygen 😉

cold sonnet
#

outta your mouth?

#

hunter answer

#

hunter I know you're there

#

also

slate swan
#

yes

#

😳

cold sonnet
#
                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
maiden fable
cold sonnet
#

bro's gone again

maiden fable
#

No thanks, I will pass on that

cold sonnet
#

how unfortunate

#

then I don't want it

maiden fable
#

Anyways, its ot 🤷

cold sonnet
#

def not

slate swan
#

aka meAG_Angry 02lewd

maiden fable
#

Hm?

slate swan
desert badger
#

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: UnsupportedOperation: not readable help

#
    with open('uploads.json', "w") as f:
        data = json.load(f)
sick birch
#

You can't read from it without read perms

maiden fable
#

Yea, u gotta do r

sick birch
#

When you specify w it doesn't even load the contents into memory

sick birch
#

^w^

desert badger
#

ohhh sorry

#

thank

sick birch
#

np

paper sluice
#

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?

placid skiff
sacred blaze
#

hey guy can some help me with opencv puttext display ui

quick gust
#

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

placid skiff
#

WTF?

slate swan
#

then no

paper sluice
#

like i got 20 commands, i dont wanna be adding *args to each of them

slate swan
#

*args refers to a unknown amount of arguments which returns a tuple

desert badger
#

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 ""
buoyant quail
#

list

desert badger
buoyant quail
#

umm... {"test": ["1", "2", "3"]}

desert badger
#

and how do i make my bot save it like this? lol

slate swan
#

so the list has ints and not strings that are ints

hushed galleon
buoyant quail
desert badger
#

i want it to save strings

slate swan
#

fair point but im not sure if its still a correct way

desert badger
#

what i want to save is links lol

slate swan
#

ah

#

then yeah a list or tuples are fine

desert badger
#
        data[str(ctx.author.id)]['urls'] = [url]

``` does this work
#

thats what i want to do if there are no urls in it lol

desert badger
#

wait can i just send my code to someone to help me with it? :-:

slate swan
#

just use len

slate swan
#

!e print(len({1: 2}))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

1
desert badger
#

im confused can someone just look at my code

slate swan
#

havent you been given answers already?

buoyant quail
#

!e print(not {})

unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your eval job has completed with return code 0.

True
slate swan
buoyant quail
#

ik

slate swan
#

just saying to everyone lol

buoyant quail
#

ahh

desert badger
#
    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 "#"
slate swan
#

try it outok

desert badger
#

its not even finished bruh

#

look at updated urls

#

marked it with "#"

boreal ravine
desert badger
#

BRUH HOW IM CONFUSED BRO THATS WHY IM HERE

#

ahem caps lol

boreal ravine
buoyant quail
#

.append

#

do you know what is list xd?

desert badger
desert badger
buoyant quail
#

bruh

boreal ravine
#

.. what?

desert badger
#

u told me to use it again

desert heart
#
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.

desert badger
#
    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 ? :)
boreal ravine
#

No

buoyant quail
#

append changes list

boreal ravine
#

that will overrite the old key

buoyant quail
#

it returns None

desert badger
#
    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 ?

buoyant quail
#

and delete updated_urls =
and this too data[str(ctx.author.id)]['urls'] = updated_urls

desert heart
desert badger
#

help im confused :(

desert heart
#

append modifies the list in-place rather than returning a new one

desert badger
#

can someone edit my code? im really confused rn...

boreal ravine
#

how are you confused?

desert badger
sick birch
#

Where did you define data?

boreal ravine
#

why do you have ```py
data[str(ctx.author.id)]['urls'] = updated_urls

desert badger
#

sec i sent wrong code

buoyant quail
#
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

desert badger
#


    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)


sick birch
#

This is why I hate json, it turns into [] and str() hell

boreal ravine
desert badger
#

:(

sick birch
#

Perhaps consider using a database?

sick birch
#

!d discord.User.status

boreal ravine
#

!d discord.Member.status

unkempt canyonBOT
#

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.
desert badger
sick birch
#

How would it not work

boreal ravine
boreal ravine
buoyant quail
#

idk

#

i have learnt good by examples

desert badger
desert badger
buoyant quail
boreal ravine
desert badger
#

why does it save it 3 times lol

buoyant quail
desert badger
#


    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)



desert badger
buoyant quail
desert badger
#

oh i think i did something wrong

buoyant quail
#

url="another link"

#

idk where you store another urls to save