#discord-bots
1 messages ยท Page 337 of 1
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id)
How do I make so options show up like this? Or what's the name of it?
Choices
!d choices
Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a sequence object as the choices keyword argument to add_argument(). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
Thanks!!
Not that, it's in discord.py or whatever library you're using 
I printed it and they give 2 completely different values
LMAO
oops
Depends on the context
Yeah obviously if your bot sends a message it will trigger the event and you'll get its ID
I think.., there 2 values stored in my sqlite3 database with different id's so I'm guessing
im stupid manz alr
thanks tho
If you want to ignore these messages, which is recommended, consider adding a check at the top
Hello, how do I make a discord bot for personal use, I already created the bot, how do I code it
See pinned messages and channel description
Traceback (most recent call last):
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Naseer\Desktop\That one server\cogs\Fighting_Commands.py", line 117, in fight
damage = P_style[ctx.author.id][style] + dmg * Mult[FistA]
~~~~^^^^^^^
TypeError: unhashable type: 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\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: TypeError: unhashable type: 'list'
code:
else:
FistA = random.choices(FistAD, weights=[10,5,1], k=1)
damage = P_style[ctx.author.id][style] + dmg * Mult[FistA]
Hey i just wanna ask a long and hard question :D The image i post is generated through a bot like midjourney yk. Do you have any idea how these bots work? Opencv? Deep-learning? I just googled and there is no info about that. I know like these projects need lots of gpu and hardware but wanna make like the image i sent. It makes it with pixels what i mentioned. I just made a bot creates a image with api but it doesn't work the way i want it to and using the API is paid after a while so I don't want to give money. Any idea, tutorial, article or sth?
What im trying to do is add a scenario where there is a chance that certain actions are happening that boosts the damage thats been inflicted but it doesnt seem to work.?
when I remove choices() and put choice it seems to work but i want to avoid that, to make each scenario have a higher chance of happening..
They're probably running a text-to-image model or making requests to an API (most likely)
You can search up text to image models and find some info
Frankly, I don't think it's an API. I've used and researched a lot of apis, but no one can do what this bot does.
Hmm, I'll test something
I think it's deep-learning but I'm not sure :/
If I don't get it wrong, deep-learning works with math functions and I don't know the functions very well lol (u can ping me)
Alright, I'm out of ideas
can you help me out
Tysm have a good day ๐
https://paste.pythondiscord.com/7I4A
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
I get this is within the @app_commands.command
I've tried it with both
interaction: discord.Interaction and interaction: discord.interactions.Interaction
I get the same error.
This is just a mock-up.
I just want to get the basic functionality of it sending a message, adding the view, and on_interaction it will respond with adding the role right now.
what do I need to change in to make this work or why? or both
wooahh
This will be very useful to me
thank you soo much
same error if I move it to line 42. I was getting the error prior to adding button in the view.
examples/views/confirm.py lines 29 to 30
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
same error if I add it into the callback.
I'm guessing theres multiple parts that are wrong, but I don't see much documentation of these going into a class of it's own, calling the view and getting this error. even from what I found searching this discords q/a's on TypeErrors.
Also, line 9: You probably don't want to call the function, but just assign it
so like this?
https://paste.pythondiscord.com/REKA
You're still calling the function
Line 33 now though
Not sure why you create a new button as well
how is that not assigning the function to button.callback?
You're calling it, and assigning the result
Assigning would be without the ()
And look at this example, you don't need to assign the callback explicitly nor create a new button - not quite sure what you're doing
from the examples I found you need to reference the callback to the button for it to work. Is that not the same w/ @discord.ui.button? or is the asynchronous function automatically a callback.?
Look at the example
And if you wish the other examples on GitHub, there are multiple (https://github.com/Rapptz/discord.py/tree/master/examples/views)
Those are the only ones that matter, you may find outdated or wrong examples on the internet
okay.. one shows a class as discord.ui.Button and the others show as discord.ui.View
So you're saying it's automatically a callback for the button. cool.
I still get the same error tho ๐คฃ
woops
removed.
https://paste.pythondiscord.com/OJZQ
even if I remove the whole button view section. I still get the error within the @app_commands.command
This really helped for the first step. tysm again ๐
how do i get the link from my keep_alive file to be passed into uptimerobot?
it showed a complete address before, but now the created tab only shows this address "/"
im guessing your using replit, and what your trying to do is not possible anymore
Well it is
Just click out the โ๏ธ button beside devtool button this should redirect you to the current repl's address
i already tried that, and it only allows uptimerobot to be running when the tab is open
but for something like render's free option, does the 750 hours count in terms of computation or as long as program is running? since a web service I have likely uses greater than 750 hours of computation
Can anyone help me with this ```py
class Pagination(discord.ui.View):
def init(self, ctx, selection):
super().init()
for k, v in selection.items():
style = discord.ButtonStyle.secondary if k != "exit" else discord.ButtonStyle.danger
self.add_item(discord.ui.Button(style=style, custom_id=str(v), emoji=ctx.bot.get_emoji(v), disabled=False))
class Selector:
def init(self, menu, selection, *, timeout=300.0, auto_exit=True, check=None):
self.menu = menu
self.timeout = timeout
self.auto_exit = auto_exit
self.check = check or self._default_check
self._base_selection = selection
@property
def selection(self):
return self._base_selection
@selection.setter
def selection(self, value):
self._base_selection = value
def _default_check(self, reaction, user):
return (
reaction.message.id == self.menu.message.id
and user == self.menu.ctx.author
and reaction.emoji.name in self.selection
)
async def _serve(self):
await self.menu.message.edit(view=None)
await self.menu.message.edit(view=Pagination(self.menu, self.selection))
async def response(self):
await self._serve()
try:
reaction, user = await self.menu.bot.wait_for("on_interaction", timeout=self.timeout, check=self.check)
print(reaction, user) #not working
print(dir(reaction)) #not working
except asyncio.TimeoutError:
await self.menu.timeout(chron.long_delta(timedelta(seconds=self.timeout)))
else:
if (r := reaction.emoji.name) == "exit" and self.auto_exit:
await self.menu.stop()
else:
return r
everything is working except the print statements. the bot is getting timedout on time but upon reacting with the button the print statments not workig
thats not how u get response from button
just a sec ill link u an example
ok
u register callbacks for buttons either using decorators or assigning to .callback attribute manually
can't I use buttons with bot.wait_for()?
these get triggered when the button is interacted with
no
but it is getting timedout after specified time then why not response?
wdym?
the print wont work
ur trying to use buttons like reactions thats not how views work
Pretty sure you remove the on_ for wait_for and yes it should work I don't know why you would do that though
view has a wait method built in
for testing...
Sure
Thanks man! I removed the on_ from wait_for and now it is working...
but how to get the button custom_id out of that interaction event?
pretty sure they released a statement, guess not
what am i doing wrong it doesnt send the message when someone joins
are you sure you have a system channel set
yes
try printing channel and see
so i should just put print channel under it
and what is wrong with this code its from a bot i made 2 years ago ?
it says the wow = await.... line is wrong
you tell us .. you have the error
so from that error all we know is that guild creation failed
yeh
thats the problem but it worked 2 years ago
i didnt change anythign
most likely this: Bot accounts in more than 10 guilds are not allowed to create guilds.
!d discord.ext.commands.Bot.create_guild
await create_guild(*, name, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
Hi guys !
If you have a bot running on your pc and the connexion crashes for X amount of time, will it reconnect automatically when the connexion is back? If no, what should I do for it, in your opinion? ๐
discord.on_resumed() got it ! :D
Discord.py has reconection logic
now can someone help me install discord.py on windows? I tried py -3 -m pip install discord but didn't work
What is the correct approach to persist some data for users even after they have been removed from the database so that, when they decide to set up their account again, you can retrieve their historical data and use it to prepopulate certain fields?
Experience, Levels etc
not remove them from the database
or store a boolean like is_account_disabled BOOL or have a separate table
if this is like GDPR compliance shit then user IDs are considered non-identifying info either way (i think)
I only want to keep Discord ID, gained experience, level and last activity
is there event i can use await bot.wait_for() to wait for a dropdown select like you can wait for a button_click?
then yeah keep a separate table for historical data
how do you @ a message id? if it's not <@> or <#> what is it?
like this message id: @runic smelt #1198788396387155998
#discord-bots message that?
yes
property jump_url```
Returns a URL that allows the client to jump to this message.
ty!
welcome
the format is https://discord.com/channels/{guild id}/{channel id}/{message id}
oke
if you want them for certain applications. u can add a prefix for ptb.discord.com, or canary.discord.com too
no that's just a subdomain according to discord app, but they still work across all discord apps, i sent you a link from canary, it would still work on others
I need help
I forgot how to code
in python
and in general I have been cauaght up trying to be the "cool guy" I forgot that I had a career ahead of me
?? so take some time to learn python?
What in the actual frick frack?! Can someone help me understand what went wrong? the issue is towards the bottom.
I can share functions if necessary.
!paste
https://paste.pythondiscord.com/GJQA the helper function
the traceback was cutoff, do you have anymore at the bottom there?
I have a slash timeout command, everything works, e.g. error handling for anything else, but when I try time someone out, it says "Application did not respond"
!paste
No. It stopped there. It's okay tho. I think I've mostly figured out the issue.
I'll also have to wait for it to happen again lol
as it stopped happening ;-;
It's like when you slap the side of a tv or whatever and shit just starts working again.
i mean if the bot was blocked for 10 seconds simply from json.loads, its a large string there, u might wanna use orjson for speed tbh
what the heckers is orjson?
faster json lib for python
an interaction needs at most 3 seconds to respond, when you timeout a member, its probably longer than 3 seconds which gives you "application did not respond", you can respond to the interaction beforehand through interaction.response.defer then use interaction.followup.send to send a message
Do response.defer
Does anyone have an example of a slash command working with custom convertors? I am getting an unsupported annonation type with bot.tree.command but not with bot.tree
they are called transformer
!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) 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) class. For example, to convert a string into a custom pair type:
see the example in there
tytyty
how do u load extensions now? its been a while since ive used this and looks like now you have to await the .load_extension()
I put what i had before inside the on_ready() event since that function is async and awaited .load_extension() is this the standard?
cogs = os.listdir('./cogs')
utils = os.listdir('./utils')
for x, y in [(cogs, utils)]:
for cog_file in cogs:
if cog_file.endswith('.py'):
try:
await bot.load_extension(f'cogs.{cog_file[:-3]}')
except Exception as e:
raise e
for utils_file in utils:
if utils_file.endswith('.py'):
try:
await bot.load_extension(f'utils.{utils_file[:-3]}')
except Exception as e:
raise e
i also changed the setup() functions in the cogs and awaited add_cog()
use Bot.setup_hook instead
!d discord.ext.commands.Bot.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/ext/commands/api.html#discord.ext.commands.Bot.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) 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/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
[2024-01-22 02:00:22] [ERROR ] discord.client: Attempting a reconnect in 1.94s
Traceback (most recent call last):
File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 659, in connect
await self.ws.poll_event()
File "C:\Users\Gnome\AppData\Roaming\Python\Python310\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
``` What would cause this?
can anyone help with this? ```py
async def response(self):
self.set_selection()
if self.selection != self.last_selection:
await self._serve()
try:
interaction = await self.menu.bot.wait_for("interaction", timeout=self.timeout, check=lambda e: (isinstance(e, discord.Interaction) and e.user == self.menu.ctx.author and e.message == self.menu.message))
except TimeoutError:
await self.menu.timeout(chron.long_delta(timedelta(seconds=self.timeout)))
else:
if (i := interaction.data["custom_id"]) == str(self.menu.bot.config.EXIT_EMOJI_ID):
if self.auto_exit:
await self.menu.stop()
return
elif i == str(self.menu.bot.config.STEP_BACK_EMOJI_ID):
self.page = 0
elif i == str(self.menu.bot.config.PAGE_BACK_EMOJI_ID):
self.page -= 1
elif i == str(self.menu.bot.config.PAGE_NEXT_EMOJI_ID):
self.page += 1
elif i == str(self.menu.bot.config.STEP_NEXT_EMOJI_ID):
self.page = self.max_page
await self.menu.switch()
return await self.response()
class MultiPageMenu(Menu):
async def start(self):
li = [await self.page_field]
for i in self.selector.pagemaps[self.selector.page]["fields"]:
li.append(i)
self.selector.pagemaps[self.selector.page].update({"fields": tuple(li)})
await super().start()
return await self.selector.response()
async def switch(self):
li = [await self.page_field]
for i in self.selector.pagemaps[self.selector.page]["fields"]:
if i not in li:
li.append(i)
self.selector.pagemaps[self.selector.page].update({"fields": tuple(li)})
await super().switch(self.selector.pagemaps[self.selector.page])
I mean everything is working the buttons are working fine
the pagination is working , is it switching pages but each time a button is pressed after switching the page discord is showing application failed
anyone?
Hey! I'm using discord.py, it works and login but sometime if there is some error in a cog file it ofc doesnt crashes entirely but because there was some error that command doesnt obviously but it doesnt even show what was wrong or what is the error, before when I used to use pycord everytime my command would break it would show me that this this things is wrong or an exception i should say? so why is it now showing now?
do you have logging setup? what method did you use to start the bot? bot.start?
yes bot.start or client.start
do I have to pass like logging =True?
!d discord.utils.setup_logging - you'd have to setup logging yourself or use this function
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.
New in version 2.0.
ok ok I fixed it, now its working, Thanks!
So something simple as
historical_data = {
"discord_id": existing_user["discord_id"],
"experience": existing_user.get("experience"),
"games_played": existing_user.get("games_played"),
}
await inactive_users.insert_one(historical_data)
await collection.delete_one({"discord_id": user_id})
LGTM 
It would probably be more memory efficient to have a relational db rather than (what it looks to be) a document-based one, but that's just me being pedantic
Yeah you are right, it's MongoDB
cool, thanks
anybody know why this is happening?
[2024-01-22 02:00:24] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 86e0d5927e143698382d4602ba0e641a.
[2024-01-22 03:48:26] [ERROR ] discord.client: Attempting a reconnect in 1.16s
Traceback (most recent call last):
File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 659, in connect
await self.ws.poll_event()
File "C:\Users\Gnome\AppData\Roaming\Python\Python310\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
[2024-01-22 03:48:27] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 86e0d5927e143698382d4602ba0e641a.
[2024-01-22 06:56:41] [ERROR ] discord.client: Attempting a reconnect in 0.29s
Traceback (most recent call last):
File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 659, in connect
await self.ws.poll_event()
File "C:\Users\Gnome\AppData\Roaming\Python\Python310\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
[2024-01-22 06:56:41] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 86e0d5927e143698382d4602ba0e641a.
network error is your internet acting up?
vps
vps?
Virtual Private Server.
its the internet problem as i can see
it is saying that it is trying to reconnect
Nothing I can do if it's not caused by my code
how to appcommands group work?
!d discord.app_commands.Group
does
test = discord.app_commands.Group(name="test")
@test.command(name="testing")
async def testing():
pass
will this work
no, because command callbacks take interaction
also don't forget to tree.add_command(test)
What provider?
ovh
Distro?
idk
Ubuntu?
oh windows
so how do i do it
what are u trying to do?
create a slash command?
wtf is a group slash command
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
oh okay
so instead of needing the "guild_only()" for each command, you just apply it globally
How to interaction Modal question with buttons?
A hands-on guide to Discord.py
u cant have buttons in a modal only text inputs
I am so scared to click this link
Oh god I'm so curious though too
Ok, I've seen enough... hahaha
but i saw a server has a function that interact Modal with Select menu. so i wonder if i can do that same thing. (for the verification purpose)
i have done make a Modal question and it trigger with slash command is fine, but i don't know how to interact with Buttons or Select menu.
You can create an option and when its pressed then you can
send the model to the user with
await interaction.response.send_modal()
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
Also here is an example on how to interact with it
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
why am i getting this error
More info needed. How are you invoking the package etc
Is there a way to check if a user triggered a hybrid command from a slash or text command? I tried this
if message.type == discord.MessageType.chat_input_command: but it didn't seem to work
Reversing it worked for some reason.
if message.type != discord.MessageType.context_menu_command:
How do I dm someone with the bot when I ban/kick/mute/warn them? I have troubles coding that
You just discord.Member.send()
may I have an example of it?
it makes me understand easier
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**.
Don't forget to use try/except if you are not using an error handler
Example
try:
await member.send(embed=embed)
except discord.Forbidden:
print("Not allowed to send DMs to the user.")
pass
Or however you want handle it
what are the different ways to pip install?
sudo apt install python3-pip
you can just check ctx.interaction, slash fills it, prefix makes it None
Thats easier. Thanks
Can someone please help me, I'm trying to sync my commands (and adding new slash commands) without restarting the bot using pycord. Both self.bot.sync_commands() and self.bot.register_commands() threw me an error "Application command names must be unique" while all my command names are unique.
looks like a pycord bug Pycord-Development/pycord#1383
silver-volt there mentions a workaround for it, using bot._pending_application_commands = [] before reloading the extension
Thank you!
hm, this doesn't wanna work, I'm not sure why.
uptime = datetime.utcnow() - self.start_time```
I tried self.bot and it didn't fix it either
what part of it doesn't work?
The uptime = part, for my uptime command
@app_commands.command(name="uptime")
async def slash_uptcmd(self, interaction):
"""โ๏ธ | Checks The Bots Uptime."""
uptime = datetime.utcnow() - self.start_time
upt = str(uptime).split(".")[0]
embed = discord.Embed(title='Uptime', description=f'{upt}', color=discord.Color.purple())
await interaction.response.send_message(embed=embed)```
ok, and where do you define self.start_time?
(this is not something that discord.py provides. You need to create that variable somewhere. Probably better to have it attached to Bot instead)
e.g. in your main file bot.start_time = datetime.datetime.now()
oh, that explains it, 1 moment
i alr removed the old command and switched it with a group it still giving error
hmmm
its app commands btw
then what the hmmm for
nothing i was just looking for one of my frnd which i last saw here
u are not him anyway he came here to solve m doubts nnot to ask from me
it still give error
what are a beginner or an itermidiate
in the middle
ic
beginner is someone new
when u started?
june 2023
no
@slate swan u still exist?
He does
so is this error
thts nice to hear
Time to find more developers for bobux
can u help this guy
am not a bot dev so i cant help him
You sure you don't have duplicated command in some other cog? Try searching entire project for "tinyurl"
Tried searching?
yes
There are 2 groups named tinyurl?
no
Where's second result
I guess
whats 'bobux' ......
u still guess?
it was befire called shorten url but i wanted it as group i made it a group but it gave error so i even changed the name of the group still
Ah
what are u making anyway?
url shortner
Okay let's do it the hard way ๐
Please send full traceback
ok

Hopefully I can solve this before I need to go
@fiery girder in api.py setup, add this line
print("\n".join(f"{c.cog_name} - {c.qualified_name}" for c in bot.walk_commands()))```
And oops I need to go
but where
Ping me with this I will return to this later
api.py setup function right before adding API cog
ok
Is there a Google translate library that I can use to create a command for my bot?
it just shows a empty line @vale wing
!d translators
No documentation found for the requested symbol.
there is a pacakge calls translators tho
or you can use google official but the docs arent in python so its hard to figure
i think you forgot tree
thes are all appcommands
i fixed it
Prob
i fixed it
What was the cause
some guy from this discord was helping me and said you need to do self.bot.tree.add_command(group) so i did that caused it to malfunction
Oh yeah
Because it looked like a command defined in the main file (no self parameter). You don't need to do that when within cogs
Hi, in discord.py, how do I disable automatic reconnection if the bot was forcefully disconnected?
2024-01-23 20:26:34 INFO discord.voice_client Disconnected from voice by force... potentially reconnecting.
2024-01-23 20:26:34 INFO discord.voice_client Starting voice handshake... (connection attempt 2)
2024-01-23 20:27:34 INFO discord.voice_client The voice handshake is being terminated for Channel ID 1199359436997808209 (Guild ID 1003940162046263347)
2024-01-23 20:27:34 INFO discord.voice_client Reconnect was unsuccessful, disconnecting from voice normally...
Is there a way to get every message in a channel?
If there are not many messages you can just use history
Otherwise bot will be fetching them forever and you typically never need that
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples
Usage...
Are you sure it's forced? Why would that happen?
wait
this "Disconnect" button
Oh so bot automatically reconnects if you disconnect it as mod
no it doesn't?
Does it actually reconnect or there's just this message
no
This I mean
About reconnection attempt
it doesn't reconnect
Then there's nothing to worry about
2024-01-23 20:27:34 INFO discord.voice_client Reconnect was unsuccessful, disconnecting from voice normally...
"Reconnect was unsuccessful"
^
okay
but few music commands dont work
Hi, how do I do this? I want to enter a command and the bot will ask what is your name? After my reply, the bot remembers it. When re-entering the command. the bot outputs my name. Also, how can I change my name in the database in the bot, for example, if I made a mistake
Player: !team
Bot: Hi, what's your name
Player: Steve
Bot: I remember it well
Player: !team
Bot: Hi Steve!
well, also delete the name if the player made a mistake
I don't think it is related to the log entry
I this AI? Or you just need persistent data storage?
To be honest, I do not know. Here is an example of a bot asking for my quote, I wrote it and it saved it.
Yeah you need persistent data storage, a database for example
understood, but how to do it?
Well if you got no experience of working with them, I recommend checking #databases pins for learning resources
thank you very much. Good luck and good health โค๏ธ
You too comrade
Could someone help me correct this code?
Itโs for a discord slash command called** /Giveaway (time) (prize) (emoji)**
The error message is the image
from discord.ext import commands
import random
import asyncio
import os
from discord.utils import get
import re
import itertools
import requests
import schedule
import time
intents = discord.Intents.all()
client = commands.Bot(command_prefix="/", intents=intents)
@client.event
async def on_ready():
await client.tree.sync()
await client.change_presence(activity=discord.Game(name="Playing Forever Long SMP"),
status=discord.Status.online)
print(f"{client.user.name} is now online")
@client.tree.command(name="giveaway", description="creates a giveaway")
async def giveaway(ctx, duration_seconds: int, *, prize: str):
if duration_seconds <= 0:
await ctx.send(f"Invalid duration. Please specify a positive number of seconds.")
return
embed = discord.Embed(
title="๐ **Giveaway started!** ๐",
description=f"Prize: {prize}\nDuration: {duration_seconds} second(s)\nHosted by: {ctx.user.mention}\n\nReact with ๐ to participate!",
color=discord.Color.blue()
)
message = await ctx.send(embed=embed)
await message.add_reaction('๐')
await asyncio.sleep(duration_seconds)
message = await ctx.channel.fetch_message(message.id)
reaction = discord.utils.get(message.reactions, emoji="๐")
participants = [user for user in await reaction.users() if user != client.user]
if participants:
winner = random.choice(participants)
winner_embed = discord.Embed(
title="๐ **Giveaway ended!** ๐",
description=f"Prize: {prize}\nWinner: {winner.mention}",
color=discord.Color.blue()
)
await ctx.send(embed=winner_embed) ```
The error is message = ctx.send(embed=embed) as it shows in the command prompt.
What would be the correct code to replace it?
Can someone else do this? I cant for another 4 minutes
tree commands receive a discord.Interaction object rather than the context object you're used to, so you'll need to use the interaction.response.send_message() method instead (and consider renaming ctx to interaction for clarity)
see also: https://fallendeity.github.io/discord.py-masterclass/slash-commands/#sending-responses
Thanks
So every time it says ctx also replace it with interaction
well its not only renaming, since context and interaction have different attributes/methods which you'll need to take into account
does replit have type checking? that'd make it a lot easier to know when you're misusing parameters, assuming said parameter is type hinted
@proud schooner oh yeah, member.status returns a discord.Status enum so if you want to check for a specific status, you'll need to compare it to a member of that enumeration directly, for example member.status == discord.Status.offline
Yeah, iโve just home. The error is AttributeError: โstrโ object has no attribute โstatusโ
Iโve looked a few places for a fix and couldnโt find one.
oh your user variable is literally a string...
Yeah thats what i meant
what user are you trying to refer to?
you just want to check for a member's status by their ID?
Yeah thats basically it
you'll need to retrieve their member object from a guild that they're in using Guild.get_member(), which also requires having the members and presences intent enabled in your client
if it returns the member object, you can then check their .status as usual
there's a bit more complexity to it, more specifically that discord doesnt send offline member objects for "large" guilds, i.e. 250+ members as set by discord.py, but in short if get_member() returns None you should assume that user is offline
I did this. The new code is -
@client.tree.command(name = "giveaway", description = "creates a giveaway")
async def giveaway (Interaction, duration_seconds: int, *, prize: str):
if duration_seconds <= 0:
await Interaction.response.send_message(f"Invalid duration. Please specify a positive number of seconds.")
return
else:
message = await Interaction.response.send_message(embed=discord.Embed(
title="๐ **Giveaway started!** ๐",
description=f"Prize: {prize}\nDuration: {duration_seconds} second(s)\nHosted by: {Interaction.user.mention}\n\nReact with ๐ to participate!",
color=discord.Color.blue()
))
await Interaction.message.add_reaction('๐')
await asyncio.sleep(duration_seconds)
message = await Interaction.channel.fetch_message(message.id)
reaction = discord.utils.get(message.reactions, emoji="๐")
participants = [user for user in await reaction.users() if user != client.user]
if participants:
winner = random.choice(participants)
winner_embed = discord.Embed(
title="๐ **Giveaway ended!** ๐",
description=f"Prize: {prize}\nWinner: {winner.mention}",
color=discord.Color.blue()
)
await Interaction.response.send_message(embed=winner_embed)
And the error is in the image -
AttributeError: โnonetypeโ objective has not attribute โadd_reactionโ
yeah it's a bit weird, send_message() doesn't return a message object like you would expect due to a discord API limitation
you'll need Interaction.original_response() to retrieve the message after it was sent
actually i'm not sure if calling original_response() updates the reaction count given that it gets cached...
btw speaking of count, you can use reaction.count to get the total for that reaction rather than looping through reaction.users() which makes an unnecessary API call
So I should replace send_message() with Interaction.original_response() and see if that works?
er no, original_response() is how you retrieve the message sent by send_message()
the caching issue might make that approach a problem though...
What would you recommend doing?
also another sidenote, send_message() can't be used twice in a row because discord only allows one response, as such any followup messages should be done using the followup webhook
https://fallendeity.github.io/discord.py-masterclass/slash-commands/#sending-followups
Yeah it gets the user. I then further carried on the command after testing it. i requested and it worked. I appreciate your help.
given what you already know, you might find it easier to give an ephemeral response telling the command user that the bot is setting up the giveaway, then get the discord.TextChannel object from the interaction.channel attribute to send the giveaway message, as that will work similarly to the code that you used to have
in other words it might look like: ```py
await interaction.response.send_message("Starting giveaway...", ephemeral=True)
message = await interaction.channel.send("This is the giveaway!")
... # Wait for reactions, then fetch the users that reacted:
participants = [user async for user in reaction.users() if ...]
Pick winner as you used to, and use interaction.channel.send() to show the winner```
note: i missed the random.choice(participants) part and thought you just wanted the number of people that reacted, so ignore what i mentioned earlier about reaction.count
yet another note: the await reaction.users() syntax had a breaking change with discord.py 2.0 so it's outdated now, hence why i'm showing async for in the example
https://discordpy.readthedocs.io/en/stable/migrating.html#moving-away-from-custom-asynciterator
Youโve confused me? Could u show me where to put this into the code?
Sorry
Hey! I have a modal that requests 3 text inputs, one of those is server invite link, it is not required because I thought I could generate a server invite myself, but struggling with that. I have not found a method on discord.Guild that would create an invite, and using await interaction.channel.create_invite() results in a 404: Unknown Channel. How could I fix that? Or do I have to force invite link from the user in the modal?
Try printing out interaction.channel. It being an unknown channel is strange
prints its name just fine
wait what
this time it didnt do 404, but another error
File "D:\bogdan\p\pikastats\venv\lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
await self.on_submit(interaction)
File "D:\bogdan\p\pikastats\cogs\guild.py", line 141, in on_submit
await channel.send(embed=embed)
TypeError: send() takes no keyword arguments```
since when does send take no kwargs ๐
I removed the adding reaction so it could just out the member that just pur the reaction there themselves . The code -
@client.tree.command(name = "giveaway", description = "creates a giveaway")
async def giveaway (Interaction, duration_seconds: int, *, prize: str):
if duration_seconds <= 0:
await Interaction.response.send_message(f"Invalid duration. Please specify a positive number of seconds.")
return
else:
message = await Interaction.response.send_message(embed=discord.Embed(
title="๐ Giveaway started! ๐",
description=f"Prize: {prize}\nDuration: {duration_seconds} second(s)\nHosted by: {Interaction.user.mention}\n\nReact with ๐ to participate!",
color=discord.Color.blue()
))
await asyncio.sleep(duration_seconds)
Interaction.channel.fetch_message(message.id)
reaction = discord.utils.get(message.reactions, emoji="๐")
participants = [user for user in await reaction.users() if user != client.user]
if participants:
winner = random.choice(participants)
winner_embed = discord.Embed(
title="๐ Giveaway ended! ๐",
description=f"Prize: {prize}\nWinner: {winner.mention}",
color=discord.Color.blue()
)
await Interaction.response.send_message(embed=winner_embed)
And it still got a error โnonetypeโ objective has no attribute โidโ @hushed galleon
!code
How can you delete messages in bulk without getting ratelimited?
@proud schooner you need to await bot.fetch_guild i believe.
I will give it a shot and lyk.
cool ๐
I got ratelimited with purge as well
Maybe need to add sleep in between
It comes up at โguildโ is not defined in vscode, thats trying to define the guild. The guild is fetching from a guild id (gid)
Okay so the problem iโm getting is i havenโt defined guild beforehand. Thats me trying to define guild.
what happens when you run it?
you also need @bot.event on the on_ready call i believe.
(that might be why guild isnt defined, because it isnt running)
ignore the rate limits 
discord.py preemptively sleeps before hitting them anyway
my ip has been temporarily banned, do not ignore the rate limits. Granted, I was triggering a lot of them but i would not take the risk.
(its not anymore in case that wasnt clear)
thats really weird, i have almost the exact same code and it doesnt error out.
it works fine if i don't define guild, when i try to define guild it won't let me run it.
guild = await bot.fetch(gid) not the other way around.
That might be why..
you must've fucked up real bad then. discord.py sleeps before getting a 429 by looking at the rate limit headers for (iirc) X-requests-remaining and X-retry-after. under normal circumstances you would not get IP banned, at least not with discord.py
yeah, i was messing around with some silly things on a private server.
the only thing that could mess with this is having multiple bots on the same IP address and they adding up to the global 50request/1s ratelimit, but that only happens in like repl.it shared IPs
dont underestimate the power of pure determination and ignorance
I am... concerned
Okay, thank you guild is now defined. It was a stupid ass error on my half and I appreciate the help, I'm going to try figure out the rest of this now, thanks again!
cool, happy to help :)
Hey one quick question. I was wanting to @task.loop() something but I donโt want it to end up spamming the channel unless my discord status changes, do you know how i could do that?
to my understanding fetch_member() doesn't return any activity/status because the API doesn't provide that, so it has to be retrieved from cached members that dpy receives from the gateway
and get_member() only works on cached guilds rather than one retrieved with fetch_guild()
iirc you can at least get whether the user is online.
so you want to run a task and do what when your discord status changes?
Change a channel permission and send a message to a channel
having had a quick look though the docs, i just dont think discord.py has the listeners for this so you'll just have to loop your task and check each time.
if you really need it like this there might be a better solution
doesn't seem so
wdym? isnt this what i said?
cached Member.status is updated by discord.py through listening to on_presence_update since none of that is gettable through rest api
it shows my status as offline despite it not being so
ooooooh thats a listener?
@proud schooner you can use that then i think
!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...
alr looked up in the docs
yeah, but for the other person :)
fair enough
So how would I go about doing it?
Wing it and see where i end up?
ye, just have a search around a see what you find. It should look something like this:/
@bot.event
async def on_presence_update(before, after):
...
seems pretty straightforward, what have you tried so far?
account_name = discord.ui.TextInput(label="The account name", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
notable_items = discord.ui.TextInput(label="Account notable items", placeholder="", required=True, max_length=50, style=discord.TextStyle.short)
sell_for = discord.ui.TextInput(label="Price", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
extra = discord.ui.TextInput(label="Extra", placeholder="", required=False, max_length=20, style=discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting we will be with you as soon as possible!", ephemeral=True)
channel = discord.utils.get(interaction.guild.channels, name="application")
embed = discord.Embed(title='Application', description=f'Application Submitted By: {interaction.user.mention}')
await channel.send(embed=embed)
@bot.tree.command(name="account", description="Apply to sell")
async def account(interaction: discord.Interaction):
await interaction.response.send_modal(AccountModal())```
*I want to add a command that sends a embed with a button on it and then it pops up the modal i already coded can someone help me?*
discord.User.id is not a valid way of accessing that user's id. You would use either before or after.id
discord.X will never refer to a specific instance/object of X. That's the class
The same can be said for any class
def __init__(self, app: str):
super().__init__()
self.app = app
self.add_item(discord.ui.Button(label="Just a Test"))
@discord.ui.button("Test Btn", style=discord.ButtonStyle.blurple)
async def applyBtn(self, interaction: discord.Interaction):
await interaction.response.send_message(self.app, ephemeral=True)
@bot.command()
async def apply(ctx: commands.Context):
app = await ctx.channel.send()
embed = discord.Embed(title="Apply at ", description=f"Press the button below to apply!")
await ctx.send(embed=embed, view=ApplyButtons(str(app)))
class AccountModal(discord.ui.Modal, title=""):
account_name = discord.ui.TextInput(label="", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
notable_items = discord.ui.TextInput(label="", placeholder="", required=True, max_length=50, style=discord.TextStyle.short)
sell_for = discord.ui.TextInput(label="", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
extra = discord.ui.TextInput(label="", placeholder="n", required=False, max_length=20, style=discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting we will be with you as soon as possible!", ephemeral=True)
channel = discord.utils.get(interaction.guild.channels, name="application")
embed = discord.Embed(title='Application', description=f'Application Submitted By: {interaction.user.mention} \n Account Name: {self.account_name} \n Notable: {self.notable_items} \n Price: {self.sell_for} \n Extra: {self.extra}')```
i want a modal to pop up when a user clicks the button on the embed but i dont know how to do that this is my code can somsone help me?
You'd do await interaction.response.send_modal(ModalClass())
In applyBtn, that is
Can you show your new code
It's just await interaction.response.send_modal(AccountModal())
Right now discord doesn't know what modal you want to send
Yo I need help
it says something like @bot.command() expected an indented after function
You need to put a function under decorator, like this
@bot.command()
async def my_command(ctx):
await ctx.send("Hi")
Bro
Theres a new problem that im facing can u help
Describe your problem
So like do u know Roblox
The game? Sure
dm me ill send the problem
No
You can describe the problem here
Are you using some tutorial or something
no
Most of them are outdated and the only reliable way is to refer to documentation
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
double check these
they should be on
I did
NVM
I FIXED IT tysm
Ayo exploit ๐๐
@final iron accept my friend request plz ๐
i can already see what you're going to do
Yes snipy how perspicacious of you ๐
bruh
Anyone seen sarth recently?
def __init__(self, app: str):
super().__init__()
self.app = app
self.add_item(discord.ui.Button(label="Just a Test"))
@discord.ui.button("Test Btn", style=discord.ButtonStyle.blurple)
async def applyBtn(self, interaction: discord.Interaction):
await interaction.response.send_modal(self.app, ephemeral=True)
@bot.command()
async def apply(ctx: commands.Context):
app = await ctx.channel.send()
embed = discord.Embed(title="Apply at rbxaccs", description=f"Press the button below to apply!")
await ctx.send(embed=embed, view=ApplyButtons(str(app)))
class AccountModal(discord.ui.Modal, title="Sell your account!"):
account_name = discord.ui.TextInput(label="The account name", placeholder="eg. exploit", required=True, max_length=20, style=discord.TextStyle.short)
notable_items = discord.ui.TextInput(label="Account notable items", placeholder="eg. epic face", required=True, max_length=50, style=discord.TextStyle.short)
sell_for = discord.ui.TextInput(label="Price", placeholder="eg. $200", required=True, max_length=20, style=discord.TextStyle.short)
extra = discord.ui.TextInput(label="Extra", placeholder="eg. extra information", required=False, max_length=20, style=discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting we will be with you as soon as possible!", ephemeral=True)
channel = discord.utils.get(interaction.guild.channels, name="application")
embed = discord.Embed(title='Application', description=f'Application Submitted By: {interaction.user.mention} \n Account Name: {self.account_name} \n Notable: {self.notable_items} \n Price: {self.sell_for} \n Extra: {self.extra}')
await channel.send(embed=embed)```
Error is I cant send an empty message? I want the button to be clicked then the modal pops up
!traceback send the 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.
Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\RHG\Documents\rbxaccs\main.py", line 23, in apply
app = await ctx.channel.send()
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\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: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
so i have this lfg modal code:
async def on_submit(self, interaction: discord.Interaction):
category_name = "Games"
category = discord.utils.get(interaction.guild.categories, name=category_name)
vc_name = f"{self.game} - {interaction.user.display_name}"
vc = await category.create_voice_channel(vc_name)
ck = discord.Embed(title= f'Description: {self.info}', timestamp= datetime.now(), type='rich', color=discord.Color.random())
ck.add_field(name=' Game',value=f'{self.game}', inline=True)
ck.add_field(name=f' Game Mode',value=f' {self.type}', inline=True)
ck.add_field(name=f' Region',value=f'{self.region}', inline=True)
ck.add_field(name=' VC/Lobby Space', value=f'{len(vc.members)}/{vc.user_limit} members in VC right now!')
ck.set_footer(text='use /invite to create your own game invite!')
invite = await vc.create_invite(max_age=0, max_uses=0, unique=True)
ck.add_field(name=f'**{vc.name} | {vc.category}** ', value=f'**[Click here to join]({invite.url})** ', inline=True)
ck.set_author(name=f' {interaction.user.display_name} is looking for party members!', icon_url=f'{interaction.user.guild.icon}', url = 'https://discord.com/users/' + str(interaction.user.id))
ck.set_thumbnail(url=f'{str(random.choice(list))}')
await interaction.response.send_message(embed=ck)
await interaction.user.edit(voice_channel=vc)
await vc.set_permissions(interaction.user,manage_members=True,move_members=True,moderate_members=True)```
everything works fine but it gives an error saying "Target user is not connected to voice." i was initally using `await interaction.user.edit(voice_channel=vc)` but that doesnt work so what's a way of adding a user to a voice channel
i want to add a user to a vc without them being in a vc previously
@naive briar can you add me? Got a personal invitation for you
Sounds suspicious
๐๏ธ๐๐๏ธ
It's an invitation to semi-closed source bot dev team
I'm not into bot dev currently, so no
Ok
there's an intruder among sus
you're too shady lmao
how do I do a timeout command ?
Your own timeout command or the built-in one?
That happens
i was convincing someone promising to give him fake candies
my own
Snipy turned into white van kidnapper
let him cook
y do you need one sure, you will need a database and background loop with tasks.loop
my boss annoying thanks, i think ill choose the builtin one, how do I make it?
i want to add a user to a vc without them being in a vc previously
You can't do this. They have to be in a vc already, in which case you can move them to another VC
@discord.ui.button("Test Btn", style=discord.ButtonStyle.blurple)
async def applyBtn(self, interaction: discord.Interaction):
- await interaction.response.send_modal(self.app, ephemeral=True)
+ await interaction.response.send_modal(AccountModal())
Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\RHG\Documents\rbxaccs\main.py", line 23, in apply
app = await ctx.channel.send()
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\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: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
still getting this
You're sending an empty message on line 23
app = await ctx.channel.create_apply()
why doesnt this work? what would i replace with it so its not 'empty'
I'm not sure what create_apply is. It's not a method that exists for TextChannel objects
i dont know what to put so i just tried that
Hey i have a bot that creates pictures with pixels. This is the first print but i wanna train and improve it. The bot is currently selecting a sample visual from the database and changing it but what i want to do is that when it changes the picture, it detects it when i press the yes or no buttons that appear underneath it it will regenerate a image. if i press the yes button it will say ''ahh he like this image and that's how I need to do the next pictures''. (This is cringe ik but dont know how to explain it :D) any idea, video, article? (please ping me <3)
If I import something in my main file does that cover it for cogs too or do I have to import from inside the cog
you need to import it in each python file where you want to use it.
Ok thanks
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
currently making a bot which screenshots an html page
<style>
* {
margin: 0;
padding: 0;
}
@font-face {
font-family: 'Whitney';
src: url('fonts/Whitneyfont.woff') format('woff');
}
@font-face {
font-family: 'WhitneyMedium';
src: url('fonts/Whitneymedium.woff') format('woff');
}
body {
background-color: #36393f;
font-family: 'Whitney', sans-serif;
}
.whitney-medium {
font-family: 'WhitneyMedium', sans-serif;
}
</style>
the html isnt changing to my desired font in the screenshot
instead of whitney its changing to sans serif and idk why/how to fix or change it
Thats cool
Not a python question but check browser console to find out if some fonts are not found, might be bad path
any reason ur not using some existing package?
alright ty if they arent is there a way i can verify its the correct path etc
anyone here know digital art anyhow?
That doesn't sound to be related to Discord bots
sry about tht
!e
a = 1
print(a*100)
@vital axle :white_check_mark: Your 3.12 eval job has completed with return code 0.
100
You can use on_command_completion
Thanks. Iโll give it a shot!
Thank you!
!e
code
!e
a = 10
e = 20
b = 50
print("a+b+e*1000)```
@timid sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 4
002 | print("a+b+e*1000)
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 4)
!e
a = 10
e = 20
b = 50
print("a + b + e * 1000)โ```
@timid sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 4
002 | print("a + b + e * 1000)
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 4)
@simple surge :white_check_mark: Your 3.12 eval job has completed with return code 0.
even numbers: 30
Haven't used the api but they have documented everything nicely with examples https://codeforces.com/apiHelp/methods
If you need help you can ask it here itself
You're more likely to get help in the server than dms
๐
my interaction.response.send_message dont work
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/python.py", line 62, in select_callback
await interaction.response.send_message(f"Hienoa! Pidรคn myรถs {select.values[0]}:sta!")
AttributeError: 'Select' object has no attribute 'response'```
Sun functio parameterit on varmaan vรครคrin pรคin discord.pyssa interaction on ekana ja select tokana (toisin pรคin muissa libraryissa)
cause your interaction is not an actual Interaction object
its Select object
please help code doesn't work, no errors
import io
from PIL import Image, ImageDraw, ImageFont
from nextcord.ext import commands, tasks
class Banner(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
self.update_banner.start()
self.last = 0
@tasks.loop(minutes=1)
async def update_banner(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(1048990513568686080)
with Image.open("Banner.png") as img:
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("Gilroy-Medium.ttf", 130)
total = len(guild.members)
voice = len([m for m in guild.members if m.voice])
# check if the voice count is different from the last value
if voice != self.last:
x = 1040 #945
y = 300 #400 #311
draw.text((x, y), str(voice), font=font)
img_bytes = io.BytesIO()
img.save(img_bytes, format="png")
img_bytes.seek(0)
bytes = img_bytes.read()
# use banner_url instead of banner
await guild.edit(banner_url=bytes)
# save only the voice count
self.last = voice
def setup(bot):
bot.add_cog(Banner(bot))
What's the decorator for giving slash command params descriptions?
Idk if this is the most ideal way to debug, but put a bunch of print statements. If the print statement runs it means the code above has run.
This doesn't necessarily mean the code above is working as intended, it just means the code above might not be where the error lies. You'd also want to print the variables above the print statement to ensure it's storing the expected value
app_commands.describe
ty ty
Does discordpy have a param thingy for dates/datetime?
Like how it does for things like channels, users and true/false?
No, you need to make your own
;-;
This is harder to implement than you think if one would want it implemented into the library itself
So what you're saying is.. I could do /remindme date:<date> and the <date> is calender picker?
Because you need to take into consideration different date formats and shit. For example most of the western world uses dd/mm/yy, but the united has it backwards. So like 10/12 would mean the 10 of December for most people, except some
So you need to take some biased decisions implementing this, that could mildly inconvenience some people
(the code itself for parsing a date is trivial tho)
No, discord doesn't have they either
I fucking wish they did.
D:
Same ๐ญ

I haven't used timestamps with bots in ages so I don't really remember what does and doesn't work, but can bots use timestamps like <t:1706269244:R>. in Embeds, specifically in field values and footers?
yeah, think you're thinking of Embed.timestamp
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
for others
okay thanks
using my old discord code to fix some stuff, have to instal easy_pil but i get this error whats it mean?
Need full traceback, please paste as text
!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.
But I suspect it's cause ms build tools are not installed
doesnt aiohttp already have 3.12 wheels though? why is it trying to build from (a presumably outdated) source?
How do I get how many users are in my server?
it's something like guild.get_users() right?
guild.member_count
lol that simple huh?
as per docs, you'll also need member caching nvm just the intents for join/leave events if you want member_count to stay in sync after on_ready
How can I make the bot delete any discord link without deleting my own servers link?
assuming you have an invite regex, you can compare the invite code against some whitelist
or if you want to support any valid invite, like those created by users, you can use Client.fetch_invite() to verify that it points to your server
not with a simple api call, you'd either need to start fetching messages until you find (or don't find - this can end up as a very big pointless search) a message from them, please don't do that, or you listen for messages from when your bot joins the server and just go from there, storing the message or whatever your usecase is, as you see them
maybe one day, discord's API could open the search functionality to bots
How can i make bot
!e
code
!e for i in range ("1,1000")
print("Hello, World!")
@timid sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | for i in range ("1,1000")
003 | ^
004 | SyntaxError: expected ':'
!e for i in range ("1,1000");
print("Hello, World!")
@timid sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | for i in range ("1,1000");
003 | ^
004 | SyntaxError: invalid syntax
!e for i in range ("1,1000"):
print("Hello, World!")
@timid sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | print("Hello, World!")
003 | ^
004 | IndentationError: expected an indented block after 'for' statement on line 1
#bot-commands next time btw
What the problem?
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
!d discord.ext.commands.Bot ideally you should use this tho
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
from discord.ext import commands and then commands.Bot()
im making a discord bot integrated with the google classroom api. its my first time working making a discord bot and i kinda need help on it
mainly with authentication
AttributeError: 'PartialMessage' object has no attribute 'embeds'
dm_message = client.get_partial_messageable(case["dm_channel_id"]).get_partial_message(
case["dm_message_id"])
embed = dm_message.embeds[0]
await dm_message.edit(embed=embed)
Why can't I edit the embed?
a partial message is basically just an ID
for when you don't need any information.
!d discord.PartialMessageable.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
So I should remove embed = dm_message.embeds[0]?
if you don't need it, yes. if you are planning to edit that embed, you will need to actually retrieve it thru fetching
I need to fetch it just because I want to edit it? That won't apply if I want to delete it iirc
if (need to access data from message) -> you fetch
so no, not for deleting/editing/etc by itself.
Do you know what this could be?
# Fetch the channel and message using the action_log message ID
channel = client.get_channel(745832392404762695)
message = await channel.fetch_message(case["action_log"])
# Update the embed with the new reason
message_embed = message.embeds[0] # Assuming there is only one embed in the message
message_embed.set_field_at(index=3, name="Reason", value=new_reason, inline=False)
# Update the message with the modified embed
await message.edit(embed=message_embed)
Traceback (most recent call last):
File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "D:\discord bots\blitzcrank.py", line 2857, in set_reason
message_embed.set_field_at(index=3, name="Reason", value=new_reason, inline=False)
File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\embeds.py", line 704, in set_field_at
raise IndexError('field index out of range')
IndexError: field index out of range
Your embed has less than 4 fields.
you're trying to modiy the fourth field (3) and there isn't one.
What does this mean?
Traceback (most recent call last):
File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "D:\discord bots\blitzcrank.py", line 2908, in set_reason
await dm_message.edit(embed=embed, view=view)
File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\message.py", line 983, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, params=params)
File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In channel_id: Value "None" is not snowflake.
In message_id: Value "None" is not snowflake.
can you show your code? seems quite weird for dm_message to not have a channel or message ID unless you created a partial message or something
Nvm it was because they were None in the database
I simply changed it to:
if "dm_channel_id" in case and "dm_message_id" in case and case["dm_channel_id"] is not None and case[
"dm_message_id"] is not None:
@client.tree.command(description='List of all Franchise Owners')
async def folist(ctx):
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.user.roles)
mapping = {
role: discord.utils.get(ctx.guild.emojis, name=emoji.strip(":"))
for role, emoji in zip(nflRoleListNames, nflEmojiListNames)
}
emoji = mapping.get(teams.name)
client.memberList = []
nflRoleNum = range(len(r.nflRoleListNames))
nflRoleList = []
i = 0
for i in nflRoleNum:
role = discord.utils.get(ctx.guild.roles, name=r.nflRoleListNames[i])
nflRoleList.append(role)
i = i + 1
role = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
empty = True
for member in ctx.guild.members:
if role in member.roles:
userRoleSet = set(member.roles)
teamRoleSet = set(nflRoleList)
currentTeam = userRoleSet.intersection(teamRoleSet)
if currentTeam == set():
currentTeam = "No Team Detected"
else:
currentTeam = list(currentTeam)
currentTeam = currentTeam[0].mention
client.memberList.append(
f"{emoji }{currentTeam} - {member.mention} `{member}`")
empty = False
if empty:
await ctx.response.send_message(f"There are no franchise owners.", ephemeral=True)
return
foNum = len(client.memberList)
embed = discord.Embed(title="Franchise Owners",
description='\n'.join(client.memberList))
embed.add_field(name="Amount", value=f"{foNum}/32")
embed.set_thumbnail(url=ctx.guild.icon)
embed.set_author(name=f"{ctx.guild.name}", icon_url=ctx.guild.icon)
await ctx.response.send_message(embed=embed, ephemeral=True)```
how do i make it where it puts the emoji that connects with the current team like the image, ik it checks for the role in the user so im tryna figure out how to make it where it its like the pic
Action on message edit?
Basically when someone wins a game I want it to edit the message that was sent in the logs channel. I know it's possible but my brain is ๐ฉ when it comes to things i've not got the grip of or learnt.
I know self.edit_original_reponse would work but it's as a async so self is not supported.
Associate the sent message object with some game ID or store it in the game, like
async def log(...):
...
return await channel.send(...)
I don't know how you handle games so can't provide example code for the storage itself
Key thing is you can store message object
Not persistently but I assume you don't need it to be persistent
It's not a proper game, it's just a discord bot coded game. I might remove the async and just do it so it will edit original response.
Sorry, that's incredibly hard to read. Why don't you use roles IDs
channel.send is not an interaction send, it's common message send
would that work?
๐ง
I'll try it
I don't get how this is related
Your log must return the message, you store that message, when need to edit, just access it
So how would i log it?
Again, I don't know how you handle the game. Probably like this
msg = await log("uncool text")
handle_game_or_whatever()
await msg.edit("cool text")
As i said its a discord coded bot itโd have to be logged in a json file or?
It's a discord bot coded in python, this is python code
Don't get where the issue is
And how is json related to this
Could you show your game code
Basically iโm asking its all fully coded in python. No game related so would i have to log the log in json and read the json file?
^
I don't understand anything from your descriptions, sorry
The game code was fully made in discord.py. There is no game it links to.
Let me get the code
I'm aware of that
@bot.tree.command(name="mines", description="mines")
async def mines(interaction: discord.Interaction, mines_amount: int, bet: str):
valid = True
uid = str(interaction.user.id)
bet = suffix_to_int(bet)
if mines_amount >= 25 or mines_amount <= 0:
valid = False
embed = discord.Embed(title=":x: Error",
description="Invalid Number Of Mines",
color=0xff0000)
embed.set_author(name="Bot Central",
icon_url="https://cdn.discordapp.com/icons/1189054412459622400/b8533545e1e91a4ca2ada9f4d5a4e1.png?size=4096")
embed.set_footer(text="games")
await interaction.response.send_message(embed=embed)
return
if valid:
subtract_gems(uid, bet)
af = get_affiliate(str(interaction.user.id))
add_gems(af, bet * 0.1)
board = generate_board(mines_amount)
userboard = [
["", "", "", "", ""],
["", "", "", "", ""],
["", "", "", "", ""],
["", "", "", "", ""],
["", "", "", "", ""],
]
coollooking = '\n'.join([' '.join(sublist) for sublist in board])
await log(f"{interaction.user.name} Started A Mines Game! Board:\n\n{coollooking}")
await interaction.response.send_message(
content=f":moneybag: **Winnings:** ``{add_suffix(bet * 0.80)}`` :star: **Multiplier:** ``0.80``",
view=MinesButtons(bet=bet, board=board, bombs=mines_amount, interaction=interaction, usersafes=0,
userboard=userboard, exploded=False))```
Okay, so the game is handled in MinesButtons view I presume?
That is correct.
When does it finish? When you press sort of end button?
When it finishes you have to press a button let me get that bit of the code.
async def button_cashout(self, interaction: discord.Interaction):
if interaction.user.id == self.interaction.user.id:
multi = round(calculate_mines_multiplier(
self.bombs, self.usersafes, MineHouseEdge), 2)
add_bet(str(interaction.user.id), self.bet, round(self.bet * multi))
bet = self.bet
winnings = self.bet * multi - bet
total = winnings + bet
add_bet(str(self.interaction.user.id), bet, winnings )
await self.interaction.edit_original_response(
content=f":star: Cashed Out! (**Profit:** ``{add_suffix(round(winnings))}``, **Multiplier:** ``{multi}``\n Total: ``{total}``)",
view=MinesButtons(bet=self.bet, board=self.board, bombs=self.bombs, interaction=self.interaction,
usersafes=self.usersafes, userboard=self.userboard, exploded=True))
All you need to do is make your log return message, add the message attribute to your view, and just access it in finish callback
is that in this button_cashout?
class MinesButtons(View):
def __init__(..., msg: discord.Message):
super().__init__(...)
self.msg = msg
async def button_cashout(...):
await self.msg.edit(...)
Pseudo
Im shit at discord.py idk what goes in the โฆโs ๐ญ
because its a public bot
I gave you pseudocode, ... means something that you have and does matter in your actual code but does not matter when explaining this certain aspect
I get you now.
You'd typically use a database for that
not really good with databases so i just found an easier way
There are also some weird constructions like
for i in range(...):
...
i += 1
One question tho, how exactly are emojis connected to roles? Are those role icons? Or do you define the emojis by yourself
i have a list of emojis names and also the roles so it like checks both and finds what names are connected
idk how to explain it without in sounding confusing
i am
Even code looks confusing
nflRoleListNames = [
"Arizona Cardinals", "Baltimore Ravens", "Atlanta Falcons",
"Buffalo Bills", "Carolina Panthers", "Cincinnati Bengals",
"Chicago Bears", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos",
"Detroit Lions", "Houston Texans", "Green Bay Packers",
"Indianapolis Colts", "Los Angeles Rams", "Jacksonville Jaguars",
"Minnesota Vikings", "Kansas City Chiefs", "New Orleans Saints",
"Las Vegas Raiders", "New York Giants", "Los Angeles Chargers",
"Philadelphia Eagles", "Miami Dolphins", "San Francisco 49ers",
"New England Patriots", "Seattle Seahawks", "New York Jets",
"Tampa Bay Buccaneers", "Pittsburgh Steelers", "Washington Commanders",
"Tennessee Titans"
]
nflEmojiListNames = [
":Arizona_Cardinals:", ":Baltimore_Ravens:", ":Atlanta_Falcons:",
":Buffalo_Bills:", ":Carolina_Panthers:", ":Cincinnati_Bengals:",
":Chicago_Bears:", ":Cleveland_Browns:", ":Dallas_Cowboys:",
":Denver_Broncos:", ":Detroit_Lions:", ":Houston_Texans:",
":Green_Bay_Packers:", ":Indianapolis_Colts:", ":Los_Angeles_Rams:",
":Jacksonville_Jaguars:", ":Minnesota_Vikings:", ":Kansas_City_Chiefs:",
":New_Orleans_Saints:", ":Las_Vegas_Raiders:", ":New_York_Giants:",
":Los_Angeles_Chargers:", ":Philadelphia_Eagles:", ":Miami_Dolphins:",
":San_Francisco_49ers:", ":New_England_Patriots:", ":Seattle_Seahawks:",
":New_York_Jets:", ":Tampa_Bay_Buccaneers:", ":Pittsburgh_Steelers:",
":Washington_Commanders:", ":Tennessee_Titans:"
]```
```py
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.user.roles)
mapping = {
role: discord.utils.get(ctx.guild.emojis, name=emoji.strip(":"))
for role, emoji in zip(nflRoleListNames, nflEmojiListNames)
}
emoji = mapping.get(teams.name)```
๐
Why not use the dict from the beginning
Also store emojis like !py_strong
Not just name inside colons
To get this format, send a message yourself, not with bot with emoji and put a \ before it, like
\:emoji_name:
the bot is a public bot, the emojis are like that because i have a command which generates emojis with the names like that. every person who has the bot generates the emojis with that name
what is the question?
!e ```py
d = {"Sus Role": "๐", "Fire Role": "๐ฅ", "idiot": "๐"}
print("\n".join(f"{v} - {k}" for k, v in d.items()))
@vale wing :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ๐ - Sus Role
002 | ๐ฅ - Fire Role
003 | ๐ - idiot
Oh heck bro, you def need a database
i'd have to re write mad code and learn it when it alrerady works fine
You will just continue to lose braincells if you keep using names
well, tbf database only helps a lot when you are trying to make it work for multi guild
And just let someone rename role/emoji and the whole thing is screwed
@somber sky is this single server bot
its supposed to be a a multi but like i said if it works fine im not about to learn databases and re write my whole code which is over 2.3k lines
i dont see why
That's a challenge of your pro developer arc
However before rewriting it completely take a look into cogs as well
2.3k lines in one file ain't good
Especially considering that's probably entire project in one file
And of course naming convention
Learn these things on side project and proceed to rewriting โบ๏ธ
- Style conventions (see PEP 8)
- Cogs and extensions (dpy devs are bad, couldn't even include proper example of using cogs in extensions), will need a guide for this however
- Databases: start with sqlite, switch to aiosqlite (it's just async version of builtin lib) when understood how things work
are you still active?
@bot.tree.command(name="claim-rakeback", description="View Your Rakeback")
async def claimrake(interaction: discord.Interaction):
uid = str(interaction.user.id)
if is_registered(str(interaction.user.id)):
rake_back = get_rake_back(uid)
rbclaimed = GetTotalRbClaimed
totalrb = rbclaimed+rake_back
if rake_back > 0:
add_rbc(uid, rake_back)
set_rake_back(uid, 0)
add_gems(uid, rake_back)
await log(f"<@{uid}> Claimed {add_suffix(rake_back)} Rakeback")
embed = discord.Embed(title=f":white_check_mark: Claimed Rakeback",
description=f"You Claimed :gem: ``{add_suffix(rake_back)}\n You now have a total of ``{add_suffix(totalrb)}`` rakeback claimed. Nice!",
color=0x88ff70)
await interaction.response.send_message(embed=embed)
I get an error when trying to add the two together. The error is: discord.app_commands.errors.CommandInvokeError: Command 'claim-rakeback' raised an exception: TypeError: unsupported operand type(s) for +: 'function' and 'int' meaning the + is the error. Is there any way i can fix this, any help will do! Thanks.
You didn't call GetTotalRbClaimed
You should also use the same naming convention as other functions
yep thats why! thanks
Why would that be? Confusion?
You usually name classes like that, with a capital first letter (PascalCase)
def add_rbc(uid, amount):
data = readdata()
data['users'][uid]['Total_Rakeback_Claimed'] + amount
writedata(data)
When it runs this the amount isnt getting added.
This is my other problem
use += instead
!e ```py
x = 1
x + 2
print(x)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
!e ```py
x = 1
x += 2
print(x)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
3
no when you do x + 1 it doesnt save x value for later with one added
I'll look into changing that for all my command. can you help with my other error?
this is the other problem i have
it isnt adding my data
didnt i just help you with that?
but i was writing that for this problem
ohhh i see, thats my bad. Thanks!
it works I appreciate your time!
What's this? using discord.py
It's a ratelimit. I suggest you add a cooldown for the command to prevent it
Ok thanks
You're most likely doing something that blocked the event loop, e.g., long synchronous actions
!blocking - for more information
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
No
I haven't seen XOR (Exclusive OR) being used in Discord bots a lot, why is that?
2024-01-27 11:59:03 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/invites.py", line 223, in on_member_join
inv = invites[invite.id]
~~~~~~~^^^^^^^^^^^
KeyError: '3a9g4XQe'
How do i solve this?
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member) -> None:
guild = member.guild
if guild.id != GUILD_ID:
return
guild_invites = await guild.invites()
invites = {inv.id: inv for inv in guild_invites}
for invite in self.cached.values():
inv = invites[invite.id]
assert inv.uses is not None
if inv.uses > invite.uses:
await invite.add_uses(1)
await self.add_invite_to_user(inv)
await self.send_join_message(member, inv)
what you mean by that
This kind of stuff:
team_1_scored = 5
team_2_scored = 5
has_winner = team_1_scored ^ team_2_scored
if has_winner:
print("There is a winner!")
else:
print("It's a tie!")
do uk what xor does?
Using the exclusive or
It checks if solely one of the propositions is true, and only if one of the propositions is true
binary for 5 is 101
101 ^ 101 will give 000
truth table for xor is
a b
0 0 0
0 1 1
1 0 1
1 1 0
so its entirety logic dependent where u want to use it
usually its more verbose to use relational operators as far more people are used to it
u generally see bit operations in stuff like bit packing, saving some space during computation, flags and so on ur day to day logic dosent require u to meddle with these much
You would probably use is not equal to instead, at least for my example above
Right?
That's pretty weird
There should be != instead
That is what I just said ๐
Can you give me an example when you could use the xor operator?
XOR is widely used in cryptography, cause if you add c column to asher's table, you will see that
a ^ b = c
a ^ c = b
b ^ c = a
Which means you can make any of these original data, key and encrypted data
Of course modern encryption algorithms are more advanced but I believe xor still plays a key role there
Can somebody explain why there always is a winner?
A = 5
B = 5
if A or B and A != B:
result = "There is a winner."
else:
result = "It's a tie!"
print (result)```
just if A != B
But why does it say there is a winner with the and condition? Because they are not both true?
cause you didnt wrap those in ()
if (A or B) and (A != B):
but like i said this can be simplified to if A != B:
Thanks. I thought it had something to do with the order of the operators
Why do you need to wrap them? I'm just trying to understand the logic
cause python interprets this as if it was if A or (B and A != B):
Thanks
My friend just told me "Don't be shy of your parentheses" I will try to keep that in mind ๐
hello
hello
i've a problem
The thing is that โฆ in VSC let me running my bot without any problemsโฆ but in my host giving me an error in the module of asyncio in the file of asyncio/runners.py
Send the full traceback please
And Iโm not understanding why ..
Alr
Traceback (most recent call last):
File "/home/container/bot.py", line 32, in <module>
asyncio.run(main())
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/container/bot.py", line 29, in main
async with client:
AttributeError: __aenter__
discord.py 2.3.2
on both your local enviroment and the host?
mm idk how to see the version in my host
print(discord.__version__)
which host are you using?
this is an actual code btw just put it in your code and see what it prints when you run it
discord.py==2.3.2
do you have any other discord api wrappers installed on the host?
like py-cord or disnake or whatever
that might be why
aha-
try uninstalling it and see if it helps
alr
i've other inquirement
my vsc using phython 3.10.11 and my host 3.10.13
how to change my vsc? -
shouldn't matter, only thing that affects dpy is python 3.12, and also dpy forks
maybe a clean reinstall
oh
alr
pip install -U --force-reinstall discord.py
but in my host doesnt let me doing this-
idk why-
i see
this is in my vsc
this in my vsc
Hello guys
I'm python beginner and need some help
with?
I can't learn
I need someone to help me
Cause I started to learn and couldn't because the course is full of rules and stuff without projects so you learn for no particular reason
oh
Then I started the projects
It's just tasks
Nobody does both teach and projects at the same time
More for #python-discussion
I wanna know how did you start
Cause I've no clou about the journey and how should it be
know absolutely nothing about python
start discord.py
suffer
learn python
this is a python server? thats js?
also u didn't send the code how would we know whats wrong best we have is the error telling "this '}' was unexpected/not needed"
2024-01-27 11:59:03 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/invites.py", line 223, in on_member_join
inv = invites[invite.id]
~~~^^^^^^^^^^^
KeyError: '3a9g4XQe'
How do i solve this?
can u help me get my bot alive on vsc
is it python related if it is then ask here
then ask here
what specific file do i make to work on the bot
visual studio code?
like any extension
ur run the main bot code containing the bot class
any other extensions or cogs are loaded from the main bot class
@pale zenith Can you edit an embed with discord.PartialMessageable in a channel as well?
Instead of using message = await channel.fetch_message(case["action_log"])
Try and see

There is no idea to fetch the message as I already got the message ID
as mentioned yesterday you fetch only when you need the information from the message
!d discord.PartialMessage - this also exists, by the way :P
class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following...
Do you still need to fetch the channel though?
only if you need info from the channel
(you can pass a partial channel to the channel argument)
ParialX -> no info, only api calls
So I realized that I still need to fetch the user to obtain the username and avatar, and I also need to fetch the moderator for the same reason. Wouldn't that be the same as fetching the message itself?
why isnt that working?
So fetching users will not result in the same as fetching the message, as we still need to obtain some data?
what edi are you using?
its an hosting idk called endelon oder smth
fetching a user returns a User object. fetching a message returns a Message object. They are two completely differnt things. (Your question is... strange... perhaps could you elaborate if this doesn't answer it?)
oh thanks
np ๐
The error says the issue
sure, let me paste that code to vscode
๐ thought it will underline the problem but it didnt, let me try fixing it
We are using PartialMessage so that we don't need to make any API calls, right? However I still need to fetch some users because I require the avatar, and I can't obtain it with just the user ID. So my question is, will it not lead to the same result since we will need to make an API call either way by fetching the message or the user?
Do keep in mind that I have no idea what your end goal is.
So I literally cannot answer that in a satisfactory manner, because the answer is: It depends.
If you need data from the message then you fetch it, simple as that
I cannot see how there's any correlation between fetching a user and fetching a message. they're different things. Unless you mean like... fetch message-> message.author vs fetch the author itself. I'm still quite confused.
You create an embed with my and your avatar. The only thing you save is the User IDs for both me and you.
Then you want to add some text to the embed later, since we are using PartialMessage you need to fetch my and your user to set the avatars for the embed again. This is because it's not possible add back the avatars by only using the User IDs.
that is all factually correct
So wouldn't it be better to fetch the message instead of 2 users, and edit/add one of the lines, given that the avatars already exist for the embed?
yeah if that's what you need to do
if the info is already in a pre-existing embed, then reusing it seems fine.
anyone recommend any courses or tutorials for beginners?
for discord bots?
yes
thanks
Someone accesiable for help?
step zero is to ask a question ๐
Don't ask to ask, just ask your question
2024-01-27 11:59:03 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/invites.py", line 223, in on_member_join
inv = invites[invite.id]
~~~^^^^^^^^^^^
KeyError: '3a9g4XQe'
How do i solve this?
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member) -> None:
guild = member.guild
if guild.id != GUILD_ID:
return
guild_invites = await guild.invites()
invites = {inv.id: inv for inv in guild_invites}
for invite in self.cached.values():
inv = invites[invite.id]
assert inv.uses is not None
if inv.uses > invite.uses:
await invite.add_uses(1)
await self.add_invite_to_user(inv)
await self.send_join_message(member, inv)
That invite no longer exists. AKA it was deleted. (could be because it was the last use of that invite)
is this an error that happens always, or just some times?
Always, thats the mystery part

How can I prevent my for loop from stopping due to an error?
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/cogs/partner.py", line 564, in partner_all_guilds
channel1 = await self.bot.fetch_channel(channel_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 2565, in fetch_channel
data = await self.http.get_channel(channel_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 741, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'partner-all-guilds' raised an exception: NotFound: 404 Not Found (error code: 10003): Unknown Channel```
if guild:
if manager or interaction.guild.owner:
async with self.bot.db.cursor() as cursor:
await cursor.execute("SELECT ps_request, guild FROM setup ORDER BY RANDOM() DESC LIMIT 20")
channel = await cursor.fetchall()
for i, (channel_id, guild) in enumerate(channel, start=1):
print(channel_id)
try:
channel1 = await self.bot.fetch_channel(channel_id)
except discord.app_commands.CommandInvokeError or discord.errors.Forbidden or discord.errors.NotFound or discord.app_commands.errors.CommandInvokeError:
print(f"Missing access to channel {channel_id}")
continue
async with self.bot.db2.cursor() as cursor:
await cursor.execute("SELECT ad FROM ad WHERE guild=?", (guild,))
ad = await cursor.fetchone()
if not ad:
continue
await channel1.send(embed=embed, view=partner.buttons(timeout=None, guild=interaction.guild_id, bot=self.bot, member=interaction.user, embed=None, guild_member_count=interaction.guild.member_count, guild2=guild))
await interaction.followup.send("Partner shipped all servers!", ephemeral=True)
return
else:
await interaction.followup.send("You are not a trusted manager to run this command!", ephemeral=True)
else:
await interaction.followup.send("Please by premium to access this command!", ephemeral=True)```
just a try except should be enough
im using spotipy and ffmpeg for music, and i cant seem to get it to play.. theres no errors but it doesnt actually play any audio it just loads the track
u need to pass the exceptions in a tuple like this `except (a, b, c):
i dont think spotify web api exposes the whole track to play
https://developer.spotify.com/documentation/web-api/reference/get-track
u seem to be fetching only the track object
why u need ffmpeg if u just want to send the song link?
thought i should for audio playback
u need ffmpeg when directly working with audio streaming/downloading/converting
Oh
spotify dosent expose the tracks or audio data in their api (iirc they have a 30s demo at best)
wym?
meaning u cant download the song from spotify using the track id
meaning i cant make it play music from link?
yeah
see the preview tag on bottom u can play only a part of the song if u click on the play button
yeah
any way to change that..?
i know youtube was a thing but that is off limits now. but i couldve sworn ppl use spotipy now
not legally no that would be breaking spotify tos
most if not all