#discord-bots

1 messages Ā· Page 100 of 1

dull terrace
#

also that means i'd be making twice as many api calls right

wicked atlas
#

I don't think that would really hurt it

#

interaction endpoints don't contribute to the bot's global ratelimit

grand willow
#

Instead of having item.callback = removed how could I rewrite it to work since removed is a function and I need to add a positional argument that I cant if I would do item.callback = removed(itme_name)

#

not sure if anyone understands what I mean

faint sapphire
#

doing this
commands without args -> details ab the command
using on message, if the content == the command and nothing else
give details

problem is, on message is in the bot.listen
its prob that which doesnt allow it to work

#

yh works when i use bot.event instead of bot.listen
idk why it was recommended to use bot.listen

wicked atlas
#

Does it look like one of these?

#
@bot.listen()
async def on_message(msg):
      ...

# or

@bot.listen("on_message")
async def my_message_handler(msg):
    ...
hushed galleon
#

for example: py if isinstance(error, commands.MissingRequiredArgument): filtered_args = <ctx.args with Cog and/or Context removed> if filtered_args or ctx.kwargs: await ctx.send(<an error message>) else: await ctx.send_help(ctx.command)

high sedge
#

Hello

#

I have an issue, "discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead." I get this even though the servers member intent is enabled

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

sick birch
hushed galleon
#

what intents= did you pass to your bot constructor? you may have requested another intent that wasnt enabled

high sedge
#

I did though. I disabled and renabled it

#

#Intents are permissions for the bot that are enabled based on the features necessary to run the bot.
intents=discord.Intents.all()

#

I have it for all

wicked atlas
#

And they're all enabled in the dev portal too?

high sedge
#

I am fking blind af. I bybassed Message intent

#

Thank you guys

#

I am tired lmao!

fresh ferry
#

any help would be great, i paid for a discord source and theres these errors so im having to dive deep and figure out how to fix these as dev blocked me

slate swan
fresh ferry
slate swan
#

sure

torn sail
slate swan
primal token
# slate swan what i thought...

No offense, but you thought about it and you asked the user to send you the command when it was an issue related to indentation, dont you think thats a waste of your time?

slate swan
#

...

primal token
primal token
primal token
robust fulcrum
slate swan
#

dont use termux lol

robust fulcrum
#

The replit is more annoying than termux

slate swan
#

Hey!

I have a command that looks like

if not owner(ctx):
  <error>

But i want it so if they arnt owner or developer it returns the error

vocal snow
#

returns an error? Or raises an error

slate swan
vocal snow
#

So... A string?

slate swan
slate swan
slate swan
#

would i put :

if not owner(ctx) or developer(ctx):
  return <message>
#

yea

drifting arrow
#

Discord has an auto-afk channel right for when someone doesnt speak after x time correct?

smoky cedar
#

can someone help.? im trying to make clear msg command

torn sail
keen lark
#

Oh i didn't see this channel.

Hi, I'm making a bot to remember my favorite game bot, I would like to know if there was any way to cancel a reminder using await asyncio.sleep(900 * donor), i want cancel it (after set it, ofc) to make another one found a soluction!

smoky cedar
#

?

#

nvm thanks it works now

frail sedge
#

!doptions

#

!discord options

maiden fable
#

?

obtuse heron
#

how save message in json

storm tangle
#

Hello, my bot just reached 78 guilds with 25k+ users.
Last time my bot denied because of having a copyright music system and a snipe command which were against ToS.
Currently i have the following commands in my new bot:
connect4, lisapresent, meme, snake, ttt, ban, kick, purge, role, unban, autorole, counter, embed, starboard, status_role, ticket, welcome, avatar, gunsmith, help, ping, poll, reportbug, serverinfo, translate, updates, userinfo
Does any of the command are against ToS or can do issues in the process of verification?
Please do tell me about this because i don't wanna get the verification denied this time.

slate swan
#

can i send someone my code? Cuz i needsomeone to fix it

hazy oxide
#

what's the problem?

naive briar
#

I saw that 🄓

rare echo
#

i found a direct link for it

#

but if you view any server as an @ everyone role then it shows up

slate swan
#

Is there any way to be able to tag multiple members with slash commands?
Example: /ban @member1 @member2 reason

slate swan
#

multiple options

shrewd apex
#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
naive briar
shrewd apex
#

not sure

marsh cedar
#

Can we make and verify it?

naive briar
#

I don't understand your question

marsh cedar
#

Ok

#

Will discord verify?

#

My bot in py

shrewd apex
marsh cedar
#

Becoz some kept on YouTube discord.py dead and waste

#

So came to clarify

naive briar
shrewd apex
naive briar
marsh cedar
#

I am not saying

slate swan
# marsh cedar I am not saying

those videos are hella outdated and the creators don't pay attention enough to update them.
discord.py was dead for a while but its back now. many verified big bots are already using it

#

so it won't be an issue with verification

slate swan
#

already tried

#

but thanks

slate swan
#

!d discord.app_commands.Transformer

unkempt canyonBOT
#

class discord.app_commands.Transformer```
The base class that allows a type annotation in an application command parameter to map into a [`AppCommandOptionType`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType "discord.AppCommandOptionType") and transform the raw value into one from this type.

This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the [`Transform`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transform "discord.app_commands.Transform") class. For example, to convert a string into a custom pair type:
slate swan
#

make ur own convertor

primal token
primal token
shrewd apex
primal token
#

šŸ

faint sapphire
pulsar solstice
#
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Public Bot\main.py", line 453, in bankdataprivate
    json.dump(users, f)
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 180, in dump
    fp.write(chunk)
ValueError: I/O operation on closed file.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: I/O operation on closed file.```
#

what does this error mean?

wicked atlas
gaunt ice
#

whats the issue

fresh ferry
#

hey everyone, I'm trying to create a bot that the user can add to a server but i want them to register themselves with the bot with there profile so it keeps a record like "coins" for example so if they use it on any other server that has the bot it shows their balance, kinda like an Economy bot

any help would be great and much appreciated

gaunt ice
#

u can maintain a database

#

with the users unique id

fresh ferry
gaunt ice
#

np

pulsar solstice
#

what does this error mean?

#
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Public Bot\main.py", line 453, in bankdataprivate
    new_users = f[str(ctx.author.id)]["status"] = "no"
TypeError: '_io.TextIOWrapper' object is not subscriptable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '_io.TextIOWrapper' object is not subscriptable```
naive briar
pulsar solstice
#


@bot.command()
async def bankdataprivate(ctx):
    with open("bank_privacy.json", 'r') as f:
        users = json.load(f)
    await add_priv_status(ctx.author)
    status_current = users[str(ctx.author.id)]["status"]
    if status_current == "no":
        await ctx.reply("Your Bank data is already set to private.")
    else:
        with open("bank_privacy.json", 'w') as f:
            new_users = f[str(ctx.author.id)]["status"] = "no"
            json.dump(new_users, f)
            await ctx.reply("Your bank bal was set to private.")```
#

I did read it

wicked atlas
#

That one looks like you’re trying to access a key of a dict, but it’s a file object or something

#

This is different code than the error shows

pulsar solstice
#

no*

naive briar
primal token
#

!pypi aiofiles

unkempt canyonBOT
fresh ferry
#

is it possible to run a discord bot using visual studio code using my internet to test bot ??

wicked atlas
# pulsar solstice mo

Let me be more specific, the line the error says it’s happening on is different than the line in the code you just sent

primal token
fresh ferry
pulsar solstice
primal token
wicked atlas
pulsar solstice
#

even the dir gets removed

#

like everytime it's a blank file

naive briar
#

I

pulsar solstice
#

...

#

???

primal token
#

So i agree with you, it has given me allot of trouble

fading marlin
naive briar
fresh ferry
primal token
inner wing
naive briar
#

It was really an easy solution after all

indigo pilot
#

Ive only really done something like this with dropdown menus, where thats just a list, but idk about this

#

but whta would i even define to put code in it lmao

#

my brain

slate swan
#

Installed python from website how do I set it as the interpreter?

indigo pilot
#

lmao

faint sapphire
#

for some reason errors come up twice
it does that for several commands, and I dont have 2 functions with the same name

tepid dagger
#

is there an updated place to find functions for the api?

#

can't seem to find anything

tepid dagger
#

!d

unkempt canyonBOT
tepid dagger
#

im confused lol

#

what do these mean

#

nvm

faint sapphire
tepid dagger
#

tysm

hushed galleon
faint sapphire
#

i commented them out

hushed galleon
#

also filtered_args just has to ignore the first one or two elements because thats the Cog and/or Context instances that are being given to your command

faint sapphire
#

i think i see thanks

#

damn my computer is clapped

#

its running everything twice XD

mental hollow
#

I keep getting this error when attempting to fetch a message.. anyone know why?

Ignoring exception in command ds:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 184, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/cogs/suggestions.py", line 45, in ds
    m = await s.fetch_message(MessageID)
  File "/home/container/.local/lib/python3.9/site-packages/discord/abc.py", line 1597, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "/home/container/.local/lib/python3.9/site-packages/discord/http.py", line 359, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "<discord.ext.commands.context.Context object at 0x7f78c0b29100>" is not snowflake.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 342, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 951, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 193, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "<discord.ext.commands.context.Context object at 0x7f78c0b29100>" is not snowflake.
naive briar
mental hollow
#

I passed a message ID, that was it

#

as per docs said

naive briar
#

The error says otherwise pithink

mental hollow
#

I have a MessageID argument

#

in my deny suggestion (ds)

#

which is the first arg, then I have a status arg

#

I’ll post the code here, one second

primal token
#

You're missing an extra argument for the message id

naive briar
#

The first argument of text commands is always context

mental hollow
#

ah

primal token
naive briar
primal token
#

You should also be using snake_case for local variables

mental hollow
#

Wait so I use async def(self, ctx, MessageID: int, *, status: str) ?

primal token
#

message_id is more suiting

mental hollow
#

async def(self, ctx, message_id: int, *, status: str) ?

inner wing
#

what the limit of button rows can be?

primal token
primal token
inner wing
#

so the total can be 25?

#

5x5?

mental hollow
primal token
#

wasnt the max like 27? probably not because it would be uneven

mental hollow
#

always was told it’s 25

mental hollow
#

this says I need a embed object

#

so how do I get my embed object (which was already sent) with message ID

primal token
#

!d discord.Message.embeds

unkempt canyonBOT
naive briar
#

That was fast

primal token
#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is ā€œsyntheticā€ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

mental hollow
primal token
#

it can return an empty list

mental hollow
#

it shouldn’t since my suggest command will always send an embed

#

and only an embed

primal token
#

Well, then no need!

mental hollow
#

thanks, I’ll try it now :)

primal token
#

šŸ‘

mental hollow
#

now I’m not getting any error but my bot does nothing when I run the command..

faint sapphire
indigo pilot
indigo pilot
#

!evel

#

!eval dict = {}
dict.append("test": {"hello": lol})

#

!eval dict = {}
dict.append({"test": {"hello": lol}})

#

i give up

#

#bot-commands

faint sapphire
#

yall know the bot ticket tools?
it has a transcript command

to do something similar do I have to use the discord website and copy paste the hmtl to a webpage?

slate swan
#

or you put it outside of init

#

so you might want to put it inside

indigo pilot
indigo pilot
robust fulcrum
#
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/client.py", line 627, in connect
    await self.ws.poll_event()
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

Guys i have literally for this error more than 50+ times
Can anyone tell how to fix
Don't say me to use any other app
I am using termux

indigo pilot
#

u need a webserver

lilac oriole
#

is this code correct??

hushed galleon
obtuse heron
#

how using discord.message.Message()?

hushed galleon
#

if you go with the same approach of using attachments, the webserver is only necessary if you have certain assets you need to include that arent embedded inside the html itself, e.g. css/javascript, although i guess maybe sourcing from a github repository would work

hushed galleon
obtuse heron
#

ол

#

I want to made message with using dickt

faint sapphire
hushed galleon
#

nah not uploading the message history to github

#

you can generate an html page from the history and use a content provider to host the css/javascript files separate from the html if you need to

faint sapphire
#

generate a page without using anything to host it
and use who to host the java/ccs?

hushed galleon
#

@obtuse heron well, creation of Message objects is part of discord.py's internals so they dont really support it

#

do you actually need a full-fledged message object, or do you need an object with certain attributes so it'll work as a replacement for a function that needs a message? or do you want to edit one of your bot's messages without fetching that message from the API?

hushed galleon
faint sapphire
#

ight np, thanks for the ideas

outer lotus
#

please guys help me how to fix

shut tendon
#

did you try installing as admin those libraries? python3 -m pip install name-libra

mental hollow
#
if not ctx.author.guild_permissions.manage_messages:
    return await ctx.message.delete()
else:
    #Code

The author doesn’t have manage messages permissions so why isn’t my bot deleting their message? Rather, my bot returns an error from the #Code part when the command is executed from a user who doesn’t have permissions.

#

How are we supposed to help with no code?

#

You’re self botting?

naive briar
#

It's against Discord's ToS

mental hollow
#

It’s against TOS.

#

So.. you’re willingly doing it?

naive briar
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

mental hollow
#

!rule 2

unkempt canyonBOT
primal token
#

Interesting how you dont care about this platforms TOS but you agreed to themšŸ¤”

tacit prairie
#

Anyway forgot it

mental hollow
mental hollow
# naive briar What's the error?

Well in my #code, I fetch a message; and one of my arguments is a message ID, so I get an error that the user is missing a required argument.

dull terrace
#

Have you tried printing ctx.author.guild_permissions.manage_messages ?

naive briar
mental hollow
mental hollow
dull terrace
#

Okay well if you print it and it returns True, then you know it's the wrong person it's doing it for or something else

mental hollow
naive briar
#

I don't understand what could go wrong

mental hollow
#

me either!

mental hollow
#

I just got the error again

naive briar
#

Show the error message

dull terrace
#

it printed None?

#

or it caused the error?

sick birch
mental hollow
mental hollow
mental hollow
# naive briar Show the error message
Ignoring exception in command ds:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 342, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 943, in invoke
    await self.prepare(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 873, in prepare
    await self._parse_arguments(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 779, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 612, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: message_id is a required argument that is missing.
tawdry perch
#

If I want to create x amount of buttons, depending on amount of items in list. How would I do that? Normally to create a button I would do this ```py
class MyButton(disnake.ui.View):
def init(self):
super().init(timeout=None)

@disnake.ui.button(label="nice label", style=ButtonStyle.red)
async def first_button(
    self, button: disnake.ui.Button, inter: disnake.MessageInteraction
):
    inter.response.send_message("cool message")
Every button would have the same kind of syntax, except for at least these 2`label (being a item from list)`, `style (randomly picked)`
sick birch
tawdry perch
#

I don't how to do the dynamic part, do you know the location of add_item docs?

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

This function returns the class instance to allow for fluent-style chaining.
tawdry perch
#

I think I got an idea

#

thank you! I got it working

dull terrace
#

Had an interesting idea but it's a lot of work

#

Top.gg let's you embed your website on your bots page, so I could make a few different things, randomly serve one and have my own invite bot button on the page

#

Then I can track which one performs the best and use that froggy_chill

#

I mean in theory even a 5% increase of invites over time would be worth the time investment assuming my bot gets big enough or is around long enough right 7739monkathink

honest shoal
dull terrace
#

I googled traffic and top.gg seems by far the biggest

honest shoal
#

I don't have any public bot, top.gg indirectly brings ads on discord

dull terrace
#

Not really... Just don't vote for bots if it bothers you

honest shoal
#

there are vote locks on commands

#

even some in-game currency can only be accessed by it

#

basically an ad wall to use commands

slate swan
#

better than paid bots imo

#

top.gg also doesn't forces it, its just the developers who do that for votes

rare echo
slate swan
#

i find opening a link and clicking a button eaiser
don't do much stuff with bots anyways

honest shoal
rare echo
slate swan
#

the only thing i can imagine is some bots.using music featurs, but fkit Spotify exists

honest shoal
#

they don't get anything from ads but a place for their bot in special section

#

upcoming app directory will tackle this shit' out

slate swan
#

prob sure it will have requirements

#

discord made a servers directory recently limited to some servers and it can be revoked anytime

dull terrace
honest shoal
dull terrace
#

At some point you want developers to get some benefits from making apps on your site

#

I'm fine with top.gg getting ad revenue considering the service they provide

honest shoal
#

Then it's about different opinions ĀÆ_(惄)_/ĀÆ

#

in my opinion top.gg has many cons, "pay to get" something is actually bad

tough lance
#

how can i add two fields per line in embed instead of three?

honest shoal
#

F means field

grand willow
#

Can someone tell me whats wrong?
Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'

ok = timedelta(days=time)
await user.timeout(until=ok,reason=reason)
winged coral
#

It explains pretty well

#

You're using a kwarg when it's positional only

grand willow
#

Oh

grand willow
sick birch
grand willow
grand willow
sick birch
#

Remove until=

#

That makes it positional

grand willow
#

oh

#

thanks

sick birch
#

np

unkempt canyonBOT
pulsar bridge
#

It's been ageeessss, how've you beeen?

sick birch
pulsar bridge
#

I don't blame you, haven't been here in ages

primal token
pulsar bridge
#

I remember a noid, last time I was here

#

ah yes

primal token
#

anyway, how are you doing nexus? I hope you have stopped with the usage of semi-colons in python

pulsar bridge
#

I've been pretty good, a bit busy though, you?
And yes, I've corrected my sinful habits PI_Holy

primal token
#

Sorry if i didnt remember you, i just dont really remember users as it's not like they would remember me kek

pulsar bridge
#

Ah, don't pay a second thought to it

primal token
pulsar bridge
#

Y'all are busy, remembering everyone who pops in is impossible

#

Unless you've got a fully functioning database inside your head eyes_sus

primal token
#

Yeah i have a JSON db with blockingio that's why I'm mentally slow

pulsar bridge
#

lol

#

Speaking of databases

#

Anyway, got an issue with dry brain juice and can't fix this issue, so I came here

food_sweet_list = [
    "Muffin",
    "Donut",
    "Bar Chocolate",
]
...
     query_one = { "user_id": message.author.id }
...
            if (food_drink_col.count_documents(query_one) == 0):
        add_food_and_drink = {'user_id': message.author.id, 'user_name': message.author.name}
        food_drink_col.insert_one(add_food_and_drink)
        existing_user = food_drink_col.find(query_one)
        original_query = { "user_id": message.author.id }
        for result in exisitng_user:
            for x in food_sweet_list:
                print(x)
                new_query = { "$set": { (str(x)): int(0)} }
                food_drink_col.update_many(original_query, new_query)

#

The issue is that it ain't adding x into the collection

#

The issue is in the for loop, I think

#

Wait, I should add more code

primal token
#

you misspelled existing_user with exisitng_user

pulsar bridge
#

you're kidding, aren't you..?

primal token
#

Wish i was

pulsar bridge
#

shhh, Cat_Shhh

primal token
pulsar bridge
#

;-;
Aight thanks for that
I should probably get more sleep MeguDed

primal token
#

Was that really your issue?pithink

slate swan
#

if someone presses my button, i want it to click a link so its like a authroize bot link

primal token
primal token
#

!d discord.ui.Button.url

unkempt canyonBOT
slate swan
#

@discord.ui.button(label="Press me AFTER verification!", style=discord.ButtonStyle.primary, emoji="āœ”ļø", url={url})

unkempt canyonBOT
#

examples/views/link.py line 33

self.add_item(discord.ui.Button(label='Click Here', url=url))```
sick birch
primal token
#

!d discord.ui.button | this doesnt have a url kwarg

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
primal token
#

!d disnake.ui.button

unkempt canyonBOT
#

disnake.ui.button(cls=disnake.ui.Button, *, style=ButtonStyle.secondary, label=None, disabled=False, custom_id=..., url=None, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`disnake.ui.View`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.View "disnake.ui.View"), the [`disnake.ui.Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") being pressed and the [`disnake.MessageInteraction`](https://docs.disnake.dev/en/latest/api.html#disnake.MessageInteraction "disnake.MessageInteraction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
primal token
#

disnake has it though

slate swan
#

could you show me a code example on how to add it

torn sail
slate swan
#

@discord.ui.button(label="Press me AFTER verification!", style=discord.ButtonStyle.primary, emoji="āœ”ļø")
async def button_callback(self, button, interaction):

#

where would i add that

torn sail
#

Oh I was just saying why it has no url kwarg

primal token
#

šŸ˜…

torn sail
#

I wonder why disnake has that kwarg tho

primal token
#

Seems a bit useless

torn sail
#

Yeah

slate swan
slate swan
torn sail
austere vale
#

does anyone know how to create code to have your discord bot detect when your twitch channel is live and then send out a message?

drifting arrow
#

So

#

So my server just got access to the new forums thing

#

Is there any way to limit peoples view to each forum post?

wary shadow
austere vale
wary shadow
#

hmm, this has changed. Where is the channel data hidden now pithink

austere vale
#

thank you!

primal token
wary shadow
#

It has an entire pubsub system you can tie into. A passive check is significantly easier to stand up for a simple "is it live" check.

#

imo

#

The streams endpoints should be public too so you can even bypass all the noise of authentication. pithink

primal token
wary shadow
#

if the question was "how do I hook a discord bot into the event stream of Twitch so that I can capture all of the events such as go-live, bits, cheers, supers, drops, and whatever else exists" then sure, I'm misleading. darkoLUL

wary shadow
# primal token pubsub? Havent heard of that word before

Webhook delivery with a publisher-subscriber pattern. PubSub. Discord uses this pattern afaik. A client logs in, subscribing to events, and remains subscribed until it stops responding at which point discord unsubscribes it. (this is why your bot can "hang" online a few minutes after you kill the process)

primal token
#

Seems like a gateway with webhooks kek

wary shadow
#

It is, but with more control for the host.

pliant gulch
#

It is very safe to say that discord uses pub-sub pattern, I mean just look at how api wrappers implement it.

#

Also since discord uses elixir in their stack for websockets we can also pretty much safely assume it's pub-sub without knowing the architecture 100%

primal token
#

Ill look into the pattern

sick birch
pulsar bridge
#

back again
So I've learned how to manipulate external files to a certain extent, but I have a few questions:
Lets say I have my main .py file and an external .txt file,
The .txt file is made up of a ton of separate paragraphs

  1. Is there a way to add "tags" to the different paragraphs?
  2. Is there a way to randomly pick one of the paragraphs?
  3. Is there a way to randomly pick one of the paragraphs based off user input compared against the tags? Like if I inputted the word "grey" it would only randomly select from the paragraphs with the "Grey" tag
upbeat gust
pulsar bridge
#

darn

upbeat gust
#

you probably could, but it would be really jank

pulsar bridge
#

Aight, I'll keep experimenting, but if it doesn't work I'll use a db

#

thanks AE_Violet_salute

upbeat gust
pulsar bridge
#

I'm the kind of person who'll try and try at this sort of stuff, My curiosity outruns my common sense MeguDed

warm lava
#

which db is the best for discord

upbeat gust
warm lava
upbeat gust
#

sqlite (the lib) is blocking, aiosqlite is an async version

warm lava
#

aiosqlite has minimal documentation

upbeat gust
#

because its basically sqlite, just async

warm lava
#

it's killing me

upbeat gust
#

you can just use sqlite's docs

warm lava
#

import šŸ—æ
from šŸ—æ import šŸ—æ

šŸ—æ = "šŸ—æ"

print(šŸ—æ)
vale wing
slate swan
robust fulcrum
#

Guys is there any other way of hosting our discord bot on our device other than termux?

winged coral
#

šŸ˜ž

maiden fable
warm lava
#

that would be cool tho

slate swan
#

I have 2 events with on_member_join and only one of them works how do i fix it?

#

Any guide on how to add tagscript to your bot?

winged coral
slate swan
winged coral
#

Yeah don't do that

slate swan
#

Then what do i do

winged coral
#

One is overriding the other

slate swan
#

oh

winged coral
#

Set the name kwarg

#

In bot.event

slate swan
#

i dont really understand

#

like @bot.event **kwarg

winged coral
#

No

#

Set the kwarg called name

#

To the name of the event

slate swan
#

the event is on member join

winged coral
#

Yes

#

So set it to that

slate swan
#

like

#

@bot.event
async def on_member_join(member, **kwarg):

#

You can use listeners

#

how

vale wing
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
naive briar
#

😿

vale wing
#

J

slate swan
#

but how do i do it w the bot

naive briar
#

Change @bot.event to @bot.listen("event_name")

vale wing
#

Event name isn't necessary if the function is named as event

naive briar
#

They just don't override each other if they have different function name

slate swan
upbeat gust
upbeat gust
slate swan
#

but will it work?

upbeat gust
slate swan
#

@upbeat gust its not workinf

upbeat gust
slate swan
# upbeat gust show what you did, and define "not working"

@bot.listen("memberjoin")
async def memberjoin(member):
channel = bot.get_channel(1026080365825237002)
embed = discord.Embed(title=f"{member.name} Joined The Server!", description=f"We Have Now {len(member.guild.members)} Members! \n {member.mention}", timestamp=datetime.now() , color=0xa9e8cd)
await channel.send(embed=embed)

#

it isnt sending only the other one

upbeat gust
#

why did you change the event name? We all said function name

slate swan
#

oh

#

on_member_join thats the fuction

upbeat gust
#

The function name can be whatever you want

slate swan
#

where do i put the function

upbeat gust
#

???

#

@bot.listen takes an event name

#

it decorates a function that you define

slate swan
#

OHH

#

@bot.listen("memberjoin")
async def on_member_join(member):
channel = bot.get_channel(1026080365825237002)
embed = discord.Embed(title=f"{member.name} Joined The Server!", description=f"We Have Now {len(member.guild.members)} Members! \n {member.mention}", timestamp=datetime.now() , color=0xa9e8cd)
await channel.send(embed=embed)

#

like that??

upbeat gust
#

BLUE matters
RED does not

#

You have it the wrong way around

slate swan
#

oh i understand

#

@bot.listen("on_member_join")
async def memberjoin(member):
channel = bot.get_channel(1026080365825237002)
embed = discord.Embed(title=f"{member.name} Joined The Server!", description=f"We Have Now {len(member.guild.members)} Members! \n {member.mention}", timestamp=datetime.now() , color=0xa9e8cd)
await channel.send(embed=embed)

upbeat gust
#

Name the FUNCTION whatever you want

slate swan
#

is that it?

upbeat gust
#

Put the right EVENT inside LISTEN

upbeat gust
slate swan
#

i will try! thankss

#

WORKS!

#

Thank you so mucchhhhh

vale wing
#

To be more correct

upbeat gust
robust fulcrum
#
    @app_commands.command(name="buy",description="buy an item from the shop!")
    @app_commands.describe(item="id of the item to buy")
    @app_commands.autocomplete(item=item_complete)
    async def _buy(self,interaction: discord.Interaction, item: str):
        user = interaction.user
        checking = await self.check(user.id)
        if checking == False:
            await interaction.response.send_message("Ah! The user has not started the game yet.\nFor what are you waiting! suggest him/her now.")
        else:
            wal = await self.bot.wallet.read(interaction.user.id)
            if item == "#01":
                if wal.money >= 30:
                    itemcheck = await self.bot.items.read(interaction.user.id,"healing potion")
                    if itemcheck:
                        await self.bot.items.updatequantity(interaction.user.id,"healing potion",itemcheck.quantity+1)
                    else:
                        await self.bot.items.create(interaction.user.id,"healing potion")
                    await interaction.response.send_message(embed=Embed(title=interaction.user, description=f"successfully buyed {self.emo.get('healing potion')}healing potion!"))
                else:
                    await interaction.response.send_message(embed=Embed(title=interaction.user, description="you don't have enough money to buy it!"))
            else:
                await interaction.response.send_message(embed=Embed(title=interaction.user, description="This item is not available yet!"))

Guys i have made this buy command in my bot
But it's adding 2 items instead of adding 1 item
Can anyone help me how to fix or i did something wrong

slate swan
#

how do i do that if the member doesnt have a pfp it will still send the embed?

naive briar
unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
slate swan
#

like that?

naive briar
#

Yes

slate swan
#

okay i will try thanks

#

works thanks!

fresh ferry
#

can someone help me look over my code, visual studio code isnt telling me whats the problem no errors and wont run the bot for a test ???

unkempt canyonBOT
#

Hey @fresh ferry!

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

slate swan
#

guys guys

#

!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.

slate swan
#

plz help me to fix this

#

error: bot.warnings[guild.id] = {warnings}
AttributeError: 'Bot' object has no attribute 'warnings'

#

tbh I copied from github but can't make it work

#

what are you trying to do'

#

there are a lot tuts from youtube

#

@slate swan also bot.run("TOKEN")

naive briar
slate swan
fresh ferry
slate swan
#

do you think I would send the bots token in here?

slate swan
slate swan
fresh ferry
fresh ferry
slate swan
slate swan
slate swan
slate swan
#

??

naive briar
#

It did not

slate swan
#

but I created a file called warnings

naive briar
#

Just creating a file doesn't do anything. You have to either define it by subclassing the bot or define it by setting it

fresh ferry
slate swan
slate swan
#

I'll just try coding my own

fresh ferry
#

i know it pretty much says the answer for me but when i remove the double instances it brings up multiple errors lol ??

fresh ferry
unkempt canyonBOT
#

Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

fresh ferry
upbeat gust
#

dont use json as a db

#

the error is pretty self explanatory anyway, that user isnt in your stored levels

#

but you are using it as a db

slate swan
#

error:

  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 395, in on_message
    async with bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'```

code:
```py

@bot.event
async def on_ready():
    print(f"{bot.user.name} is online!")
    try:
      synced = await bot.tree.sync()
      print(f"Synced {len(synced)} command(s)")
    except Exception as e:
      print (e)
    setattr(bot, "db", await aiosqlite.connect("level.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")


@bot.event
async def on_message(message):
    if message.author.bot:
      return
    author = message.author
    guild = message.guild
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
        xp = await cursor.fetchone()
        await cursor.execute("SELECT level FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
        level = await cursor.fetchone()

        if not xp or not level:
            await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
            await bot.commit()

        try:
            xp = xp[0]
            level = level[0]
        except TypeError:
          xp = 0
          level = 0

        if level < 5:
           xp  += random.randint(1, 3)
           await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
        else:
             rand = random.randint(1, (level//4))
             if rand == 1:
                 xp += random.randint(1, 3)
                 await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
        if xp >= 100:
            level += 1
            await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
            await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
            await message.channel.send(f"{author.mention} Nice Job! You Have Leveled Up To Level **{level}** ! ![StreetGameAnimatedFire](https://cdn.discordapp.com/emojis/1010539069568204883.webp?size=128 "StreetGameAnimatedFire") ")
    await bot.db.commit()

@bot.command(aliases=['level', 'Rank'])
async def rank(ctx, member: discord.Member = None):
    if member is None:
        member = ctx.author
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (member.id, ctx.guild.id,))
        xp = await cursor.fetchone()
        await cursor.execute("SELECT level FROM levels WHERE user = ? AND guild = ?", (member.id, ctx.guild.id,))
        level = await cursor.fetchone()

        if not xp or not level:
            await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, member.id, ctx.guild.id,))
            await bot.commit()

        try:
            xp = xp[0]
            level = level[0]
        except TypeError:
          xp = 0
          level = 0
        
        em = discord.Embed(title=f"{member.name}s Level!", description=f"Level: {level}\nXP: {xp}", color=discord.Color.blue())
        await ctx.send(embed=em)

also i have a file called levels.db

slate swan
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
slate swan
#

@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")

#

like

naive briar
#

It's just an event (on_ready)

naive briar
#

Just run it normally

slate swan
upbeat gust
#

just do bot.db = ...

slate swan
#

withor cursor?

upbeat gust
#

you need to create bot.db first- why are you concerned about the cursor

#

and yes, do it in setup_hook

slate swan
#

on_message can also get triggered before on_ready ( or even multiple times )
thats why you should be using setup_hook

#

i did

#

now it says

#

[2022-10-05 11:27:30] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 403, in on_message
await bot.commit()
AttributeError: 'Bot' object has no attribute 'commit'

upbeat gust
#

what is bot.commit supposed to do

slate swan
#

like'

#

bot.db.commit
not bot.commit

#

OH

#

i will try

#

it will work, tutorials suck anyways
try reading docs and learning urself instead

#

i will try

#

but there are no errors

upbeat gust
#

missing process_commands in your on_message

slate swan
#

change the event decorator on on_messafe to .listen()

slate swan
#

i will try

#

works!

#

thank you all SO SO SO much!

upbeat gust
#

holy

#

im not gonna bother with this json crap
whats the problem here anyway

#

try it and see lol

#

what if this user has never sent a message before?

#

meaning it isnt inside the users dict/json

#

what part dont you understand

#

what do you think happens when you do "?level @upbeat gust"

#

the bot doesnt know what my level is because it doesnt even know me

#

im not inside the users dict

#

thats already what it does-

#

do you even know what your own code does

#

well what if that person has never sent a message?

#

they wont be inside users

#

you need to check if that person is inside users before trying to get their level

#

this has nothing to do with json

#

its a python dictionary

#

so are levels being added to the json when you send messages?

#

then why does it look like this??

#

then how do you know levels are being added?

#

??

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
#

the error:

[2022-10-05 12:06:00] [ERROR   ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 471, in rank
    background.test((200, 40), user_data["name"], font=poppins, color="#FFFFFF")
AttributeError: 'Editor' object has no attribute 'test'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 202, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Editor' object has no attribute 'test'

the code-
https://paste.pythondiscord.com/beyiritopo

naive briar
#

What could that be huh ducky_beer

slate swan
#

OHHH

#

THANKS

#

i did test instead of text lol

#

how do i make it to an ellipse?

dull terrace
#

The rainbow glow is blinding

pulsar solstice
#
TypeError: 'str' object does not support item assignment

what does this error have do with this code:

async def add_priv_status(user):
    members = await get_priv_data()

    if str(user.id) in users:
        return False
    else:
        members[str(user.id)] = {}
        members[str(user.id)]["node"] = 9

    with open("data_privacy.json", 'w') as f:
        json.dump(users, f)
#

???

naive briar
#

No offense, but I don't think those are the lines that caused an error

#

Wait nvm

slate swan
dull terrace
#

You assigned a string to member

slate swan
#

the square

dull terrace
#

Then you tried to assign an item to it

pulsar solstice
naive briar
slate swan
#

how do i make it a circle

dull terrace
#

That's literally what the error means

pulsar solstice
dull terrace
pulsar solstice
slate swan
#

like that

slate swan
naive briar
slate swan
#

easy_pil

pulsar solstice
#

simple

dull terrace
#

Idk what you're trying to accomplish, sending that as an attachment?

pulsar solstice
#

shit

naive briar
#

Good explanation

pulsar solstice
#

no

slate swan
#

Like

naive briar
#

I could totally understand

slate swan
#

Now it sends ot that way That you can see that its a square

#

and i want it to be like that an ellipse

pulsar solstice
dull terrace
#

Why would you have to do that with pillow?

#

Save the background image and then just draw the slider ontop before you send it

slate swan
#

pillow?

#

but vsc did that

dull terrace
#

You said you're using easy_pil which I assume is some weird version of pillow

slate swan
#

not me

#

vsc did that image

naive briar
pulsar solstice
#

as members

dull terrace
pulsar solstice
#

here it is

upbeat gust
slate swan
#

!paste

upbeat gust
#

Vsc is a code editor

slate swan
#

thats the code

upbeat gust
#

This has nothing to do with discord

slate swan
#

i didnt upload any media

upbeat gust
#

No one said you did

slate swan
#

oh

dull terrace
#

With an s

naive briar
#

That wouldn't make any difference

#

And it's for converting strings to dictionaries

robust fulcrum
#

Guys is there any way if running discord bot on mobile 24/7 other than termux?

dull terrace
#

when it should be a dictionary

fresh ferry
#

how do i open a help channel ?? i remember doing it ages ago but cant remember ?

cold sonnet
#

people would ask literally anything here

slate swan
#

!paste

#

the code

@bot.event
async def setup_hook():
    print(f"{bot.user.name} is online!")
    try:
      synced = await bot.tree.sync()
      print(f"Synced {len(synced)} command(s)")
    except Exception as e:
      print (e)
    setattr(bot, "db", await aiosqlite.connect("level.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")

@bot.group()
async def slvl(ctx):
    return

@slvl.command(aliases=["e", "en"])
@commands.has_permissions(administrator=True)
async def enable(ctx):
    async with bot.db.cursor() as cursor:
         await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id))
         levelsys = await cursor.fetchone()
         if levelsys:
            if levelsys[0]:
               return await ctx.send('The Leveling System Is Already Enabled!')
            await cursor.execute("UPDATE levelSettings SET levelsys = ? WHEER guild = ?", (True, ctx.guild.id,))
         else:
             await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?", (True, 0, 0, ctx.guild.id,))
         await ctx.send("Enabled The Leveling System!")
    await bot.db.commit()


@slvl.command(aliases=["d", "di"])
@commands.has_permissions(administrator=True)
async def disable(ctx):
    async with bot.db.cursor() as cursor:
         await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id))
         levelsys = await cursor.fetchone()
         if levelsys:
            if levelsys[0]:
               return await ctx.send('The Leveling System Is Already Disabled!')
            await cursor.execute("UPDATE levelSettings SET levelsys = ? WHEER guild = ?", (False, ctx.guild.id,))
         else:
             await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?", (False, 0, 0, ctx.guild.id,))
         await ctx.send("Disabled The Leveling System!")
    await bot.db.commit()

the error:

https://paste.pythondiscord.com/arokucewab

upbeat gust
#

are you gonna constantly keep your phone awake and connected to the internet

#

please dont suggest replit

slate swan
#

oh okay

dull terrace
upbeat gust
#

this needs to be a tuple

dull terrace
#

ā«

upbeat gust
#

add the , after ctx.guild.id like you have on every other query

slate swan
#

ohhh i forgot!

#

thank you both !

meager chasm
#

Dey wernt talking to u

fresh ferry
slate swan
upbeat gust
#

you shouldnt be using requests anyway, its blocking
use aiohttp

slate swan
upbeat gust
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)

discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author'])```


For more help, see aiohttp's documentation: http://aiohttp.readthedocs.io/en/stable/
slate swan
#

Like this?

upbeat gust
#

that and in your code

slate swan
#

Where at I’ll send my code in dms

upbeat gust
#

use it instead of the requests library

slate swan
#

Idk anything about coding I just got it off github

#

why is it sending twice? i did the code only once

slate swan
upbeat gust
#

yeah im not fixing it for you

#

you can do that yourself

upbeat gust
slate swan
#

I’ll pay ya if needed

#

Bro I need this done

upbeat gust
#

🤨

slate swan
#

?

#

Drop me your Cashapp

naive briar
unkempt canyonBOT
#

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

slate swan
#

Bro he won’t even help me

upbeat gust
#

ive given you all relevant info and further suggestions, wdym 'wont even help'

slate swan
#

Dude I’m asking where I put it in the fucking code

#

I got it off github

naive briar
upbeat gust
slate swan
#

Where’s that at

upbeat gust
#

i dont fucking know its not my code

#

you can even ctrl f it its not that hard

slate swan
#

I can show you the code

upbeat gust
slate swan
#

I’m on phone rn I can’t

#

So can someone help?

#

Boutta fucking kms this shit so annoying

#

learning how to use aiohttp might help

#

Where do I use it at i skidded it off github so idk nothing about coding

rare echo
#

but your issue isnt that you need help, the issue is that you want someone to do it for you

slate swan
#

No I’m asking where i put the thing at on my code

rare echo
#

what "thing" ?

rare echo
#

to import aiohttp?

slate swan
#

Yes

rare echo
#

at the top?

slate swan
#

Yes the aiohttp where do I put it in my code

rare echo
#

well its a module, so youd have to create something with it

#

depending on what you want to do

#

so in this case if its a discord bot perhaps under the command that will be using it

#

but as i said before i would suggest learning python basics before tackling something and just guessing along the way ( without actually learning )

slate swan
#

Ah fuck nah

rare echo
#

?

slate swan
#

the code =

@bot.command(aliases=["top"])
async def leaderboard(ctx):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT level, xp, user FROM levels WHERE guild = ? ORDER BY level DESC, xp DESC LIMIT 10", (ctx.guild.id,))
        data = await cursor.fetchone()
        if data:
          em = discord.Embed(title="Leveling LeaderBoard")
          count = 0
          for table in data:
              count += 1
              user = ctx.guild.get_member(table[2])
              em.add_field(name=f"{count}. {user.name}", value=f"Level - **{table[0]}** | XP - **{table[1]}**", inline=False)
          return await ctx.send(embed=em)
    return await ctx.send("There Are No Users In The LeaderBoard")```


the error

[2022-10-05 14:34:09] [ERROR ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 508, in leaderboard
user = ctx.guild.get_member(table[2])
TypeError: 'int' object is not subscriptable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 204, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not subscriptable

slate swan
#

then what do i do

naive briar
naive briar
#

Wait 🤨

slate swan
#

Okay

naive briar
#

Why did you set the limit if you're going to fetch one item?

slate swan
#

yo

#

can someone help me

naive briar
slate swan
#

i will try

slate swan
#

someone help

slate swan
naive briar
#

Intents are required

slate swan
#

i have intents

#

!intents is how you do it

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
slate swan
#

are you watching some trash YT tutorial?

naive briar
#

Not again

vale wing
#

Genius

slate swan
#

Maby

#

works but its doing me twice

vale wing
#

Why is it rainbow

slate swan
vale wing
slate swan
slate swan
#

@bot.command(aliases=["top"])
async def leaderboard(ctx):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT level, xp, user FROM levels WHERE guild = ? ORDER BY level DESC, xp DESC LIMIT 10", (ctx.guild.id,))
data = await cursor.fetchall()
if data:
em = discord.Embed(title="Leveling LeaderBoard")
count = 0
for table in data:
count += 1
user = ctx.guild.get_member(table[2])
em.add_field(name=f"{count}. {user.name}", value=f"Level - {table[0]} | XP - {table[1]}", inline=False)
return await ctx.send(embed=em)
return await ctx.send("There Are No Users In The LeaderBoard")

vale wing
#

Cause you might have duplicate records

slate swan
#

thats the code

vale wing
#

I need the table creation code

slate swan
slate swan
#

!share

slate swan
#

!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.

vale wing
#

Just levels table SQL

slate swan
slate swan
#

i can also assume ur going to host the bot on replit

vale wing
# slate swan it works on vs code tho

!e

print(" ".join(i for i in sorted([_amo__gu__s for _amo__gu__s in map(str,filter(lambda x:True,list(tuple(set(["this","works","too"])))))],key=lambda x:x.startswith("t"),reverse=True)))```
unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

too this works
slate swan
slate swan
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1664971534:f> (10 minutes) (reason: newlines rule: sent 11 consecutive newlines in 10s).

The <@&831776746206265384> have been alerted for review.

vale wing
#

@slate swan you probably want to recreate table with id INT PRIMARY KEY because otherwise you will have duplicate rows in your table

slate swan
#

what was that O.o

vale wing
vale wing
slate swan
#

i will try

vale wing
#

Type should be INTEGER PRIMARY KEY instead of just INTEGER for id column

cosmic sequoia
#

I have a store where the catalog can change, how do I create a message with buttons, the number of which will be equal to the number of goods in the store?

slate swan
#

shouldn't they be using BIGINT(18) instead of INTEGER

vale wing
#

Make sure you delete the table first, although you can set the primary key by altering it I think

slate swan
#

OH

#

@bot.event
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
setattr(bot, "db", await aiosqlite.connect("level.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER, id INT PRIMARY KEY)")

vale wing
slate swan
#

i did that

#

i seee

vale wing
#

In postgres discord IDs are stored in BIGINT fields however

hollow badger
#

!unmute 643460905283092510

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.

slate swan
#

oh can i do something then?

hollow badger
#

!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.

vale wing
#

What happened to him lol

slate swan
hollow badger
slate swan
#

how do i send my code then lmfao

velvet compass
fresh ferry
#

any ideas ??

#

i knows the problems with the try: and expect: but it doesn't make sense

slate swan
#

can't have 2 excepts for same try

fresh ferry
#

pretty much removed them all within it and it some what worked ima test rn to see

slate swan
naive briar
smoky cedar
#

hi. how do I make the admin ommand that if the user used in and he don't have admin perms the command will not work?

slate swan
# naive briar You probably have 2 rows with duplicated values

@bot.command(aliases=["top"])
async def leaderboard(ctx):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT level, xp, user FROM levels WHERE guild = ? ORDER BY level DESC, xp DESC LIMIT 10", (ctx.guild.id,))
data = await cursor.fetchall()
if data:
em = discord.Embed(title="Leveling LeaderBoard")
count = 0
for table in data:
count += 1
user = ctx.guild.get_member(table[2])
em.add_field(name=f"{count}. {user.name}#{user.discriminator}", value=f"Level - {table[0]} | XP - {table[1]}", inline=False)
return await ctx.send(embed=em)
return await ctx.send("There Are No Users In The LeaderBoard")

naive briar
#

I didn't ask for the code

slate swan
#

but you can see i didnt

naive briar
#

There are duplicated rows in your database file, not the problem with this code

rare echo
rare echo
#

see if anything is duplicated

slate swan
#

is that my answer?

rare echo
#

you’ll have to use some sort of viewer

slate swan
#

to delete level.db?

slate swan
rare echo
#

i don’t use vsc so i can’t recommend anything for that

rare echo
#

check the data and see if there’s anything duped

rare echo
# slate swan

have you put anything into the db? or is it just empty

rugged shadow
#

check level.db

#

it's not plain-text, you need an sqlite viewer

slate swan
rugged shadow
#

yep

#

install the "SQLite" extension

slate swan
#

I did

rugged shadow
#

ctrl+shift+p

#

search "open database in explorer"

slate swan
#

now what

rugged shadow
#

level.db

slate swan
rugged shadow
#

Bruh

#

No

slate swan
#

what?

rugged shadow
#

There should be a tab called "sqlite explorer"

slate swan
#

OH

#

there is

vale wing
#

@slate swan I said use primary key for ID

vale wing
#

And delete the table to overwrite it

slate swan
#

what do i do instead of table

shrewd apex
slate swan
slate swan
shrewd apex
#

i want my ide to glow as well

#

oh

#

😭

slate swan
#

do you have that already?

naive briar
rugged shadow
#

this is why you should use primary keys

slate swan
# naive briar There's no primary key, great

@bot.event
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
setattr(bot, "db", await aiosqlite.connect("level.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER, id INTEGER PRIMARY KEY)")

rugged shadow
#

your db is old

#

just remove yourself from the db and recreate

slate swan
#

wdym

rugged shadow
#

you updated your code after you got put in the database right?

slate swan
#

working!

#

its working!

smoky cedar
#

hi. how do I make the admin ommand that if the user used in and he don't have admin perms the command will not work?

rare echo
#

/test example message_id:1027118383222767666

in the code its just an Option(int, desc=...) but why am i getting an error saying its not a valid integer

#

ik i could take it as a str and just int it

smoky cedar
#

can someone help?

slate swan
#

blame javascript for that

rare echo
slate swan
rare echo
slate swan
smoky cedar
wicked atlas
smoky cedar
#

where

slate swan
smoky cedar
#

oh yes thanks

slate swan
#

at the end of function defination

smoky cedar
#

help..

#

it works but when I use the application command

#

it shows this error

naive briar
smoky cedar
#
member:discord.Member ```
#

or

member:str
wicked atlas
#

member is fine

slate swan
#

from reason

smoky cedar
#

oh

naive briar
smoky cedar
#

reason:str

slate swan
smoky cedar
slate swan
#

Idk it looks normal to me. Btw u need to add , *, before the reason parameter cuz when somebody uses the command and tries to warn somebody it will take only the first word. And try to typehint the reason reason: str = None (if u want, its not necessary)

smoky cedar
#

thamk u, it works now

#

anddd one thing

slate swan
#

Mhm

smoky cedar
#

how'd make it only user that have administrator perm can use it?

#

I wanna design it like embed msg blah³

slate swan
smoky cedar
#

where do i put i

slate swan
#

Under @uncut zenith.command() šŸ¤·šŸ¾

slate swan
#

nope, that check won't work

smoky cedar
#
if commands.has_permissions(administrator = True)
#

?

slate swan
#

!d discord.app_commands.checks.has_permissions

unkempt canyonBOT
#

@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
slate swan
#

app cmds have their own check system

slate swan
slate swan
smoky cedar
#

@discord.app_commands.checks.has_permissions(administrator)```
slate swan
unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.GuildChannel.permissions_for "disnake.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
smoky cedar
#

@slate swan ? sori ping

#

@discord.app_commands.checks.has_permissions(administrator)```
#

@tree.command(name="ban", description = "bans the specific user! (Admin) ")
@discord.app_commands.checks.has_permissions(administrator)
async def ban(ctx, member : discord.Member, reason:str):
  await member.ban(reason=reason)
  await ctx.response.send_message(f"__**SUCCESSFULLY BANNED {member}! **__")

#

here.

#

my whole command

tiny wraith
#

*im kind of new to this pls bare with me *

i ran into this error while trying out of curiosity on making a discord music bot

i was using the code that i found from github named DingoLingo

slate swan
slate swan
slate swan
#

as for the command itself, no it won't work