#discord-bots
1 messages Ā· Page 100 of 1
I don't think that would really hurt it
interaction endpoints don't contribute to the bot's global ratelimit
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
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
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):
...
But for commands, I'd suggest using the commands module
https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
i would probably implement this in on_command_error instead, catching MissingRequiredArgument and checking if any arguments were successfully parsed
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)
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
Integrate your service with Discord ā whether it's a bot or a game or whatever your wildest imagination can come up with.
The error is pretty clear. You need to enable intents in the dashboard
what intents= did you pass to your bot constructor? you may have requested another intent that wasnt enabled
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
And they're all enabled in the dev portal too?
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
can you send command? upload to hastebin
sure can, want me to send via dms ??
sure
well the indentation is wrong
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?
what i thought but i wanted to make sure so i didnt give false information
...
except:
pass
š
ok
If you dont mind me asking how much did it cost you for this code in USD? Its terribly written
it is pretty bad lol
It is also sad to see honestly š
as dev blocked me
https://paste.pythondiscord.com/owawarefex
Guys how can I fix this error
dont use termux lol
I have no other option
The replit is more annoying than termux
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
returns an error? Or raises an error
returns something saying they dont have the permissions to run the command
So... A string?
if not owner(ctx):
return ctx.send("you are not a owner")
yea
yes i get that.. but i want it to be if not owner or developer
would i put :
if not owner(ctx) or developer(ctx):
return <message>
yea
Discord has an auto-afk channel right for when someone doesnt speak after x time correct?
can someone help.? im trying to make clear msg command
Remove the curly braces in limit={amount}
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 found a soluction!asyncio.sleep(900 * donor), i want cancel it (after set it, ofc) to make another one
?
how save message in json
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.
can i send someone my code? Cuz i needsomeone to fix it
what's the problem?
I saw that š„“
Note: This is currently part of a closed experiment! Only a select group of communities are participating with this feature.
We're excited to announce Premium Memberships for communities on Discord...
i found a direct link for it
but if you view any server as an @ everyone role then it shows up
Is there any way to be able to tag multiple members with slash commands?
Example: /ban @member1 @member2 reason
multiple options
!d discord.ext.commands.Greedy
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`...
Does it work with the slash command's option though? 
not sure

Discord won't reject your bot because of its library
if u go tell this in dpy server u have my respect š¶
And Danny did continue to maintain discord.py again a few months ago
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
doesn't work in slash commands
already tried
but thanks
!d discord.app_commands.Transformer
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:
make ur own convertor
Can i have MegaTron?
tutorial hellš
||bumblebee||
š
i do this```py
@bot.event
async def on_message(msg):
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?
Youāre trying to dump json to a closed file object
whats the issue
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
oh really ? okay thanks xen š
np
oh
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```
You can't get data from a file if you didn't read it
@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
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
Then why are you getting from the f instead of users?
Should be doing file operations asynchronously
!pypi aiofiles
is it possible to run a discord bot using visual studio code using my internet to test bot ??
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
Visual Studio is just an editor, which you can use your python interpreter to run files so i dont see why not?
yeah just tryna figure out the run command haha
I don't know why but bank_privacy.json resets every time the command in ran
You can just press the run button or use the terminal if youre wondering how to run a file
You know what, no it isnāt. I blame mobile code formatting
You made it to
no actually the whole file gets reseted
even the dir gets removed
like everytime it's a blank file
I
mobile and desktop client can show a different message if we're talking about codeblocks, it's mostly as mobile client always removes the space characters in a message at the start even in a codeblock while in desktop it keeps the original state
So i agree with you, it has given me allot of trouble
- Consider using an actual database instead of a JSON file
- You're trying to assign an item to an object that doesn't support the operation. Perhaps you wanted to use
usersinstead of a file-like object?
The open function with the w mode will remove all of the file's content, and json.dump will write the data back, but the error raised before json writes the data in, so the file becomes blank
Really would depend on how much CRUD operations are done on the file and how much data it may contain but it is always good to start with a database for scaling and it's good practice
install it
It was really an easy solution after all
Hey i have a question,
https://discord-edating.com/6sH7qu4P does anyone have any idea how i can convert each item in ticketcatrgorys to a button?
Ive only really done something like this with dropdown menus, where thats just a list, but idk about this
https://discord-edating.com/w0p4tECV would this work? copiolet gave me it
but whta would i even define to put code in it lmao
my brain
Installed python from website how do I set it as the interpreter?
That domain
lmao
thanks, that does make more sense,
however, how do u make filtered_Args work (that line doesnt work and tried some others that didnt either)
for some reason errors come up twice
it does that for several commands, and I dont have 2 functions with the same name
is there an updated place to find functions for the api?
can't seem to find anything
!d
!d
theres discord.py on the second page
tysm
if you see it twice then it was likely raised twice by your error handlers
i commented them out
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
i think i see thanks
damn my computer is clapped
its running everything twice XD
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.
Did you pass a Context object to the fetch_message function?
The error says otherwise 
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
You're missing an extra argument for the message id
The first argument of text commands is always context
ah
Not always

You should also be using snake_case for local variables
Wait so I use async def(self, ctx, MessageID: int, *, status: str) ?
message_id is more suiting
async def(self, ctx, message_id: int, *, status: str) ?
what the limit of button rows can be?
you forgot the functions name but you're probably going to fix that either way
5 iirc
tysm, works now
yes afaik
wasnt the max like 27? probably not because it would be uneven
always was told itās 25
one more question, Iām being told my message object has no attribute set_field_at
this says I need a embed object
so how do I get my embed object (which was already sent) with message ID
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
That was fast
!d discord.ext.commands.Context.message
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.
so in my case I would use m.embeds[0] right?
Should make a check first
it can return an empty list
it shouldnāt since my suggest command will always send an embed
and only an embed
Well, then no need!
thanks, Iāll try it now :)
š
now Iām not getting any error but my bot does nothing when I run the command..
i was getting 2 of everything when using bot.listen()
for on_message
i changed it back to bot.event
but I wonder why I was told to use bot.listen()
https://discord-edating.com/wLBQzvVO anyone know how i can do this? selection is passed in from a button and i need it to get questions, so idk how to exactly do this
!evel
!eval dict = {}
dict.append("test": {"hello": lol})
!eval dict = {}
dict.append({"test": {"hello": lol}})
i give up
#bot-commands
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?
self.selection?
or you put it outside of init
so you might want to put it inside
cant access that from there
has to be there (?..)
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
theres modules
u need a webserver
is this code correct??
i think they use the same data they collect from the API, in particular the message history, and then generate a discord look-alike html page thats uploaded as an attachment for staff to open
how using discord.message.Message()?
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
"using" a discord.Message object is too vague for me (and others) to tell you anything relevant, so could you describe what you're trying to do?
oh u mean uploading the message history to a github file?
and thanks, I forgot I could simply use message history XD
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
generate a page without using anything to host it
and use who to host the java/ccs?
@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?
i dont do much web dev so i wouldnt know what options are good
ight np, thanks for the ideas
anyone
did you try installing as admin those libraries? python3 -m pip install name-libra
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?
It's against Discord's ToS
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!rule 2
2. Follow the Discord Community Guidelines and Terms Of Service.
Interesting how you dont care about this platforms TOS but you agreed to themš¤
Anyway forgot it
Hey! Anyone know the answer to this?
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.
Have you tried printing ctx.author.guild_permissions.manage_messages ?
Can you show your command parameters
async def ds(self, ctx, message_id: int, *, status: str):
Nope, but Iām quite certain the author doesnāt have manage messages.
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
?
I don't understand what could go wrong
me either!
printed nothing
I just got the error again
Show the error message
I'm guessing it has something to do with how you may not have given them manage messages permission guild-wide
cause the error
they shouldnāt have it at all?
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.
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)`
You would subclass button and dynamically add_item
I don't how to do the dynamic part, do you know the location of add_item docs?
!d disnake.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
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 
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 
What do you use to share your bot then
I googled traffic and top.gg seems by far the biggest
Not really... Just don't vote for bots if it bothers you
there are vote locks on commands
even some in-game currency can only be accessed by it
basically an ad wall to use commands
better than paid bots imo
top.gg also doesn't forces it, its just the developers who do that for votes
i mean id rather pay for something to support devs than ads
i find opening a link and clicking a button eaiser
don't do much stuff with bots anyways
why won't devs do that if they find a chance to grow their bot
i went the route of making my own and not that
the only thing i can imagine is some bots.using music featurs, but fkit Spotify exists
they don't get anything from ads but a place for their bot in special section
upcoming app directory will tackle this shit' out
prob sure it will have requirements
discord made a servers directory recently limited to some servers and it can be revoked anytime
Doesn't discord have a server directory that zero people use
it's different and was not intended to tackle with sites, but the app directory is
you can checkout this paragraph chain at D. Devs server - #697489244649816084 message
You know promoting your patreon could also be viewed as an ad
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
Then it's about different opinions ĀÆ_(ć)_/ĀÆ
in my opinion top.gg has many cons, "pay to get" something is actually bad
how can i add two fields per line in embed instead of three?
F1 - >inline=False
F2 -> inline=True
F3 -> inline=False
F4 -> inline=True
...
F means field
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)
Oh
Idk how to fix it tried some stuff nothing works
Have you tried using it as a positional argument?
I think yes
await user.timeout(until=timedelta(days=time, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0))
Itās still a kwarg
how, i dont understand
np
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
I've gotta say I don't recognize the name. I'm good though, thanks for asking. Yourself?
Robin forgetting everyone nowš
ban for cursed messagešØ
anyway, how are you doing nexus? I hope you have stopped with the usage of semi-colons in python
I've been pretty good, a bit busy though, you?
And yes, I've corrected my sinful habits 
Sorry if i didnt remember you, i just dont really remember users as it's not like they would remember me kek
Ah, don't pay a second thought to it
Could be better, good or else šØ
Y'all are busy, remembering everyone who pops in is impossible
Unless you've got a fully functioning database inside your head 
Yeah i have a JSON db with blockingio that's why I'm mentally slow
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
you misspelled existing_user with exisitng_user
you're kidding, aren't you..?
Wish i was
shhh, 

;-;
Aight thanks for that
I should probably get more sleep 
Was that really your issue?
if someone presses my button, i want it to click a link so its like a authroize bot link
Which a message component or a button which is shown when opening a profile of a bot?
@discord.ui.button
!d discord.ui.Button.url
property url```
The URL this button sends you to.
TypeError: button() got an unexpected keyword argument 'url'
@discord.ui.button(label="Press me AFTER verification!", style=discord.ButtonStyle.primary, emoji="āļø", url={url})
examples/views/link.py line 33
self.add_item(discord.ui.Button(label='Click Here', url=url))```
Ah yeah, that jogs my memory. Good seeing you again
i dont understand
!d discord.ui.button | this doesnt have a url kwarg
@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.
!d disnake.ui.button
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.
disnake has it though
could you show me a code example on how to add it
^
I would assume that itās because url buttons canāt have a callback so a decorator is useless
like do i remve the @discord.ui button?
@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
Pardon?
What this says in the note
Oh I was just saying why it has no url kwarg
š
I wonder why disnake has that kwarg tho
Seems a bit useless
Yeah
so how do i use it in disnake
Do this in ur views init
where do i add that
Define an __init__ function in ur view
Check this out
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?
So
So my server just got access to the new forums thing
Is there any way to limit peoples view to each forum post?
A very simple way to do that would be to use a timed event on the bot. Every 5-10 minutes send a request to twitch's api, get the status of the channel, and take action as needed. You'll need to have your bot remember if the channel was live though, or you'll announce it every timer cycle.
do you know how to send a request to the twitch api?
hmm, this has changed. Where is the channel data hidden now 
Ah I see. Once you know the user's id you can use https://dev.twitch.tv/docs/api/reference/#get-streams to get the data on if the stream is live.
thank you!
Does twitch's REST API really not support webhooks?
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. 
pubsub? Havent heard of that word before
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. 
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)
Seems like a gateway with webhooks kek
It is, but with more control for the host.
What you say as "gateway" is basically just pub-sub pattern. And an API Gateway is just something that handles the flow sorta. Like where to pass things, etc. Basically an organiser.
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%
Ill look into the pattern
A... broker? Is that the right term?
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
- Is there a way to add "tags" to the different paragraphs?
- Is there a way to randomly pick one of the paragraphs?
- 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
now for this youd use a database, not a text file (or json)
darn
you probably could, but it would be really jank
u should just go with a db, its not worth the effort trying to make text files work for this
I'm the kind of person who'll try and try at this sort of stuff, My curiosity outruns my common sense 
which db is the best for discord
there is no "best db", good options are sqlite and postgres
is aiosqlite good?
yes, its a library for sqlite
sqlite (the lib) is blocking, aiosqlite is an async version
aiosqlite has minimal documentation
because its basically sqlite, just async
it's killing me
you can just use sqlite's docs
import šæ
from šæ import šæ
šæ = "šæ"
print(šæ)
Make your own data format š¤
šæyou don't even really need any methods other than aiosqlite.connect, aiosqlite.Connection.cursor aiosqlite.Cursor.execute most of the times
Guys is there any other way of hosting our discord bot on our device other than termux?
š
Doesn't work
I tried using emojis as variables but showed a unicode error ;-;
that would be cool tho
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?
Do they have the same name
@bot.event
async def on_member_join(member):
Yeah don't do that
Then what do i do
One is overriding the other
oh
the event is on member join
like
@bot.event
async def on_member_join(member, **kwarg):
You can use listeners
how
!d discord.ext.commands.Bot.listen
@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...
šæ
J
but how do i do it w the bot
Change @bot.event to @bot.listen("event_name")
Event name isn't necessary if the function is named as event
They just don't override each other if they have different function name
@bot.listen("on_member_join")
async def on_member_join(member):
It'll still override eachother if they have the same function name-
then what do i do
..name them differently..?
but will it work?
looks like the docs has an example
https://github.com/phenom4n4n/phen-cogs/blob/master/tags/processor.py
Why would we tell you stuff that wouldn't work
okay then i will try
@upbeat gust its not workinf
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
there's no event called memberjoin
why did you change the event name? We all said function name
No that's the event-
The function name can be whatever you want
where do i put the function
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??
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)
Name the FUNCTION whatever you want
is that it?
Put the right EVENT inside LISTEN
Yes
Red matters if blue is not provided
To be more correct
shhhh
@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
how do i do that if the member doesnt have a pfp it will still send the embed?
!d discord.Member.display_avatar
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.
profile_image = await load_image_async(str(member.display_avatar.url))
like that?
Yes
Pls help me anyone
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 ???
send the code
Hey @fresh ferry!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
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.
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")
You didn't define warnings in the bot
I have done that bruh
its a invite counter + auto role assigner based on the amount of invites a user does
do you think I would send the bots token in here?
oh, i dont really understand that sorry
warning system
wowwwww buddy dont get snappy your the one asking for help
your good man thanks for trying to look over it tho š
asking for help not for nuking
i am a girl and ofc! maybe other people can help
@naive briar it is kinda defined tho
No
??
It did not
Just creating a file doesn't do anything. You have to either define it by subclassing the bot or define it by setting it
lol sorry for the miss gendering you ahha
its alr!
uhh
I'll just try coding my own
i know it pretty much says the answer for me but when i remove the double instances it brings up multiple errors lol ??
hopefully it goes well š
!custom-help
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
i dont think thats the issue but thanks š
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
well you think wrong, you can't create a help command without removing the old one or providing a new subclass
open the gist it enlightenments you how to do both of these things
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}** !  ")
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
don't create a connection in on_ready, thats a really poor way.
use setup _hook instead
!d discord.Client.setup_hook
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")...
but how will the bot run?
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
like
It's just an event (on_ready)
why are you using setattr
Just run it normally
thats what it says in the vid
just do bot.db = ...
withor cursor?
you need to create bot.db first- why are you concerned about the cursor
and yes, do it in setup_hook
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'
what is bot.commit supposed to do
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
missing process_commands in your on_message
change the event decorator on on_messafe to .listen()
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?
??
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
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'
Editor object has no attribute test
What could that be huh 
The rainbow glow is blinding
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)
???
like
You assigned a string to member
the square
Then you tried to assign an item to it
no I didn't
Your get_priv_data returned string
That's literally what the error means
how?1
In Photoshop or with pillow or
how to fix it the?
like that
nono
I can't tell anything since I don't know how that function works
simple
Idk what you're trying to accomplish, sending that as an attachment?
shit
Good explanation
no
Like
I could totally understand
Now it sends ot that way That you can see that its a square
and i want it to be like that an ellipse
It adds a node to the value in this case the key is user id and the value is node which is 9
Why would you have to do that with pillow?
Save the background image and then just draw the slider ontop before you send it
You said you're using easy_pil which I assume is some weird version of pillow
I meant how the get_priv_data function works
it loads the json file
as members
You're probably saving it as a string or something weird
async def get_priv_data():
with open("bank_privacy.json", 'r') as f:
members = json.load(f)
return members```
here it is
Tf does that mean? Vsc doesn't do anything
Vsc is a code editor
i didnt upload any media
No one said you did
oh
Guys is there any way if running discord bot on mobile 24/7 other than termux?
the error is that it says the thing is a string
when it should be a dictionary
how do i open a help channel ?? i remember doing it ages ago but cant remember ?
people would ask literally anything here
!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:
why would you do this??
are you gonna constantly keep your phone awake and connected to the internet
please dont suggest replit
oh okay
pay for a a vps
await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id)) dis line
this needs to be a tuple
ā«
add the , after ctx.guild.id like you have on every other query
Dey wernt talking to u
well jokes on me then XD
How do i fix this https://mcpaste.io/a2f7ac8604b35e79
A easy to use Paste site for Minecraft Server logs.
you shouldnt be using requests anyway, its blocking
use aiohttp
Where do I put that at
use aiohttp instead of the requests library
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/
Like this?
that and in your code
Where at Iāll send my code in dms
I already said
use it instead of the requests library
Idk anything about coding I just got it off github
why is it sending twice? i did the code only once
bruh
Iāll send my code in dms
Why is my bot sending every message twice?
Either you have a stale instance of the bot running in the background, or you mistakenly put await bot.process_commands(message) in an on_message listener (which is not the same an event).
š¤Ø
!rule 9
Bro he wonāt even help me
ive given you all relevant info and further suggestions, wdym 'wont even help'
i diddd thanks!
He did try to help you, he just doesn't want to fix your code for you. You have to do it yourself
this is the fourth time, use it in place of the requests library
Whereās that at
I can show you the code
^
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
go learn the basics, then when you need help with an issue and not having someone essentially make it for many here will support you in solving an issue
but your issue isnt that you need help, the issue is that you want someone to do it for you
No Iām asking where i put the thing at on my code
what "thing" ?
.
to import aiohttp?
Yes
at the top?
Yes the aiohttp where do I put it in my code
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 )
Ah fuck nah
?
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
table is a number, not an iterable
then what do i do
The int object is not subscriptable. The fetchone will return a tuple of the selected data, so just use that
where
Wait š¤Ø
Okay
Why did you set the limit if you're going to fetch one item?
because i want the leaderboard to show up of 10 members
yo
can someone help me
Then use fetchall instead of fetchone. It will fetch items from the database by the limited number
i will try
you should use fetchall / fetchmany ( if not using limit) then
someone help
you need to add intents
Intents are required
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.
well compilers don't lie
Not again
Genius
Why is it rainbow
idk lol
Is there a primary key in your db
wdym?
you shouldn't have multiple client instances
@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")
Cause you might have duplicate records
thats the code
I need the table creation code
it works on vs code tho
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.
Just levels table SQL
works and should are different things
you probably have older version of dpy installed on ur device
nah the newest one
i can also assume ur going to host the bot on replit
!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)))```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
too this works
nah only for myself
write this in terminal
pip show discord.py
: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.
@slate swan you probably want to recreate table with id INT PRIMARY KEY because otherwise you will have duplicate rows in your table
what was that O.o
where do i put that?
That was kinda sus
Your table creation code
i will try
Type should be INTEGER PRIMARY KEY instead of just INTEGER for id column
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?
shouldn't they be using BIGINT(18) instead of INTEGER
Make sure you delete the table first, although you can set the primary key by altering it I think
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)")
In sqlite integer type recognition is automatic I think
In postgres discord IDs are stored in BIGINT fields however
!unmute 643460905283092510
:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.
oh can i do something then?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What happened to him lol
thx
posted too many newlines. Happens with large code sometimes.
how do i send my code then lmfao
@slate swan use the paste bin service
any ideas ??
i knows the problems with the try: and expect: but it doesn't make sense
can't have 2 excepts for same try
pretty much removed them all within it and it some what worked ima test rn to see
https://paste.pythondiscord.com/tazokabepo thats the code and thats what its doing
You probably have 2 rows with duplicated values
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?
@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")
I didn't ask for the code
but you can see i didnt
There are duplicated rows in your database file, not the problem with this code
i dont understand
youāre storing data in your db and two rows inside the db are cloned either names or values (i just popped in)
then what do i do
who do i remove?
go ahead and pop her open and take a look at the data
see if anything is duplicated
youāll have to use some sort of viewer
to delete level.db?
in the code?
either install something (plug-in) or just an external sql db viewer
i donāt use vsc so i canāt recommend anything for that
done
what now
check the data and see if thereās anything duped
have you put anything into the db? or is it just empty
empty
I did
level.db
what?
There should be a tab called "sqlite explorer"
@slate swan I said use primary key for ID
i did
And delete the table to overwrite it
what do i do instead of table
how is it glowing
shareX
do you have that already?
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)")
wdym
you updated your code after you got put in the database right?
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?
/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
can someone help?
discord doesnt accept numbers of that much length
blame javascript for that
gotcha, thnx
you forgot a colon
how in the world were you able to see that
im blessed with nice eyes :3
colon?
The error message points to it
where
:
oh yes thanks
at the end of function defination
You need to specify the option type for it
member is fine
from reason
oh
read the error
reason:str
Can i see the code
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)
Mhm
how'd make it only user that have administrator perm can use it?
I wanna design it like embed msg blah³
I believe its @commands.has_permissions(administrator = True)
where do i put i
Under @uncut zenith.command() š¤·š¾
Didnt mean to ping
nope, that check won't work
!d discord.app_commands.checks.has_permissions
@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...
app cmds have their own check system
That would work too if u were checking the author perms like
if ctx.author.guild_permissions.administrator:
# ...```
Idk bout thatš¤·š¾i dont use dpy2
@discord.app_commands.checks.has_permissions(administrator)```
!d disnake.Member.guild_permissions
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.
@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
*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
yes that will work
this?
outdated code, remove bot = from bot.run
you need to place that @ thing above that
as for the command itself, no it won't work



