#discord-bots
1 messages · Page 358 of 1
well you need to tell us the error
why is player still not defined
So when I double click the program it immediately closes
run it on command promt
pt
try not making it a class method
yes
to what then?
remove the decorator if you can run the method without making it a classmethod
ok leave it I have no idea don't listen to me

!paste | whole code pretty please 🙏🏽
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
code stealer
nuh uh 
you’re supposed to set the pool to the bot’s pool, not pass it as a separate argument
bumping this if anyone has any knowledge with it, also forgot that I'm using disnake not discord.py
from urllib.request import Request, urlopen
req = Request(WEBHOOK_URL, data={'file': open('message.txt','rb')}, headers=headers); urlopen(req)
TypeError: can't concat str to bytes
help anyone
You should probably use aiohttp which is included with discord.py and provides an asynchronous interface
alright
If it's a Discord webhook you're trying to send a file thru, you can simply use discord.Webhook.send
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
If #discord-bots message is supposed to do that, you can refer to the example in the docs:
from discord import Webhook
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')
im not using it with a discord bot
Then uh
Why are you asking here is my first thing to say
My second thing to note is
..
!pypi webhooks
TextChannel.webhooks() sounds like what im looking for, thanks 
I have no idea how useful this is
is there way to make the variable that i made in the event code change in the commands code? i keep getting "welcoming" is not accessed by pylance in the commands code
the event:
async def on_member_join(member):
welcoming = "off"
channel = client.get_channel(1138787209735045191)
if welcoming == "off":
print("welcoming is off.")
elif welcoming == "on":
await channel.send(f"welcome {member}")```
the command:
```@tree.command(
name="welcome",
description="Enable welcoming for new user"
)
@app_commands.choices(
active=[
app_commands.Choice(name="on", value="on"),
app_commands.Choice(name="off", value="off")
]
)
async def welcome(interaction: discord.Interaction, active: app_commands.Choice[str], ):
if active.value == "on":
await interaction.response.send_message("test on")
print("on")
welcoming = "on"
elif active.value == "off":
await interaction.response.send_message("test off")
print("off")
welcoming = "off"```
it says you cant join bytes to strings
you can either:
- use a database
- use another external file
- use a cog and change the message through a class attribute
by the second one do you mean from file import variable
it is a one guild bot
btw can i send json files?
Then a bot variable will be the best option
no i mean like opening an external file like a json file and reading the contents
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
i mean through web hook
Wdym? Like:
with open("json_file.json", encoding="utf-8") as json_file:
json_file_for_discord = discord.File(json_file)
await ctx.send(file=json_file_for_discord)
?
^
anyways ill try myself thank you
Sure just specify the right headers
ok
if possible can you explain how to do it 🫠
well its pretty simple yk:
- open the file
- read it
What are you using this for btw? Maybe there's a more proper way to do it
get stuff from an api and send to a discord webhook
what do you mean by read it?? 😭
Opening the file with encoding="utf-8" in conjunction with json.load
Source code: Lib/json/init.py JSON (JavaScript Object Notation), specified by RFC 7159(which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript...
API of what?
Maybe somebody published a wrapper for it on PyPi already and you're reinventing the wheel
Oh you're just sending whatever to a Discord webhook
no its a scraper
@viscid hornet i got my code to work (im from yesterday with the images on a discord bot)
Have you checked the website is fine with you scraping their data
👍🏽
i sill get an error code but it works so xD
how do you invent a wheel? 
i see lots of projects already made
It's quite easy even when all you have to work with is a ruler and, crucially, a compass 
What's the point
i get thios error code but it does work
Traceback (most recent call last):
File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\main.py", line 76, in cypher_ascend_a
await ctx.send(embed=embed, file=file)
^^^^
NameError: name 'file' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1644, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'file' is not defined```
hey is there any way to get amount of transaction, sent by, and time from https//cash.app/payments/90v91cz7nsj6vmfj73g0sknxm/receipt
Can someone provide an example of how to add a slash command for my Discord bot?
I've been using prefix commands the whole time and now I'm trying to get slash commands to work too
Yes
unrelated to discord api so
Anyone got a discord bot with a command like this?
I know this isn’t really a place to ask this but it’s so specific idk where else to ask
property created_at```
Returns the snowflake’s creation time in UTC.
then get the diff between 2 of the snowflake
Yeah ik how to make it but I don’t wanna go and make a discord bot just for this rn so I’m just looking for a bot with this command
I think pyQuantum has it
discord/utils.py line 375
def snowflake_time(id: int, /) -> datetime.datetime:```

!e ```py
import datetime
DISCORD_EPOCH = 1420070400000
def snowflake(id):
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
print(snowflake(1233806632962625667) - snowflake(1233806023458951219))
@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.
0:02:25.317000
!e ```py
import datetime
DISCORD_EPOCH = 1420070400000
def snowflake(id):
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
print(snowflake(1233804178313445377) - snowflake(1233804180922044457))
@velvet temple :white_check_mark: Your 3.12 eval job has completed with return code 0.
-1 day, 23:59:59.378000

backward
Oh
!e ```py
import datetime
DISCORD_EPOCH = 1420070400000
def snowflake(id):
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
print(snowflake(1233804180922044457) - snowflake(1233804178313445377))
@velvet temple :white_check_mark: Your 3.12 eval job has completed with return code 0.
0:00:00.622000
the whole docs about snowflake is from here https://discord.com/developers/docs/reference#snowflakes-snowflake-id-format-structure-left-to-right
welcome
idk. just wanna make something new
smth unique and useful
it wont send anything because the file you're attaching is unnammed
wait no fucking way
i thought IDs were different
tbh it's the easiest way to make IDs
its also practically impossible to have two messages with the same ID
It does send something, look the picture
This is what i ment, this is what i wanted to make so the code works but i get that error messages when i use the command. But it still sends what i want it to send like in the picture
so it sends an attachment but still raises an error
Yes
you could catch it with a try except check
It does what it needs to do, but it still sends this
try:
to send the message
except it didnt work:
so continue```
I have to copy pate that and put it at the end of the?
thats just pseudocode, you need to implement it
invite them to a server where your bot is added
like you want to send a message without running a command?
,
Okay, I'm gonna try
@bot.tree.command(name="ban",description="Bans the user from the server")
async def ban(interaction : discord.Interaction, member : discord.Member, reason : str):
member.ban
await member.send(reason)
await interaction.response.send_message(f"Successfully banned {member} for {reason}", ephemeral=True)
the command does not ban the given user
anyone can help
discord already has a built-in ban slash command, but you need to await and call() it
How would I do that, ive forgotten most of my discord py knowledge and im not too familiar with slash commands
I got it to work
However
if the member cannot be dm'ed how can i make it so the bot says it instead of saying application failed?
It's not an error in the Bot, as I said it worked just fine in the GitHub Codespace and my local machine, so the logs are empty, no error rises
The interaction is not taking a second a responder when the error raises, and nope, the defer doesn't worked :/
A simple try and except statement
After you defer you should send a follow up, not a second response
does it?
what is it and how do you import it?
there’s a native /ban command
It’s not within discord.py
It’s an actual Discord command
How would I do this?
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.
try:
number = int(user_input)
item = some_list[number]
except:
print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")
For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.
@rain hedge ^
Thanks
I know, I was just testing with a defer, but that's not my error
I can't manage to incorporate it in to my code
Any help you can offer?
what are you stuck on?
what have you tried?
Im not to familiar with this so bare with me
i dont know where to put the try and except in the code
which line is raising the error?
wrap it in wherever is causing (or could cause) errors
are you putting it at the start?
whats the specific error?
the error im getting is "user cannot be messaged, or something like that"
i cant get the error since i cleared the terminal
accidentally
that means you cant dm them, so you just have to wrap that line in a try except statement and then continue from there or let it pass through to the rest of the code
im doing that but everything comes up with a red line under
Here, wait :b
ive done something wrong
Here's the error
@bot.tree.command(name="ban",description="Bans the user from the server")
async def ban(interaction : discord.Interaction, member : discord.Member, reason : str):
await member.ban(reason=reason)
try:
await member.send(reason)
await interaction.response.send_message(f"Successfully banned {member} for {reason}", ephemeral=True)
except:
await interaction.response.send_message("User cannot be messaged", ephmeral=True)
have the ban response sent outside of the try except statement
you arent responding quick enough
dont understand what you mean
slash commands raise that error if you dont respond within 3 seconds, like a few others mentioned
like remove it from there
if the user can't be DMed, that message wont be sent
the .response. message
But the error raises before 3 seconds
didnt say remove, i meant move it
yeah
So, I have to defer all the interactions?
code?
mb
@quick gust i did it
oh gosh
@viscid hornet dpy: ?tag nabc

also btw, a ban command already exists in discord UI
so you dont need to make a new one

I know, i want to build on my knowledge and i think making a successfull ban command will help
especially with this try and except stuff
the exceptions should be documented
||(make something different thats not a ban command)||
but we can continue
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
lmao bro thinks we're in dpy 
too used to it 😭
i basically live here so i've grown accustomed to it
wdym?
it means discord already has a slash command for a ban built in to every discord server
the builtin command, no
You would have to implement your own
so there comes hierarchy role respect and permissions checks
I meant implementing your own ban command if thats what you meant
since your bot isn't able to use builtin /ban command
Your class Connect4Game doesn't have acquire attribute, except you meant asqlite.Pool.acquire()
i use mysqlp
I don't really get it but no, your bot cannot use other bot's command
in your own bot, yeah
then Pool of mysql if mysql has any
or Connection
if message from owner? 
first you should use @bot.command() for this one
then for that command use check @commands.has_guild_permissions()
why are we both making connect four 😭
that scared me because thats literally my class name
HAHAHAHA

@leaden olive 😭
!d discord.Client.guild_permissions

No documentation found for the requested symbol.
@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage).
New in version 1.3.
im gonna fight you 
🔪
@wide plaza after implementing that check in the logic of the ban command you will also need to provide checks for the role hierarchy like for example
if author's role is above target's role
if bot's role is above target's role
if the target is not the author
if bot has ban permissions
for last one there is also a decorator
!d discord.ext.commands.bot_has_guild_permissions
@discord.ext.commands.bot_has_guild_permissions(**perms)```
Similar to [`has_guild_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_guild_permissions), but checks the bot members guild permissions.
New in version 1.3.
no
why do you hate commands?? they're literally miles easier to learn and work with than on_message() listeners
Ayyy 💀💀
whis this guy mentioning himself 😭
nah that emoji is wild
nom nom nom
wdym?
skill issue
ok asher 😭
just sit and learn python man ;-; give urself a week get familiar with it
yes. py @bot.command() async def caller_message(context): send message
@wide plaza
he try make discord python 😭(jk)
rip
why command no deco on message i hate it
(jk)
I've told him that a lot. but he wants to make discord bot 😭
real
how can you learn python for 5 years and not even know how to make a calculator
wtf 😭did you just say 5
was it paired with skibidi toilet or satisfying slime videos? 😭
might wanna take a few duolingo classes while youre at it too ;-;
skibidi toilet is the best show
duolingo deco? no me try. commands no
i swear skibidi toilet isnt even that bad of brainrot
!ot 😊
Please read our off-topic etiquette before participating in conversations.
i watched all the episodes w my two cousins (one 3y younger and the other 6y younger - both thoroughly component) and it was actually a good watch
my bad gang 🗣️
so you wanna become a part of our conversation
how the fuck did i write component 😭
real
naah
too much dpy
if its not one that is implemented in a discord bot, you should probably move to another channel
!paste @iron cosmos
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Hello I m slow with my knowledge at the end, the select menu is sent the way I want, but it assigns no roles and the interaction failed, maybe someone can help me^^
https://paste.pythondiscord.com/CI6A
thank you
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
wheres the error on? what line?
there is no error in the console, the assignment of roles via the selcet menu does not work
ok. how does it not work? is it when you select a role, it isnt applied? take me through the steps and where you think the error would be
since this bot is yours, i dont know how this code would perform, so you'll need to fill me in on this stuff
why are u not using a role select menu?
ok wait 1sec
chosen_roles = [option.value for option in self.values] i am 90% sure this will actually give u an array of role ids
Can you select which roles you want to have in the menu?
member_roles = [discord.utils.get(interaction.guild.roles, id=roles[role]) for role in chosen_roles if role in roles]
so here for role in chosen_roles would iterate over roles ids and if role in roles will just become false since your keys are strings
yeah iirc
Oh nice
shouldnt it be role.name instead?
hmm no not able to find any option for specifying roles for role selects there is a channel_type lemme look up the discord docs
if you already have the ids directly as values why bother with the names 
First, use !uprank MENTION to open a Select menu. If you have the role 1226501882898288641 you will see the Downrank and Uprank roles in the menu. If you have the role 1226174787962011658 you will see Verified and Rank. If you have 1226501882898288641 and 1226174787962011658 you will see all four roles. If you have none of the roles you will see nothing. That works so far. The roles you choose should be given to the person you mentioned. This interaction failed. I think the problem is that the bot doesn't recognize what you select in the selcet menu.
yeah lol role select menu is auto populated by discord
no filters or options allowed
yeah I figured, if they allowed choosing; that'd be cool
kind of weird ig they allow channel types but not id based filtering
oh ok, then I could have tried that for a long time
if its raising "This interaction failed" then you probably havent given a .response. to it
or an error happened view errors arent explicitly printed out unless u setup proper logging using the on_error handlers
no, thats not what commands are
!paste
Still trying to fix that 
Unhandled exception in internal background task 'checkGames'.
Traceback (most recent call last):
File "C:\Users\lenov\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 98, in checkGames
games = await Connect4.getAll(self)
File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 220, in getAll
async with self.acquire() as conn:
AttributeError: 'Connect4Game' object has no attribute 'acquire'
First, if you don’t specify a command name in the arguments, it will use the function name
you probably want “self.pool.acquire()”
second, you’re confusing on_message with commands
“self.acquire()” points to a function in the class called “acquire”
yeah you want “.pool.acquire()”
idk how you didnt spot that 
where hahah
bro what 😭🙏🏽
also you dont have to create a cursor. the connection is automatically also a cursor
show me where you create the bot.pool attribute
wait hold on. are you subclassing Pool? thats the only way i can think you’re getting this error
and if so, you shouldnt be
idk what you’re asking but if you want a db go for sqlite. sqlite3 is a stdlib and to view sql folders, use: https://sqlitebrowser.org
i cant create a normal prefix command with @bot.command() i keep getting AttributeError: 'Client' object has no attribute 'command'
intents.message_content = True
bot = discord.Client(command_prefix="?", intents=intents, status=discord.Status.idle)
tree = app_commands.CommandTree(bot)```
That's because discord.Clients aren't bots and have no concept of commands
If you would have used discord.ext.commands.Bot, the error would go away and the bot would actually be initialized with its own command tree
idk if you meant this by that but when i do that i keep getting this error
tree = app_commands.CommandTree(bot)```
error:
```Traceback (most recent call last):
File "C:\Users\Yido\Desktop\Yido_Bot\bot.py", line 22, in <module>
tree = app_commands.CommandTree(bot)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Yido\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\tree.py", line 132, in __init__
raise ClientException('This client already has an associated command tree.')
discord.errors.ClientException: This client already has an associated command tree.```
you’re trying to make a new command tree when one already exists by default
Because the bot class already has a command tree initialised to it (as the above person said) you don't need to give it another one (it's telling you that). If you ever create a custom command tree class, you can make it use that instead by specifying it with tree_cls= iirc
wait are they not supposed to have normal commands? i swear an example bot by rapptz used Client and had commands
well this is new
what the fuck is the point of Client then 😭🙏🏽
How to dm the sender when message is sent?
Just event handling, webhooks, messing with other parts of Discord API, just not specifically about a bot user or commands
send exists for users and members if you want to dm them
so just member.send and define member as a memberID?
In what form do you have the sender's message
Or better yet the sender
Members aren't IDs, they're objects
trying toasync def on_message(message): if message.content.startswith('$gen'): send dm
If this is supposed to be a bot, you can use the bot class and save yourself a big chain of elif statements
But anyway message.author.send(…) in this case
no like i meant using it for a bot. i get that its the core but its like using a cpu and a usb c cable and calling it a pc, is it not?
use a command
yeah in a nutshell
wait how is solstice here 😭
Clients are just a barebones implementation of the discord gateway bot API. They take in the events that are published, with the models that discord publishes, and nothing more. Anything beyond that is essentially just random stuff that whatever library person feels is useful (commands.Bot)
Idk how to do /commands
learn then. @pale zenith can you pretty please get me a link for slash commands
i got washing to do
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Less overhead ¯_(ツ)_/¯
thanks sm for the rundown 
Mfw i'm a bot
It's inferior
“jamie pull up that picture of me fighting a monster energy drink”
🤌 .docs slash
ima get my bot to work first then ill switch 😂
So I run my bot on my pc and it works just fine, so I upload it to my vm and run the cmd and get this bs 😭
video_url = f"http:/vm ip:5000/video/{random_video}"
await message.author.send('Your video link can be found [here]({video_url})')``` So If I define this....
why the FAWK am I getting sent this
not an f string
fuck
mf forgot the f on the single quotes string 
Im actually so dumb
Im learning okay 😭
me when
its alr it happens. recently i was working on a relatively simple project for school
spent, and i shit you not, 6 hours debugging the entire thing (overexaggerating w the 10 by accident)
guess what the error was
Alr so now it sent the link but since the video title has spaces its bugging out, how can I replace spaces with like + or smth?
Damn 😂
misspelled variable name ☠️
!d g str.replace
str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
I was informed you're helping badly so I'm here to babysit
also hi link 
by who 😭

The bot is open source, there is a help command, there are bot channels, use your initiative
dw
stop mocking me 😭🙏🏽
too many eyes
help command for docs doesnt tell me anything tho. and theres way too many files for my tiny ass phone screen to go through. also what would i even look for in help channels?
wait does the g mean generic or general or smth
looks like general
thats my only logical guess
why has the dpy crew suddenly spawned in here ☠️
dw
seal team six out for my ass 🙏🏽
Well, you're giving misinformation to the newbies in here, we're here to both educate you and them
who is dpy
oh. what misinformation did i give? apologies for misleading people btw
Sounds like a name of a fish idk
you 🫵🏽

link, what misinfo did i give?
i dont get where i went wrong
wrong recommendation? wrong solution? wrong roadmap? what did i do wrong??
??
I'm trying to read your message history in here to give an outline and advice but man do you send some amount of nonsense or offtopic messages in here, it's absurd just how much offtopic you speak, or the volume of messages for 1 thing lol, gimme a bit to collate this
i do yap a lot ngl. i should stop but it feels so homey here. i’ll take your advice tho. thanks link 
also do ping me when you wanna talk because im speaking w some other people on different social media
how do I test when a message is sent if its a DM?
message.guild will be None in that case
yea
how do I send msg to a specified channel id?
channel.send where channel is defined as id?
will do you just have a bunch of links for dpy docs saved on your hard drive
no i just remember
damn thats a pretty big memory
what
its more muscle memory than anything
i've used discord.py enough that i can find pretty much anything easily
One message removed from a suspended account.
u sure the channel id you are passing is an int?
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
ok then can you use fetch_channel() and see what it gives
channel = await bot.fetch_channel(id)```
One message removed from a suspended account.
!d discord.Client.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread) with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_channel) instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
fetch doesnt give None btw
he was using get
One message removed from a suspended account.
well then the issue was that your send_embed function is being called before the bot loads its cache
for using get_channel and similar function the cache needs to be loaded first
as for doesn't run can u elaborate a bit
like it's doing nothing?
One message removed from a suspended account.
are you trying to send more than 10 embeds at once?
One message removed from a suspended account.

One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
you can't there can be only one image and one thumbnail
One message removed from a suspended account.
One message removed from a suspended account.
you can send different embed with different images, discord will combine them as long as your embed url is set the same, something like this ```py
embed = discord.Embed(title="Some Images", url="https://www.google.com/")
embeds = [
embed.set_image(url="img_one.png"),
embed.copy().set_image(url="img_two.png")
embed.copy().set_image(url="img_three.png")
embed.copy().set_image(url="img_four.png")
]
await channel.send(embeds=embeds)
embed.copy allows you to recreate a new instance with the exact attribute set. Note that it only supports up to 4 images
One message removed from a suspended account.
welcome
couldnt you have used the files kwarg in .send() and have a list of file objects instead?
for local image embed yes
i was showing in general on how to do it with external url
Anyone know how I can @ mention someone without pinging them??? Ik its possible I just dont know how, I want to like show the @obsidian hill blue thing without actually pinging the user
no you can't... unless u mention them inside an embed
Finally, inclusive asker
you can, if you set allowed_mentions= in send() appropriately
!d discord.AllowedMentions
class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.
This class can be set during [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for more fine-grained control.
there's also silent=True if you want a red bubble to pop up without any sound/push notification
whys this repeating twice, i only have one instance open https://paste.pythondiscord.com/L7QA
yes, Thats what Im trynna do
alright then it shouldn't ping them
Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
messages, upgraded, tail = self._request_parser.feed_data(data)
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
Invalid method encountered:
b'\x03'
^
Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
messages, upgraded, tail = self._request_parser.feed_data(data)
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
Invalid method encountered:
b'\x16\x03\x01'
^
Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
messages, upgraded, tail = self._request_parser.feed_data(data)
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
Invalid method encountered:
b'\x16\x03\x01'```
@hushed galleon yk what could be causing this? ive noticed it ever since I started running a webhook server for topgg
looks like top.gg is sending you a bad HTTP payload 
its been happening too much 😔 any way I can suppress the errors without having to mess with the internals?
don't think so, as http parsing goes really deep into the core
you could probably suppress it top level though
dang
oh, mind explaining just the procedure?
try/except in the route handler essentially
unless this error gets raised even before that
I'm using topggpy so I could try handling that in their route handler
I'll try and get back 👍
Do you have an on_message listener?
no messages for 1h 30min 😭🙏
at one point discord-bots channel activity was second only to pygen 🐐
we've fallen off, bros. its joever
im making connect 4 AI on discord. if any of you wanna play it hmu 
[ @shrewd apex i'll put you in this as well because i know you got nothing to do (so do i 😭) ]
code: https://paste.pythondiscord.com/U4OQ
basically for some reason, im getting a "cant iterate over NoneType" but the list literally exists and the bot knows it
where?
lemme get the line for you rq
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\user\OneDrive\Desktop\minigames\connect4 with ai.py", line 20, in callback
await self.view.play(
File "c:\Users\user\OneDrive\Desktop\minigames\connect4 with ai.py", line 129, in play
if winner := self.is_game_over():
^^^^^^^^^^^^^^^^^^^
File "c:\Users\user\OneDrive\Desktop\minigames\connect4 with ai.py", line 94, in is_game_over
for x, _ in enumerate(self.board)
^^^^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not iterable```
line 94
ohhh
its the list comp part
rotated_board = [
rotated_board = [
[
self.board[-1 - i][x] for i, _ in enumerate(self.board[0])
]
for x, _ in enumerate(self.board)
]```
place_counter function returns None
and in play function board is re assigned from it
you're such a good boy



still have the same error from yesterdaay 😂
what was the error again?
doesnt the slash commands interactions use user?
user = interaction.user
^^^^^^^^^^^^^^^^
AttributeError: 'Command' object has no attribute 'user'```
show code
name="data_test",
)
async def interaction( ctx ):
color = "red"
user = interaction.user
user_id = user.id
ref = db.reference(f"/")
ref.update({
color: {
"color" : str(color)
}
})
interaction.send(f"worked {user | user_id}")```
your function name is interaction 💀
- dont name your funcs interaction
- you already got told slash cmds dont take
ctx

😭
also:
3. use cogs. please 🙏
i already have a cogs folder with a command file in it. i just dont know how to use it
wdym "dont know how to use it"
do you not know how to:
- load the extension
- make a cog
- run commands in a cog
i only know the second one
!d discord.Client.load_extension
No documentation found for the requested symbol.
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
ok that works
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
you want this 
@slate swan 


Hello could someone help please my bot is working correctly however when I or anyone clicks on one of the buttons I get, This interaction failed.
View doesn't have an on_button_click method
where did you get that from?
Get what?
who told you that this method exists or where you found out about it?
So I got a couple of idea from places on google as I'm still learning python and unsure on some stuff
unless this is not discord.py
await bot.load_extension(f"cogs.{filename[-3]}")
File "C:\Users\Yido\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\bot.py", line 1009, in load_extension
spec = importlib.util.find_spec(name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib.util>", line 91, in find_spec
ModuleNotFoundError: No module named 'cogs.'```
https://tree.nathanfriend.io - show me your file tree
.
├── pyache/
│ └── config.cpy...
├── cogs/
│ └── greetings.py
├── .env
├── bot.py
├── config.py
├── package.json
└── settings.py
show your loading ext code
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[-3]}")
print("loaded")```
replace the loading extension with printing the filename and tell me what comes up
filename[-3] is indexing, not slicing.
how'd i not spot that 😭
leo always comes in at the best times
hes like jesus but italian i think
filename[:-3] is what you want. "Grab until the 3rd last character"
the cogs are now loaded i guess but nothing seems to be happening
explain "nothing happening"
isnt the bot supposed to say hello back to me when i say hello or on_ready event its supposed to print "the cog is ready"
async def on_ready(self):
print("the cog is ready")
@commands.command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member
async def setup(bot):
await bot.add_cog(Greetings(bot))```
did you define ._last_member as None?
and i dont see why it doesnt send. are you doing <prefix>hello?
yes
ie. ?hello, !hello, ;hello, .hello, etc
i didnt know i had to use prefix 🤯
it works now
thats how a command is supposed to be run 
its alr, now you know 
yes
thank you
!psate
!paste
https://paste.pythondiscord.com/BHWQ
Cant fix this error:
Unhandled exception in internal background task 'checkGames'.
Traceback (most recent call last):
File "C:\Users\lenov\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 98, in checkGames
games = await Connect4.getAll(self, self.pool) # Übergebe self als Argument für die Instanz und self.pool als Argument für den pool-Parameter
File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 223, in getAll
async with pool.acquire() as conn:
AttributeError: 'NoneType' object has no attribute 'acquire'
i want to make a bot that when you send the command rickroll with a user it dms this user mp3 of the song, i made another command that adds the bot to a voice channel and plays the song but that already finished, anyone can help me do the dm thing?
`import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
from discord import FFmpegPCMAudio
import requests
import json
client = commands.Bot(command_prefix='r',intents=intents)
@client.command()
async def rickroll(ctx):`
show where you're assigning pool to bot
ok
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
also please for the love of god rename client to bot
Thank youuu
show the setup function at the bottom

Nuh uh
How should I make my cogs load in main.py?

Yeah @bot.
def setup(bot):
bot.add_cog(Connect4Game(bot, pool=bot.pool))
why do you not just set pool to bot.pool instead of making it an arg?
either way, where are you defining the pool in your main file
they actually have set it to bot.pool, but theyre just not using it. instead going the long and unnecessary route by passing bot.pool and then using self.pool 💀
^^ @leaden olive
uhm
Can you get who owns a discord bot, by just the bots User id?
@viscid hornet this command would solve all the problems in the discord.py world :kekw:
just make a smart sync
that emoji name @vapid parcel 💀
😔
thats the point 😭
Now answer this QUESTION!!!
Can you get who owns a discord bot, by just the bots User id?
I don't think public can, but I am sure someone can, but I could be wrong 
afaik no
doubt
iirc it used to say when adding it, but now just refers to "the app's developer"
and you can only even get to that stage if it's public
Yeah ik, but, discord should make that public
because, then you could see who owns certain bots
but then it could be used for attacking too
so there is a Plus n a Negative to it
i mean it would be listed on stuff like top gg or smn if the owner really wanted to make it public
what's the positive? if devs want people to find them they can make that info accessible
Prolly be used more for attacking than anything, I was only asking to find the owner of this bot to see if he would continue the bot, thats why I was asking
if they dont then people shouldn't be able to
alr, goodbye ❤️
lol are you seriously reacting to messages of people having a discussion with a clown whose emoji name contains a racial slur
:/
I never made the emoji 
its from a big big server
let me think of the name
Its from this server
for the longest time we weren't allowed reactions in this channel because people abused them, and now idiots like you come in with the apparent intent of getting the permission removed again

Hello @vapid parcel please don't use emojis with slurs in the name
bro summoned the mod
idc for the name, i just like the emoji
get the gif of the emoji, add it to a priv server, with a friendlier name
I'd argue the content of the emoji is equally valid as a moderation concern for a help channel
To much work ngl 😭
insinuating people are clowns for having an opinion on privacy is... unhelpful
I have reduced motion on, so it doesn't even animate until I hover on it. The 🤡 is objectively better
You assuming that I am insulting or like trying to be rude? is wild, i was just doing it for the funny, personally I like the emoji, tbh I didn't even know the name of the emoji if I am being honest, all I type in is goofy to find it
i never read the emoji names
so change what to what?
just show me where you're setting the bot pool first
Ah
nuh uh
here
I'd prefer you share the code (after removing the credential)
class Status(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.loop = asyncio.get_event_loop()
self.pool = None
self.update_status_task = self.loop.create_task(self.update_status())
async def create_pool(self):
try:
self.pool = await aiomysql.create_pool(
host='',
user='',
password='',
db='',
loop=self.loop)
except Exception as e:
print(f"Failed to create pool: {e}")```
This is what I use for myself, which works perfectly fine
But I have no clue what you are doing, so can't really help 😭
I use this for a status on a website for my bot. But I am going to assume you are using it to connect to the db for your whole bot..?
One message removed from a suspended account.
One message removed from a suspended account.
sure one sec
This is just a discord issue, nothing you can do
I feel like trying 2 images might work on mobile
since there will be more place for them? I don't really know
dark ages fr
One message removed from a suspended account.
any news?
can you give an example? lets say the file is rickroll.mp3
to send a local file you will first need to wrap it in discord.File() object and then send it using file parameter of send
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
# Get the file path
file_path = os.path.join("example.mp3")
# Wrap it in a File Object
file = discord.File(file_path, "Whatever.mp3")
# Now send it
await member.send(file = file) # member is your discord.Member object
is there a reason why "entered" variable keeps returning as none even though something is entered through the form modal
@bot.tree.command(
name="data_test"
)
async def data(interaction: discord.Interaction):
entered = await interaction.response.send_modal(send_data())
print(f"{entered}")
color = entered
user = interaction.user.id
ref = db.reference(f"/")
ref.update({
user: {
"color" : str(color)
}
})```
your send_data modal would hold your textinput value, happens after submitting the form, interaction.response.send_modal method doesnt return anything. just move your database logic inside on_submit method of send_data, such as ```py
class SendData(discord.ui.Modal):
color = discord.ui.TextInput(label="Color")
async def on_submit(self, interaction: discord.Interaction):
color_value_set = self.color.value # get color value
# do db logic here
in your slash command, just use them as ```py
await interaction.response.send_modal(SendData())
am i supposed to do that or am i doing it wrong
you're doing it wrong, on_submit is apart of your send_data class, its a method of it. It is triggered when the user click 'submit' on the modal
Is there a way to have more than 5 buttons with Discord.py only? send() and edit() don't seem to have components= and view only handles 5 buttons and there's apparently no way to add two views to a message.
How to add multiple rows?
just add the buttons how you normally would based on the order u added it the buttons will automatically formatted
!d discord.ui.button
@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), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#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) 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.
if u want to define which row it will go in use the row property or argument
Normally I would add it with a view, something like this:
view = View()
view.add_item(Button(label="Asher"))
works now add all the buttons u want like that
and just send the view it should show all the buttons u have added
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
also takes in a row= similar to how label= u have added
but how is it wrong if its submitting
if its possible can you explain what should i do 😭
is it doing the functions inside on_submit?
the answer is going to be no
what you need to do is copy the entire on_submit function and put it inside your send_data class
you'll also need to add self to the parameter and access the "entered" value however discord allows you to
i already did explain it, the best thing you can do right now is copy the example and see how it works, it's a working example with a solution pointing to what you're trying to do
How do I test / read a users status when it’s updated or just check it every mins
use the on_presence_update event
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
How can I make a bot check if a role has been given to somebody?
You can check if the role is within their roles already:
if Role in Member.roles:
!d g discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
Member.get_role(id) is not None works too
.
Would also be false if it isn't cached
Yep, long live discord.py caching.
@viscid hornet plis help me with cogs
just ask
@bot.tree.command(name="check")
async def check(interaction : discord.Interaction):
staffrole = interaction.guild.get_role(1155546749117669376)
if staffrole in Member.roles:
print("Assigned Team")
what did i do wrong?
Well Member here is undefined. I used it as a placeholder for an existing Member object, maybe such as interaction.user in your case
I need it to scan for any member in the guild and check if they have staffrole
If I would try to use bot's get_channel function and it would return None and after that use fetch_channel coro and it would return a channel, would it be added to the cache so it works the next time with get_channel or would I have to store the fetched channel in my own cache?
(yes thats alot of woulds)
You can't directly insert things into cache. Channels you have permission to should be cached in the first place, so it's probably worth sussing out why that is
🗣️ 🗣️
i thought you used postgres. how come you're using mysql?
psst, your on_submit() should, like the other person said, be a part of your send_data class, but it also takes self and interaction as arguments
whats your issue
mf replied in 2 to 3 business days
how do i make slash commands for dms
register them globally
hows that, show an example please
what library are you using?
So you would need to sync the commands globally, it’s recommended to use a prefix command for syncing and I’d recommend using this one https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
I curated and created a pretty full-featured command for syncing your CommandTree, you can see it here:
ok thank you
You should also understand the concept of what syncing is and when to sync and you can find information about that on the hyperlink in that link
im intermediate in discord.py but i never made slash commands, but thank you
Im trying to create a forum post using discord.py library, but it doesnt create any nor it does throw any errors. What might the issue be?
async def _create_products(self, channel: discord.ForumChannel):
for product in self.data['products']:
try:
print(product)
product_utils = self.ProductModeUtils(product)
print(channel, channel.id)
product_thread = await channel.create_thread(
name=product['label'], auto_archive_duration=10080,
embed=discord.Embed(
title=product_utils.title,
description=product_utils.description
)
)
except discord.HTTPException as e:
print(f"An error occurred: {e}")
p.s. channel object is passed correctly as well as self.data json
You're excepting a specific type, is it possible you're getting some other uncaught exception that you aren't logging?
i've tried just catch general exceptions except Exception as e and it didnt show anything as well
Are you getting either of those prints?
yes, both of them
all of the data passed is correct
one of each, like the print statements supposed to do
{'label': 'test-product', 'description': 'This is a long description of test product', 'price': 1500.0, 'curr
ency': 'USD'}
en 1224700856176476161
And if you pass in multiple products, do you only get those 2 prints or do you get 2N?
multiple prints as expected
I just sticked to one item in the list, no point in setting multiple
Well if you pass in multiple, that would narrow down if a) it is going through all and discord thinks it's making them or b) you're erroring on trying to make the first one and not seeing the error
Hello, which library can I use so I can add buttons and that?
what library are you using?
Pretty much all of the major libraries support them at this point
I try to download the
discord-components and this appears to me (I have python 3.12.2) and this appears to me:
ERROR: Could not find a version that satisfies the requirement discord-components (from versions: none)
ERROR: No matching distribution found for discord-components
discord-components
Well that's not a library that exists on pypi at least
discord-component is, though it hasn't been updated in over a year so 
So which library for adding buttons can I use? the best known or a good one pls
It's a very opinionated question lol
discord.py is the most popular one
by, xd
I have downloaded discord py, does it allow me to add buttons?
Yeah, discord.py supports buttons
oh look, I'll try, thanks
there's examples in the discord.py github repository including button examples
I use mysql for my website and postgres for my bot.
ohhh i see
hey idk if this counts as discord bots but its got to do with insta claiming a ticket #1234248356642029659 and yeah ive made some post about it pls help am stuck 😭
It is against discord TOS to write automation that works on user accounts just fyi
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
await setup(self)
AttributeError: 'Command' object has no attribute 'remove_command'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/jishaku/features/management.py", line 61, in jsk_load
await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.jail' raised an error: AttributeError: 'Command' object has no attribute 'remove_command'
class jail(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.lock = asyncio.Lock()
@commands.group(name = "jail", description = "jail command mf" , invoke_without_command = True)
async def jail(self, ctx):
await self.bot.get_cog('events').cmdhelp(ctx, 'jail')
@commands.command(
help="view the jailed users in the guild",
usage="jail users",
aliases=["arrested"],
brief = """example: ,jailed"""
)
@commands.cooldown(1, 5, commands.BucketType.user)
@blacklist()
async def jailed(self, ctx):
# ect rest of my code
@jail.command(
help="view the jail module settings",
usage="jail settings",
aliases=["config"],
brief = """example: ,jail settings"""
)
@commands.cooldown(1, 5, commands.BucketType.user)
@blacklist()
async def settings(self, ctx):
# blah blah
resolved
How can I use on_presence_update to check if presence is equal to something?
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
both the after and before parameters will return Member objects
You can do something like
if before.status == after.status:
print("status not changed ")```
import discord
from discord.ext import commands
intents = discord.Intents.all()
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print("Bot is Ready!")
@client.command()
async def hello(ctx):
await ctx.send("Hi")
client.run("uMUvax8SLfhdd1Mwg")
this dosent work
read the the last 3 lines the literally tell you what you need to do
mb bro
@turbid condor yo in 2022 there used to be a website where there is gui for embedded messages then it gives python code or js code for tht
u know tht website?
nope sry never heard of it or used it
yo
can u help me once plz
Image
i wanna make embded like this
embed message
but im lost
can u give the code ?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
ik tht
im kinda lost
so the new vouch is title
the strts r discription
they are fields
i got
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
so like this
embed.add_field(name="Vouch:", value=discord.Member.mention, inline=False)
!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.
yes
async def vouch(ctx,stars,user,description,member: discord.member):
await ctx.send(member.mention)
? this?
no
this?
it's for getting the pfp
upload em
from strt
so basically here is the codse
@bot.command()
async def vouch(ctx,stars,user,description):
embed=discord.Embed(title="⭐"*int(stars))
embed.set_author(name="New Vouch Created", icon_url=discord.Member.display_icon)
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
embed.add_field(name="Vouch:", value=description, inline=False)
embed.add_field(name="Vouched By:", value=discord.Member.mention, inline=True)
embed.add_field(name="Vouched To:", value=user, inline=True)
embed.set_footer(text="Time")
await ctx.send(embed = embed)
embed.set_author(name="New Vouch Created", icon_url=discord.Member.display_icon)
it's display_avatar not icon
that's half of the error need full traceback
ill send dm
just send it here
itts txt message dosent let me send
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yeah since it need to be a discored.Member object
wt
by itself it's nothing just an empty class
ctx.author.mention
@turbid condor
ctx dosent work
@app_commands.describe(stars = "How Many Stars Do You Give?")
@app_commands.describe(user = "User You Want To Vouch")
@app_commands.describe(message = "Message")
async def say(interaction: discord.Interaction, stars: int, user: discord.Member, message: str):
embed=discord.Embed(title="⭐"*stars)
embed.set_author(name="New Vouch Created")
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
embed.add_field(name="Vouch:", value=message, inline=False)
embed.add_field(name="Vouched By:", value=discord.Member.mention, inline=True)
embed.add_field(name="Vouched To:", value=user.mention, inline=True)
embed.set_footer(text="Time")
await interaction.response.send_message(embed=embed)
where do i put ctx here?
im a bot
discord.member.mention replace this
.
interaction.user.mention
ctx is not mention
ctx is for text commands
ahh thx
wait earlier it was ctx
i changed
.
u forgot? lol np bro
.
@turbid condor last help and im leaving
@bot.tree.command(name="vouch")
@app_commands.describe(stars = "How Many Stars Do You Give?")
@app_commands.choices(stars = [
discord.app_commands.Choice(name = '⭐',value= 1),
discord.app_commands.Choice(name = '⭐⭐',value= 2),
discord.app_commands.Choice(name = '⭐⭐⭐',value= 3),
discord.app_commands.Choice(name = '⭐⭐⭐⭐',value= 4),
discord.app_commands.Choice(name = '⭐⭐⭐⭐⭐',value= 5)
])
@app_commands.describe(user = "User You Want To Vouch")
@app_commands.describe(message = "Message")
async def say(interaction: discord.Interaction, stars: discord.app_commands.choices[int], user: discord.Member, message: str):
embed=discord.Embed(title=stars.name)
embed.set_author(name="New Vouch Created")
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
embed.add_field(name="Vouch:", value=message, inline=False)
embed.add_field(name="Vouched By:", value=interaction.user.mention, inline=True)
embed.add_field(name="Vouched To:", value=user.mention, inline=True)
embed.set_footer(text="Time")
await interaction.response.send_message(embed=embed)
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
open the link in embed and see the examples
@turbid condor spoonfeed me
eheee im dum
@bot.tree.command(name="vouch")
@app_commands.describe(stars = "How Many Stars Do You Give?")
@app_commands.choices(stars = [
discord.app_commands.Choice(name = '⭐',value= 1),
discord.app_commands.Choice(name = '⭐⭐',value= 2),
discord.app_commands.Choice(name = '⭐⭐⭐',value= 3),
discord.app_commands.Choice(name = '⭐⭐⭐⭐',value= 4),
discord.app_commands.Choice(name = '⭐⭐⭐⭐⭐',value= 5)
])
@app_commands.describe(user = "User You Want To Vouch")
@app_commands.describe(message = "Message")
async def say(interaction: discord.Interaction, stars: discordapp_commands.choices[int], user: discord.Member, message: str):
embed=discord.Embed(title=stars.name)
embed.set_author(name="New Vouch Created")
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
embed.add_field(name="Vouch:", value=message, inline=False)
embed.add_field(name="Vouched By:", value=interaction.user.mention, inline=True)
embed.add_field(name="Vouched To:", value=user.mention, inline=True)
embed.set_footer(text=date.today())
await interaction.response.send_message(embed=embed)
bot.run("MTIyNzkwMDg2MjExNDgyNDIzMg.GdWaz
the examples i cant understand
i don't see any issue atm
did you just reveal your token
oh nvm that's cut down
almost revealed it
just create a bot with 1 app_command and have someone use it
alright, thanks
na
i wanna turn this into slash cmd
@commands.command()
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, count: int):
await ctx.channel.purge(limit=count)
I need help
rather then saying this state your issue
import discord
from discord.ext import commands
import asyncio
from discord.utils import get
import requests
import itertools
import json
from json import loads
import os
from typing import List
import cv2
from discord.ui import Button , View
import numpy as np
from googletrans import Translator
import datetime
import time
import urllib.request
from skimage import io
from random import randint, randrange , sample, shuffle
how can I install aall that with the lastest version
create a file called requirements.txt and put your required libraries in there like ```py
discord.py
requests
cv2
... # and so on
after that in the terminal run ``py -m pip install -U -r requirements.txt``
that's the simplest method I can think of
holy
if not entry.target.is_timed_out() and entry.before.is_timed_out():```
entry.before.is_timed_out() doesn't exist so how do I check?
what is entry in the first place?
discord.AuditLogEntry
They're diff objects, not members.
!d discord.AuditLogEntry.before
!d discord.AuditLogDiff
class discord.AuditLogDiff```
Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.
Note that accessing an attribute that does not match the specified action will lead to an attribute error.
To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for [`AuditLogAction`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogAction), otherwise check the documentation below for all attributes that are possible.
iter(diff) Returns an iterator over (attribute, value) tuple of this diff.
guys pls help
@discord.app_commands.command(name="clear", description="clear messages")
@discord.app_commands.default_permissions(manage_messages=True)
async def clear(self, interaction, amount: int):
await interaction.response.send_message(f"{amount} messages cleared", ephermeral=True)
I just want to check if they got unmuted how do I check?
i am trying to make slash cmd for clear messages
but it doesnt seem to work
anyone care to help pls ?
Sure. what issue are you facing?
there must be some traceback in your terminal?
but it just doesnt work
i think some part of the code is wong
but am not able to figure it out
@autumn sierra
wht does that mean ?
my terminal shows nothing
just the path
did u check the code ?
is there any error in hat?
@upbeat otter
do you have an error handler?
gimme a moment
nop
aftr sorting this issue i was abt to create one
I see. do you have the permissions to run this command?
am the admin
lol
oh there's a typo
whr
lemme re run
dudeeee
ur the best
got it cleared
tysmmmm
@upbeat otter
gonna work on error handling
yessir
also you should defer the response
what does that mean ?
Like after 3 seconds, the interaction times out and if you want to send a message after 3 seconds a slash command is run you won't be able to do that. defering a response beforehand and you can then edit that message
await interaction.response.defer(ephemeral=True)
#super complex processing
await interaction.edit_original_response(content='Cleared messages')```
usually just network latency be like 😔
yeah that too is a major factor
cud u explain the purpose in simpler terms perhaps ?
as of now my clear function works fine
so i dont get it
thats y
for example
I run a command that gives me weather information
Now the bot has to fetch the data from another API. Now all this will probably take a lot of time right? Let's say this all takes 5 seconds.
Now the issue with discord Interactions is that whenever you run a slash command. the bot has to return a response within 3 seconds or otherwise this interaction will be lost and there will be no response.
As the weather command took 5 seconds to process, it will never be able to return a response just in time. we use defer to prevent this
wonderful
very well explained my maan
urcool
how do i implement defer thingy
so i use defer thingy for all of my slash ?
also aftr i use defer thingy the bot has unlimited time ?
to fetch data?
@upbeat otter
15 mins
dang
how do i set it up?
.
await interaction.response.defer(ephemeral=True)
y ephemeral here ?
because defer just sends an initial response so this determines whether following messages will be ephemeral not
so i put tru for whtvr i want and false if i dont whatephemeral ?
also i add this after each slash cmd or just once at the end ??
@upbeat otter
once at start
You need to check before and after's .timed_out_until attribute of Optional[datetime.datetime], and do the appropriate date math to determine if it has expired (in case it is populated). - similar to what the is_timed_out().
so this will apply to all of my commands ?
no once at start of each command
ok
why would it be outside
lol
i think i shud do it in the 2nd last line perhaps ?
u would put it in the first line inside the async function
u told at the start
async doesnt come at the strat
lmao
u didnt mention
tht
sorry am a newbie
lol
mb
well the statement had await all awaits can only be executed under an async context
mb mb
no issues







