#discord-bots
1 messages · Page 322 of 1
whats the recommended size for discord embed images
don't do stuff in on_ready, you can set a status when you make an instance of commads.Bot():py bot = commands.Bot(intents=intents, command_prefix='!', case_insensitive=True, activity=discord.Game('Minecraft')) would show the bot as playing minecraft
ah ok. i use pycord so this still works on discord.Bot right?
it really doesn't matter since it depends on how much text there is
I think so since pycord is a fork of discord.py
can u put img bytes as embed img?
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
what do u think ive been doing the past 30 mins
thats why i asked here
I have no clue
The docs answer your question pretty clearly
Good for you
If you’re using a fork of discord.py the same code from the docs apply
Also people are going to assume you’re using discord.py whenever you ask for help unless you specify otherwise
"here are the docs" isnt exactly answering my question
If you cared to look at the paramters/return type it would
This is pretty clear
How do I use a local image file for an embed image
do i have to repeat myself
Okay, but unless you’re using hikari it’s the exact same thing lmao
You asked for help and didn’t specify, which is on you
Now you’re getting all pressed and this is mad funny
yh mad funny
keep yapping about the docs for a library i said i wasnt using
and then call me pressed
u act like a child
What’s the purpose of these for the webhooks?
I checked out their websites and they cover a lot of broad topics
!mute988196894897471508 1D Absolutely unacceptable and not how we talk to others here.
Like automation and such
!mute 988196894897471508 1D Absolutely unacceptable and not how we talk to others here.
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1700176989:f> (1 day).
In my case basically just having a Discord channel that will have every new tweet a specific Twitter account posts. I used to use IFTTT in the past but after some research it seems because of the Twitter API pricing changes, nor IFTTT nor Zapier offer the Twitter option for free users. It seems I'll have to use RSS for this
Yeah the new changes caused a lot of issues for new/not paid users
What’s RSS if you don’t mind?
for the record, there's also no need to make these types of aggravating comments.
It's basically an XML format some websites offer to check the content of the website.
Ah
When I try to delete a role, I get RuntimeError: Timeout context manager should be used inside a task, any idea how to fix this? using discord py latest
Could you show the code?
async def asyncTearDown(self):
super().tearDown()
for role in self.bot.get_guild(TEST_GUILD_ONE_ID).roles:
if APP_NAME not in role.name:
await role.delete()
for role in self.bot.get_guild(TEST_GUILD_TWO_ID).roles:
if APP_NAME not in role.name:
await role.delete()
What is tearDown()
Can you send the whole traceback
but these docs would still answer your question?
Error
Traceback (most recent call last):
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/mnt/c/Users/Andrew/workspace/projects/musicbot/tests/integration/test_follow_it.py", line 57, in asyncTearDown
await role.delete()
File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/discord/role.py", line 534, in delete
await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/discord/http.py", line 625, in request
async with self.__session.request(method, url, **kwargs) as response:
File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/aiohttp/client.py", line 1167, in __aenter__
self._resp = await self._coro
File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/aiohttp/client.py", line 493, in _request
with timer:
File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/aiohttp/helpers.py", line 705, in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
I'm trying to make the thread so no one else can invite here besides the moderator, but upon creating the thread it still possible to invite for non-moderator users, how do i fix it?
thread = await interaction.channel.create_thread(
name='123',
message=None,
auto_archive_duration=4320,
type=None,
reason=None,
)
thread.invitable = False
Error
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
File "C:\Users\Owner\Downloads\selfbot\selfbot.py", line 22, in <module>
client.run(TOKEN, bot=True)
discord.errors.LoginFailure: Improper token has been passed.```
hey guy im making self bot and got error but i put in my right token and doesnt work can someone help me? sorry bad english
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Self bots are explicity against Discord TOS
You're changing invitable after already creating the thread. Changing the invitable attribute is not gonna actually do anything on discord's side of things, it's just changing in-memory values
Is this task created via asyncio's framework or discord.py's
so how do i set inivitable to false before actually creating thread? Is there some kind of properties in a channel maybe?
I'm assuming discord.py's. The bot is running in a separate thread so the tests can run, not sure if that's causing the issue
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.
New in version 2.0.
invitable kwarg
^
so yeah, that is somehow does not work
Traceback (most recent call last):
File "F:\PYPROJECTS\discord\TicketBot\autoreg-venv\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "F:\PYPROJECTS\discord\TicketBot\package\bot\modules\view\ticket_channel.py", line 36, in send_ticket
thread = await interaction.channel.create_thread(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: TextChannel.create_thread() got an unexpected keyword argument 'invitable'
is on_member_boost a thing?
No.
Is it the latest version of discord py?
Okay, i need docs on how to catch a boost ig?
so you can send an embed to a certain channel of someone boosting n stuff like that
Possibly, are you willing to send the entire file?
Let me know if you want to see fanbot.py
If i remember correctly, discords API doesnt really handle a boost via an event.
No, Discord doesn't send that event. You can use on_member_update and check premium_since
But alternatively, i think discord.MessageType.premium_guild_subscription exists
Or this
Discord should send that event tho :)
well they dont.
would make it easier 
i am using py-cord, but the invitable argument still mentioned in documentation the same way with same usage
invitable (bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.
Thread needs to be private.
Also, look at thread.edit()
It looks like with pycord, it needs to be called after creation.
So you need to pass private_thread into the type when using create_thread
then call edit with invitable
When you don't mention that you're using a fork people will assume you're using discord.py
https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel.create_thread
invitable doesn't exist with py-cord
Yeah, it looks like it exists in thread.edit() rather than create_thread()
Another reason added onto the list of why to not use py-cord
I don't know to be honest
Error doesn't really align with anything in your code
weird right, shouldn't I expect it to just work by calling await role.delete()?
It should, I'm not really sure why that line is the one that's erroring as it doesn't involve a context manager
Are you using an old version of discord.py per-chance?
in my requirements.py, I just have discord.py with no version specified, that should pull latest right?
It should
Just check real quick with pip show discord.py
Does it work if you're not mocking it?
yeah it is up to date. The only thing I'm mocking is the interaction which shouldn't really come into play here right since the bot isn't being mocked? honestly so confused lol but gonna continue investigating
Hmm, maybe because it's trying to delete this role? <Role id=1004184458431315989 name='@everyone'> , the everyone role
nope
It might be a stupid question. but will editing the perms just update the mentioned rights in the code or overwrite all of the rights and leave those ones?
perms = discord.Permissions()
for role_id in mod_roles_id:
role = guild.get_role(int(role_id))
perms.update(manage_threads=True, send_messages_in_threads=True)
await role.edit(permissions=perms)
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
self bots are against tos
1. Follow the Python Discord Code of Conduct.
!rule 2
2. Follow the Discord Community Guidelines and Terms of Service.
!rules
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
Okay?
Why are you telling him this? He's not self-botting
!e
perms = {"Example_1": True, "Example_2": False}
perms.update(Example_1=False)
print(perms)
@final iron :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'Example_1': False, 'Example_2': False}
I think only the ones in the code, it’s probably best just to make a new channel and test it
it will overwrite the previous perms if you don't explicitly enable them or transfer them from the role's current permissions (Role.permissions)
seems a bit odd to have a function just for changing your mod role perms though
I had to use asyncio.run_coroutine_threadsafe and pass in bot.loop, it was an issue relating to using a separate thread.
I could've used bot.start() instead of bot.run() to avoid using a separate thread, but since setUpClass doesn't work asynchronously, I would've had to start and stop the bot for every single test which would've been really inefficient / prone to rate limiting with repeated logins
Thanks for assistance
Tf u on 💀
lmao
How to do this..?
also this means that your interaction can now last longer than 3 seconds correct? Thats what ive been told, so thats why im wanting to do it.
use defer with thinking set to True
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Thank you
Is this possible with Hybrids?
yes. use ctx.typing
Yeah but gives an error saying it already responded to this command
thats why im wondering lol
well im just testing it, this command really doesnt need a defer, but just for testing
An error occurred: Hybrid command raised an error: Command 'coinflip' raised an exception: InteractionResponded: This interaction has already been responded to before```
!d discord.ext.commands.Context.typing
Just a note
async with typing(*, ephemeral=False)```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.
In an interaction based context, this is equivalent to a [`defer()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.defer) call and does not do any typing calls.
Example Usage:
```py
async with channel.typing():
# simulate something heavy
await asyncio.sleep(20)
await channel.send('Done!')
```...
Do a followup after ur defer
ah okay then
defer is a response to an interaction so yeah
eh tbf, ctx.send should do followup.send internally when you do that
defer is an interaction response, yes
Dunno how u can get a context from that without a conversion
or something like _toctx or sum
Okay so this gives the bot extra time to like process the command correct?
instead of the standard 3 seconds?
Yes
okay ty
15 minutes
Me when i dont get a strong comeback:
I dont know why he just didn't tell what lib bro using 
ERROR: Failed building wheel for multidict
Building wheel for yarl (pyproject.toml) ... error
error: subprocess-exited-with-error
how to fix?
Which Python version are you on
and what are you trying to do
how do i make something like this in my bot i want multiple sections for one command
i dont want same commands but i want them like this
that's just a group subcommand
class MyGroup(commands.GroupCog, group_name='afk', group_description='description'):
subgroup = app_commands.Group(name='mod', description='balls')
@subgroup.command()
async def ignore(interaction: Interaction):
...
@subgroup.command()
async def ignored(interaction: Interaction):
...
probably looks like this from the screenshot
note that it can't go further than a single group nested command
see here too for another example
Down grade to python 3.11
so instead of normal commands.Cog i use commands.GroupCog?
does it work with hybrid or just app
GroupCog is specifically for slash, since discord slash isn't as powerful since it can't have callbacks for the initial group command, for hybrid you just do it normally as you would like a regular group command
i am making uno game so having just random command called like playcard or something is just wierd
thats why i was thinking about that
this would be hybrid equivalent ```py
class MyCog(commands.Cog):
@commands.hybrid_group()
async def afk(...):
...
@afk.hybrid_group()
async def mod(...):
...
@mod.command()
async def ignored(...):
...
i have beeen using normal Cogs but never knew that does that work like
!afk ignored
if you removed the mod ofc i dont need that many options
i only need 2
GroupCog is just a slash concept to be fair, not a lot of people use it since they are too lazy to look for it
so how does this work does it work like i mentioned
it would yea, just use afk.command() deco instead of afk.hybrid_group()
oh ok thanks
what do i put in the async def afk tho
will it run when i run the !afk ignored
by default it will run first before ignored is ran for prefix command, for slash it never will
eh wait, im wrong
oh so i can identify b/w the slash and the prefix with this
by default it will only ran if the subcommand isn't found, say !afk blah since blah isnt a subcommand, it will invoke afk with argument blah instead
oh
better to use ctx.interaction is None to do that instead
so like in afk if i run !afk it will run only the async def afk and if i run !afk ignored it will run that ignored one and if i run !afk blah it will take blah as an arg
wleocme
i have one more question if i like get a user from bot.fetchuser then can i send a message to a channel and make it empheremal for that user specific
nop, ephemeral are interaction specific
?
interaction.reply doesn't exist
But yea anything related to interaction response, including ctx.send in hybrid you can do ephemeral
ok thansk
one more question can you call a hybrid command throught another command like if i type !warn it will also activate !ban something like that its jsut an example i want to do something else that i cant illustrate
u pinged me ?? cause i got a notification
You shouldn’t be invoking the command itself. You should have a ban function that you’re calling in both your ban, and warn command
That’s the whole point of functions
yes, sorry
np
oh ok
node index.js (node:240) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time (Use node --trace-warnings ...` to show where the warning was created)
Unhandled promise rejection: Error [TokenInvalid]: An invalid token was provided.
at Client.login (C:\Users\abhay\OneDrive\Desktop\ \grbog\node_modules\discord.js\src\client\Client.js:214:52)
at Object.<anonymous> (C:\Users\abhay\OneDrive\Desktop\ \grbog\index.js:88:8)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'TokenInvalid'
}
(venv) C:\Users\abhay\OneDrive\Desktop\ \grbog>`
why bot shoiwng/invalid/token/for/no/reason
💀
i chnaged bot/token/10/times/everythig/is/perfect/still/error
How to do something like this?
give full context this isnt enough atleast for me
u mean an app bookmark?
Yeap
i think its interaction
i dont really know it sorry try asking someone else
its something to do with interaction thats for sure i think
Haha i knew you were searching 💀
Context Menus are a way to run an application command without typing anything. They are accessed in the "Apps" section when right clicking a user or message.
When you right click a message, they are called message commands. In discord.py 2.0 you can implement them as such:
@tree.context_menu(name='Translate with Google', guild=discord.Object(id=MY_GUILD_ID))
async def translate(interaction: discord.Interaction, message: discord.Message): # An annotation of discord.Message makes this a message command
...
Likewise when you right click a user or member, they are called user commands. You can change the annotation from discord.Message to discord.Member accordingly:
@tree.context_menu(name='Ban User', guild=discord.Object(id=MY_GUILD_ID))
async def ban_user(interaction: discord.Interaction, member: discord.Member): # An annotation of discord.Member makes this a user command
...
You can also annotate this with discord.User, but because context menus are only applicable in guilds, they'll probably always be members.
Documentation: https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu
Note: Context menus cannot be used inside of cogs (in the way you'd normally expect) - see the issue here: https://github.com/Rapptz/discord.py/issues/7823#issuecomment-1086830458
Thanks
does anyone know how to get those forms ?
Which forms
like lemme try find one
Are you talking about modals
is that this?
Yes
thanks mate
is this new on dpy bc i never seen
no
Am I able to retrieve basic information about a guild/server my bot is not in based on its ID? I'm only looking to resolve the guild name from its ID when the bot isn't in that server/guild
yes pls give me money now
not sure but i think its
discord.Object(name="GUILDNAME")
``` but not sure tho
No
If there's an error you should mention it
embed = client.Embed(title=self.title.value, description=self.description.value)
await interaction.response.send_message(embed=embed)```
well i just dont know how to make an embed on app commands
could u help (no error just the .Embed thing
client = MyClient(intents=intents)
What's MyClient
class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
await self.tree.sync()
intents = discord.Intents.default()
client = MyClient(intents=intents)
So you're doing discord.Client.Embed which doesn't exist
what do then?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
how import embed?
It's just discord.Embed
ok
await interaction.response.send_message(embed=embed)
idk it int working is it this still?
Is there an error?
Oops! Something went wrong.
what
How do I hide HTML's code that is popping out and just send the file to the channel?
async def archive(interaction, archive_channel, user_id):
"""
:param interaction: discord.Interaction
:param archive_channel: Object of the Transcript channel
:param user_id: (User ID of the Client)
:return:
"""
channel = interaction.channel
transcript = await chat_exporter.export(channel)
if transcript is None:
return
base_path = os.path.abspath(f"../package/bot/ui/media/user_{user_id}")
if not os.path.exists(base_path):
os.mkdir(base_path)
image_paths = []
messages = await channel.history(limit=None).flatten() # Convert to a list
for message in messages:
for attachment in message.attachments:
image_data = await attachment.read()
image_path = os.path.join(base_path, attachment.filename)
with open(image_path, "wb") as file:
file.write(image_data)
image_paths.append((attachment.url, image_path))
image_paths.reverse()
soup = BeautifulSoup(transcript, 'html.parser')
attachments = soup.find_all('div', {"class": "chatlog__attachment"})
for i, attachment in enumerate(attachments):
anchor_tags = attachment.find_all('a')
if anchor_tags:
anchor_tags[0]['href'] = image_paths[i][0]
img_tags = attachment.find_all('img', {"class": "chatlog__attachment-thumbnail"})
if img_tags:
img_tags[0]['src'] = image_paths[i][0]
modified_transcript = str(soup)
embed = create_embed(
title=f'Transcript for #{channel.name}\n',
description=f'Client: <@{user_id}>'
)
embed_message = await archive_channel.send(embed=embed)
# FILE BEING SENT HERE
transcript_file = discord.File(
io.BytesIO(modified_transcript.encode()),
filename=f"transcript-{channel.name}.html",
)
file_message = await archive_channel.send(file=transcript_file)
link = await chat_exporter.link(file_message)
new_embed = create_embed(
title=f'Transcript for #{channel.name}\n',
description=f'Client: <@{user_id}>\n[Open in browser]({link})'
)
await embed_message.edit(embed=new_embed)
wdym "HTML's code that is popping out"
Also flatten() is out-dated
oh, ok, thanks
Actually you can try the suppress_embeds kwarg
See if that does anything
Question, can you add specific description for a parameter for a slash command?
Like after where it says role it tells you the instructions for the input to that parameter?
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
Aight thanks
@unkempt canyon whats the event to get when a member boost your server
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their profile.
This is called when one or more of the following things change...
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.
Discord doesn't dispatch any event when the server gets boosted
having the boost message is the only way iirc
or maybe you get a guild update. haven't checked
With slash commands can you set an option as accepting a file?
what's the deco for an optional argument?
!d typing.Optional
typing.Optional```
`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:
```py
def foo(arg: int = 0) -> None:
...
``` On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example:
```py
def foo(arg: Optional[int] = None) -> None:
...
```...
Or default to a value
I mean like for slash commands isn't there an arg for like /help <optional: menu>
Yeah you'd typehint the arg with this
So it wouldn't need a command_choices
I meant @app_commands.choices()
Do you know what choices() does?
Yeah but when you add them they're required right
I don't believe so
Can I do this in slash commands? file: discord.Attachment
@latent jay
And to send a file?
wdym
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
oh, I should've specified, I'm using Interaction.edit_original_response()
Says it's attachments?
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Yeah it would be
And then I'd just do attachments=discord.File('path/to/file) right?
Yeah
Well attachments is a list
So you’d need to put that discord.File object into a list
Question, how do I get the bot to not send the "no response" message
You need to actually respond to the interaction instead of sending the message to the channel
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
Use that instead
How could I use wait_for to check for an attachment?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
You are not allowed to use that command here. Please use the #bot-commands channel instead.
pep_number
!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.
this error keeps coming up when i start my uno
idk why
this code of this command
Are you using discord.py?
!e import random; print(1 if random.randint(1,2) == 1 else 2)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
does discord.ext.loop runs loops even if the previous loop is still running
nope, the previous needs to finish
Does anyone have experience adding role management based on a reaction to a message?
This has been millions of times. Just ask your question
Don’t ask to ask. Just ask your question and you’ll get a faster response
Sorry I am just running into trouble. Obviously I haven't set it up correctly, but I want to assign a role based on a reaction to a message... but the reaction event isn't being registerd to the bot.
My code:
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
!d textwrap.wrap
textwrap.wrap(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, ...)```
Wraps the single paragraph in *text* (a string) so every line is at most *width* characters long. Returns a list of output lines, without final newlines.
Optional keyword arguments correspond to the instance attributes of [`TextWrapper`](https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper), documented below.
See the [`TextWrapper.wrap()`](https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper.wrap) method for additional details on how [`wrap()`](https://docs.python.org/3/library/textwrap.html#textwrap.wrap) behaves.
"Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build aiohttp frozenlist multidict yarl
ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects"
and i can't understand how to get c++ tools
Downgrade to Python 3.11.6
shall i unins the one i have ?
Yes
k ty, ill tell you if it works !
Hey i need some help swithcing the default !help command to be an embed message instead
thank ya
tysm, works
Hey, I've been fighting with this command for so long, and it still sometimes throws API rate limit. Any suggestions, how to make it better/smoother/orwhatever, that will make it always work?
https://paste.pythondiscord.com/AU2Q
(I'm talking ab first file, the other two files are just imports I'm using)
I think im doing somthing wrong, i can get a message to embed but how do i change the values?
what it says i mean
I'm looking at views in discord.py, specifically persistent buttons. I'm seeing that you have to use .add_view() to make sure that it's being watched and the example that is on the discord.py repo shows it being added during the setup_hook(). I'm trying to understand two things:
- Does it need to be in setup_hook or is that just the example they have?
- Can
setup_hookbe called in a cog and the view added that way or does it need to be on the base bot class?
Not sure if I'm explaining that well at all
Are you talking to me? or someone else, i can't tell
my brain smooth
- you can do that elsewhere but preferably in setup_hook, you dont want this to be called more than once
- i belive setup_hook behaves like event
So it should be one of the methods that'll be treated the same as if it were in the bot proper
Does it need the event decorator?
if someone could dumb this down for me please i think i misunderstand it
setup_hook is a method of commands.Bot so you’ll need to overwrite it via subclassing or assigning it
!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)...
setup_hook isn’t an actual event sent by Discord like on_ready, it’ll simply just executed once on login. I’d think of it more of a method than an event
Which part are you having trouble with?
the last bits, starting at command object and the code itself
the other article helped a bit for some other things
i just sorta need to know how that custom command works and what i can change on it
The gist goes over that
add_view()is synchronous so in theory you could put it anywhere, though constructing a view itself appears to require a running event loop at minimum- For a cog I would suggest the (a)synchronous
Cog.cog_load()method which gives you a good place to fetch any state needed for constructing your view
it's not particularly obvious how you'd remove the view during cog_unload() (to prevent old callbacks firing if you reload the cog), but based on their source code, any references to the view and its callbacks should be discarded when you .stop() the view
discord/ui/view.py lines 431 to 432
def _start_listening_from_store(self, store: ViewStore) -> None:
self.__cancel_callback = partial(store.remove_view)```
Hey question, You know how when you invoke a command using the Dyno bot, In the footer it says executed at (my timezone) then if a different user uses it it shows thier's, How does Dyno do that (Ping when responding pls)
!d discord.Embed.timestamp
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
ty
oooooo tysm
hey so im trying to make a command to essentially create an event rsvp with slash commands. The user will simply do /rsvpcreate and then there will be a questionnaire essentially to get the details needed for the event. The bot will initially respond with "Let's create a new event! Please provide the following information." but I cant figure out how to respond again with the first question being asking for the timezone.
Sorry about bad formatting im tired as
You’ll need to be more descriptive. You’re also stating elements and leaving out crucial information assuming we know what they are
How is this questionnaire formatted? Is it a modal or something else? What do you mean respond again? Respond to what?
alright so, the user does /rsvpcreate. The bot responds with a message "Let's create a new event! Please provide the following information." and will then send another message "1. What is your timezone? (e.g., 'Australia/Brisbane')". The user will reply with a regular message with the country and city or their timezone, that data will then be stored and the bot will send another message "2. What channel will the event be in?" where the user do the same thing, replying with the channel id or channel name whichll then be stored. This is my first time playing around with slash commands and I cant figure out how to respond to regular messages from the interaction (slash command) user.
Why not just have the timezone and channel as arguments in the slash command?
Or a dropdown menu
just noticed i forgot to mention that there will be 8 questions, im trying to make it as user friendly as possible so I'd rather a more interactive solution. I probably could put all of them as arguments in the slash command but I feel like that would end up messy for me and the user, even if I only do a few like the channel and timezone I'm still left with the same issue
It really depends on what the question is. In my opinion, timezone should be an autocomplete parameter in the slash command. That makes it easier for you and the user. The channel could be a channel select dropdown as they were pretty much intended for that purpose
Different arguments require different formats
The timezone could also just be a string argument or a wait_for, depending on what you want
Make a site 😜
Best UX
But yeah for discord bot good option would be redirecting users to some timestamp generation site and pasting the number from there
Or telling them to type time in UTC like that's their problem to convert time
what is the discord for py bots
What?
what's the discord library for python?
This one?
Could I make a command/function of my bot to log into a different bot account.
Something like this psuedo code:
async def subbot(ctx, token: str):
output=""
subbot = discord.ext.commands.Bot(command_prefix='?', intents=discord.Intents.default())
@subbot.event
async def on_ready():
output=(f'Logged in as {subbot.user} (ID: {subbot.user.id})')
@subbot.command()
async def test(ctx):
output=("test response")
await ctx.send(output)
subbot.run(token)
await ctx.send(output)
why would you want to run a bot .. with another bot
I host Discord bots for ppl, if they go down for whatever I need to trawl through Discord DMs to try to remember who owns the bot to notify them about the outage.
So my idea was I could just get my management bot (which isn't in their servers) to log in to their instance to send them a message about the outage. I had a few other use cases for such a feature but that's the easiest to explain
White label instances would also be a good use for such a implementation
hello how i can setup role for use command
?
@bot.command()
async def clear(ctx, amount=5):
if amount > 100 or amount <1:
await ctx.send(f"you put {amount} in, but allowed range is 1-100")
return
textchannel: discord.TextChannel = ctx.channel
await textchannel.purge(limit=amount+1)
await ctx.send(f"deleted {amount} message in {ctx.channel.name}")
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError).
Example...
?tag op
This is not a Modmail thread.
?tag lp
This is not a Modmail thread.
@empty lake oh i forgot to mention that they copy-pasted a tag from the discord.py server, and they don't actually exist here
Where’s the discord.py server?
dpy is the vanity iirc
You can easily find an invite online though
description of this channel
Would this code be functional?
cause I don't have a functional bot rn 
What you’re asking won’t work
Unless you do some extremely hacky subprocess work to start the files of the other bot and capture and redirect the stdout you’ll need to use threading
Threading comes with the performance implications
okay thanks I was only planning to have 2 or 3 commands with this subbot so I wasn't really thinking of additional files. I'll look into threading then
this kind of ends up being a general concurrency problem but you can run another bot in three ways:
- creating a subprocess
- creating a thread
- using the same event loop
using the same event loop is probably the easiest solution particularly if you need to share information between both bots
Using the same event loop can come with unexpected issues though
im not aware of any issues with it
by simple i mean the bare minimum being: ```py
subbot_tasks = []
async def start_bot():
bot = MySubBot(...)
task = asyncio.create_task(bot.start(token))
subbot_tasks.append(task)```
Hello, idk how to make a ban command for ban with id or member and not only id or not only the @
You’ll have to verify none of the bots contain blocking code or lengthy IO tasks
as in you want to ban someone by ID instead of their name?
Both, I'd like to do with id or name in the same command
ehh that's an issue regardless of how you run your bots, but i guess the consequences would be a bit worse
for discord.py you could typehint your command parameter with discord.Member which can convert both names and IDs to the same person
also works for slash commands too
If separate files were being run it would only affect the 1 bot, but with a shared event loop it has the potential to freeze all of them and imo if you’re functioning as a hosting platform of sorts you can’t really just reject peoples code
yeah there's a lot of factors to consider with the scalability of your program
Yes but if you put member: discord.Member, you can't enter id
oh for slash commands yeah, i forgot they don't autocomplete IDs
have you considered using a context menu instead?
examples/app_commands/basic.py lines 85 to 89
# This context menu command only works on members
@client.tree.context_menu(name='Show Join Date')
async def show_join_date(interaction: discord.Interaction, member: discord.Member):
# The format_dt function formats the date time into a human readable representation in the official client
await interaction.response.send_message(f'{member} joined at {discord.utils.format_dt(member.joined_at)}')```
see also discord api docs
https://discord.com/developers/docs/interactions/application-commands#user-commands
Ok thanks
okay thanks for this, useful info to know
so the hosted bots themselves would run completely independently of my management bot (not within in it), I just want my management bot to be able to log into their bots accounts using their tokens so I can send a message as their bot. It wouldn't need to be logged into their bot all of the time, ergo the command
if you just need to send a message, you could login() + get_partial_messageable().send() to make the API request without doing a full-on gateway connection, or alternatively use the discord API directly if you find that more familiar
I hadn't thought of that, that could be option
My command don't want to load on discord...
I wait since 30 minutes
And i have bot.tree.sync in my code
Can someone help me with this {
"commands": {
"Bot": {
"command_prefix": "!"
},
"room_data": {
"PUT PLAYERIDHERE": "PUT ROOM CODE HERE"
},
"on_ready_event": {
"print_statement": "Logged in as BOT_NAME (BOT_ID)"
},
"on_member_update_event": {
"if_condition": "before.activity != after.activity and isinstance(after.activity, discord.Game)",
"actions": [
{
"player_id": "str(after.id)",
"room_code": "find_room_code(player_id)",
"if_room_code_exists": {
"channel": "bot.get_channel(CHANNEL_ID)",
"send_message": "await channel.send(f"Player {after.display_name} joined room {room_code}")"
}
}
]
},
"find_room_code_function": {
"function_body": "return room_data.get(player_id, 'Room Code Not Found')"
},
"run_bot": {
"bot_token": "YOUR_BOT_TOKEN"
}
}
}
what the actual fuck
blud be coding in JSON
I have write that:
@bot.tree.command(name="ban", description="Ban a member")
async def ban_user(interaction: Interaction, member: discord.Member or str, *, reason: str = None):
await interaction.response.defer()
print(f"Attempting to ban: {member}")
if not interaction.user.guild_permissions.ban_members:
await interaction.followup.send(f"You are not authorized to use this command {interaction.user.mention}")
return
if isinstance(member, str):
try:
member = await bot.fetch_user(int(member))
except discord.NotFound:
await interaction.followup.send("User not found")
return
print(f"After fetch_user, member is: {member}")
if not isinstance(member, discord.Member):
await interaction.followup.send("Invalid user")
return
if member == interaction.user:
await interaction.followup.send("You can't ban yourself")
return
if member == interaction.guild.owner:
await interaction.followup.send("You can't ban the owner")
return
if member == bot.user:
await interaction.followup.send("You can't ban me")
return
await interaction.guild.ban(member, reason=reason)
await interaction.followup.send(f"{member} banned from the server")```
And i get this error
```shell
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 852, in _invoke_with_namespace
transformed_values = await self._transform_arguments(interaction, namespace)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 818, in _transform_arguments
transformed_values[param.name] = await param.transform(interaction, value)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 181, in transform
return await maybe_coroutine(self._annotation.transform, interaction, value) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/utils.py", line 693, in maybe_coroutine
return await value
^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 622, in transform
raise TransformerError(value, self.type, self)
discord.app_commands.errors.TransformerError: Failed to convert juggos.rc to Member```
When i put the id
Why discord.Member or str
That's not how it works, use a converter
And especially if you're using slash commands options
And also instead of having a check for the user's permission, make it a decorator and handle the error in your error handler
thats already handled by Member converter
What is this
As a legitmate question
What are you trying to do?
What’s the point of this when the default ban command exists
The built-in one is objectively better
You’re also never checking for hierarchy
It's to track what code I join in a game and idk how to fix it and make it work
Well first of all, whats with all the dictionaries?
What library are you using?
Which discord API wrapper are you using
Idk
Are you following a guide?
Nope
local_time = datetime.now()
text = "© UniBot 2023-2024 • Today at {}".format(local_time.strftime("%I:%M %p"))```
this is how dyno/carl/mee6 do it correct?
so it shows the correct time for everyone..?
@final iron (sorry for the ping)
Just wondering if you know if thats correct..
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
use the timestamp property
it's really easy
you just have to pass local_time in there
no, wait, it's actually UTC time i think
yep
Now real question
will it show different time for others based on their time?
thats kinda the goal here XD
it's expecting UTC timestamp so use datetime.utcnow instead
But would it show my time if i use UTC?
cuz im CST
yeah it should
let me test rq
that's on Discord's side to render the time on the client
you just have to supply the utc timestamp and it'll convert to the client's local time
what are you saying here?
So the timestamp is a footer
but i also wanna have "© UniBot 2023-2024 • timestamp" as the footer you know?
Like this, but this was before i had the timestamp in the embed. but now i have it in the embed... but the timestamp is a footer, so how can i do that?
Oh i know why, i was on the wrong embed 
mb
How do I edit an interaction message? I can't call edit() on a interaction.response.send_message
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
gotcha
Okay so i just had the timestamp stuff working right?
Why is it now saying Tomorrow 😭
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow) since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
use that, datetime needs to be aware
if someone could peep my thread, that would be amazing #1175628107504435240
nah, im using datetime.now()
cuz it actually does it correct unlike utcnow
Probably coincidentally the timestamp was matching UTC timezone
Its recommended to use discord.utils.utcnow instead
I'm not talking about datetime.utcnow
So i should just do
timestamp=discord.utils.utcnow(),
yea sure
Try it and see
hello hello i have a ready discord bot coded on python now i want to host it i want a free option like really free i treied every thing which shows on google result maybe there is hidden gem platform
Do have a question, this is still about timestamps but for a custom embed... based on True or False basically, whats the best way to approach the timestamp for this besides the way i do it..?
@commands.hybrid_command(name="embed")
@commands.guild_only()
async def custom_embed(
self, ctx, title, color_hex, header=None, description=None, title_url=None, timestamps=False,
footer=None, footer_image=None, thumbnail=None, image=None, author=None, author_url=None, author_icon=None
):
"""Lets you make a custom embed to your liking!"""
if not title or not color_hex:
error_embed = discord.Embed(
title="Command Error",
description="Invalid arguments! Please use the format:\n!embed title hex_color [header] [description]",
timestamp=discord.utils.utcnow(),
color=0xFF0000
)
error_embed.set_footer(text="© UniBot 2023-2024", icon_url=ctx.bot.user.avatar.url)
await ctx.send(embed=error_embed)
return
if not color_hex.startswith("#"):
color_hex = "#" + color_hex
if not re.match(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_hex):
error_embed = discord.Embed(
title="Command Error",
description="Invalid hex color format. Please provide a correct hex color.",
timestamp=discord.utils.utcnow(),
color=0xFF0000
)
error_embed.set_footer(text="© UniBot 2023-2024", icon_url=ctx.bot.user.avatar.url)
await ctx.send(embed=error_embed)
return
if len(color_hex) == 4:
color_hex = "#" + "".join([char * 2 for char in color_hex[1:]])
try:
color = int(color_hex[1:], 16)
embed = discord.Embed(
title=title,
color=discord.Color(color)
)
if header:
embed.description = header
if description:
descriptions = description.split("\\n")
for i, desc in enumerate(descriptions, start=1):
embed.add_field(name=f"", value=desc.strip(), inline=False)
if title_url:
embed.url = title_url
if timestamps:
timestamp = datetime.datetime.utcnow()
timestamp_str = timestamp.strftime("%m/%d/%y at %I:%M:%S %p")
if footer:
timestamp_str = f"{footer} • {timestamp_str}"
embed.timestamp = None
embed.set_footer(text=timestamp_str)
if footer_image:
embed.set_footer(text=timestamp_str, icon_url=footer_image)
if thumbnail:
embed.set_thumbnail(url=thumbnail)
if image:
embed.set_image(url=image)
if author:
embed.set_author(name=author, url=author_url, icon_url=author_icon)
await ctx.send(embed=embed)
except ValueError:
error_embed = discord.Embed(
title="Command Error",
description="Invalid hex colour format. Please provide a correct hex color.",
timestamp=discord.utils.utcnow(),
color=0xFF0000
)
error_embed.set_footer(text="© UniBot 2023-2024", icon_url=ctx.bot.user.avatar.url)
await ctx.send(embed=error_embed)```
@vapid parcel how do you embed these code
use ```````
then do py
best way i can explain it without it messing up lol
try one more time
you mean this```
thanks can you help me with my probleme
Sorry for ping @golden portal or @final iron..
What would be the best way to approach a timestamp for a custom embed command? Based on True or False?
Instead of my approach^
There no good free options
0
You have to pay one way or another
looks fine to me, personally I would just use a flagconverter by looking at how many argument that have
I’d typehint it is a bool so users can choose if they want one or not. I’d typehint a lot of your other parameters as well
ohh boy pay is like stealling my parents money i am minor also
discord.pys converters supports bools. It converts a few different inputs, which are listed in the docs
I’d check those out
Okay thank you
Welp, nothing is free
Thank you too.
Who do you think is paying for the servers, equipment, electricity, land, maintenance and development of the servers?
There is 1 free one... but I wouldn't recommend them because they have access to all of your data.. including the token.
Somebody has to
Which means they can sell your data, but every website sells your data in a way lmao
This is all on you if you use them just saying.
https://bot-hosting.net
i know it should not free but noob likey what the will do
Every free option has major pitfalls
Reminder this is a free host, not the best, also not the safest, but thats on you like i said.
He did mention he is a minor, depends where you live i guess, for me I can't legally get a job until 18 sadly lol
Could go mow grass tho :)
yeah there is tea shop i can clean pots @final iron
Well obvi lol, yard work, cleaning, chores (up to parents), many other ways, selling things that can make profit that you dont need.
Walk up to a house, ask for $2 to clean the weeds from their lawn
Do it XD
Do that 5 times and you’ve paid for 2 months of hosting
make the money
i am sure you are from usa
Well, physically he did... but he would need a card to do it lol
I’m not
exactlly
Give parents cash and they’ll most likely let him use their card. If not just ask a friend
thanks i will work on that time to do some risky hosting
Well yeah, just depends on if they really wanna 😭 parents be wilding sometimes
If you dont mind me asking tho, whats a good VPS
and trusted ^
Tags “vps” and “cheaper vps” in the dpy server
What type of VPS are better..?
or reliable?
@vapid parcel can i make a .env file there and no need of disclossing my token
.env files can still be opened
you can make an env file, but they have access to everything
Read the ToS and Privacy for their site before using.
VPS tag is really just based on price and which location you want it in. Cheaper VPS lists the pros and cons
Are you looking for a cheaper or more expensive option?
Oh okay
Im a minor, so imma go with cheaper because not much money XD
Hetzner imo
Also rather get a VPS, so i can run more than 1 bot basically, i know you run more than 1 bot in 1 terminal, just dont know how to right now sadly
Okay, ill check them out, gotta save up first :)
Thank you for the help
Oh also, can you make Sqlite technically be online..? for like a website dashboard for a bot..?
Or would you need a VPS
It’s like $4 a month for the cheapest tier
wdym online
Connected to a website
@vapid parcel hey bro one more thing atleast discord server bot dont send me notification of exposed token
You’ll still have to run the files for the website
You can keep your database files in the directory where your website is being run from
If you want your database on a server you’ll need to look into pymongo
You can also create a little API to interact with your database if you want
we are thinking of switching to this?
insteal of just SQLite
Nope
they do not... they should tho lowkey, that would be smart... but they dont,
Any reason why
Well the reason why is because we have no clue if we can make the SQlite db work with a website
we havent done much research yet, its like way in the future.. but we are just thinking of it, just thoughts, not commits lol
PostgreSQL would be the same situation as SQLite
They both interact with local database files
oh hm
Well, we have to do more research tbh
we are just thinking on how we will do a dashboard n everything
I’d look into PyMongo
Yeah its just thoughts for now, we still researching many things
But yeah, we wanna switch to VPS, get away from a host, then we can do many more things
more freedom XD
VPS is a good start
where can I ask for codes For my discord bot?
your brain

is py_cord different than discord.py?
how shall i add a slash command or application command using discord.py?
can't i use commands.Bot?
instead of client
you can
how
just like youdo with client
tell me the code so that i can put a slash command in my bot
yeah its right there
File "c:\Users\admin\Desktop\Coding Knowledge Drive 2\Python Programs\Discord\Helper Bot version 1\main.py", line 46, in <module>
@bot.tree.command()
^^^^^^^^
AttributeError: 'Bot' object has no attribute 'tree'
it gives this
then its not discord.py
the module name is only "discord"
it should be discord.py
!pypi discord.py
Why this bot don't responding to message
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='/', intents=intents,
help_command=None) # added debug option
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.event
async def on_message(message):
print(f'Received message: {message.content}')
await bot.process_commands(message)
@bot.command()
async def ping(ctx):
print("Ping command invoked")
await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')
@bot.command()
async def active_commands(ctx):
commands_list = [command.name for command in bot.commands]
await ctx.send(f'Active commands: {commands_list}')
@bot.command()
async def hello(ctx):
print("Hello command invoked")
await ctx.send('Hello!')
bot.run(
'TOKEN')
!mcintent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
Thank you its work
import discord
from discord.ext import commands
import asyncio
command_prefix = "."
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=command_prefix, intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.tree.command()
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')
bot.run('')
in this when i put other commands they are working but this tree command isnt working also this tree command is only slash command right?
How to show bot here
yes i want to ask same question
caues its not discord.py ...
i want my slash command to be there
then what is it
i have downloaded discord.py only
then send output of pip list
!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.
2.3.2
this is output
okay how about __author__
hybrid command also not working
shall i uninstall discord.py and install again>?
you can try ig
what does this do
makes prefix and slash command at once
!help\
Hi what are you doing here
reinstalled and still hybrid command and tree command not working
in hybrid command ".hello" is working but not "/hello"
. is my default prefix
when i type /hello nothing pops up
can you do from discord import app_commands
and see if this import works
yes its working
no error on that
show full code with @bot.tree.command()
import discord
from discord import app_commands
from discord.ext import commands
import asyncio
print(discord.__version__)
print(discord.__author__)
# Set your command prefix
command_prefix = "."
intents = discord.Intents.all()
# Create an instance of the bot
bot = commands.Bot(command_prefix=command_prefix, intents=intents)
# Event handler when the bot is ready
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
# Command to get ping
@bot.command(name='ping')
async def get_ping(ctx):
latency = bot.latency * 1000 # Convert to milliseconds
await ctx.send(f'Pong! {latency:.2f}ms')
@bot.command(name='raid')
async def raid(ctx):
await ctx.send("Timer set! I will ping you after 30 mins!")
await asyncio.sleep(1800)
message1 = ctx.author.mention
await ctx.send(f"Raid cooldown is over! {message1}")
@bot.command(name='hourly')
async def hourly(ctx):
await ctx.send("Timer set! I will ping you after 1 Hour!")
await asyncio.sleep(3600)
message1 = ctx.author.mention
await ctx.send(f"Hourly cooldown is over! {message1}")
@bot.command(name='timer')
async def timer(ctx, time):
await ctx.send(f"Timer of {time} seconds have been set!")
await asyncio.sleep(int(time))
message2 = ctx.author.mention
await ctx.send(f"Time up! {time} Seconds have been passed. {message2}")
@bot.hybrid_command
async def hello(ctx):
await ctx.send("hello!")
@bot.tree.command()
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')
# Run the bot with your token
bot.run('')
and what error you get
no errors but they dont work
did you invite bot with application.commands scope?
the bot is up and the other commands are working
A hands-on guide to Discord.py
i invited it and gave permission as administrator
ok but did you invite it with application.commands scope enabled?
ok wait i get what ur saying
just read whats in this section i linked
and do what it says
done
i ticked bot and application.commands in scope and administrator and using that url i invited the bot again
👍
but still not working :(((((((((((((((((((((
you need to sync the commands
i put / and my bot doesnt even appear there and when i put /hello still it doesnt appear
add this code ```py
@bot.event
async def setup_hook():
await bot.tree.sync(discord.Object(YOUR_GUILD_ID))
YOUR_GUILD_ID?
yeah YOUR_GUILD_ID
that you are testing the bot in
yeah
why my msg is red
oh nvm
File "c:\Users\admin\Desktop\Coding Knowledge Drive 2\Python Programs\Discord\Helper Bot version 1\main.py", line 25, in setup_hook
await bot.tree.sync(discord.Object(12121212121212121212))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: CommandTree.sync() takes 1 positional argument but 2 were given
that 121212121212 is my guild id but my guild id is different
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
sorry you have to add guild=discord.Object(...)
same as it is?
obviously you put id instead of dots
oh my guuild id
i put that but same
same what
it still does not appear?
no
i guess you have to wait a bit
it may take a while
can you give me a simple code which have atleast one slash command and it actually works?
no pls thats very complicated
i cant understnad it
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
now i remember why i dont use discord.py
so much effort just to have slash command
Anyone that has the knowledge that is required to use discord.py should be able to easily understand the code
ngl thats some facts
If you don't, you need to learn Python and the various required topics/themes to know
but i am new
you shouldnt start from a discord bot tho
Then you shouldn't use discord.py and learn Python
thats why i came to ask questions
look at my code its so simple and short and easy to understand
and look at that code ...
that doesnt make you understand it
i doubt you know what OOP, decorators and async await syntax is
if you are new
yeah please just start with the basics
I stated with discord.py with python
I started to learn Python just to make myself a bot 🫠
It's probably 3 years ago, almost right after I created my account
not gonna lie i started making bots when i almost knew nothing too but it does not mean i recommend this way
who will write a bot that will check all the files on the server that the participants throw off through the virustotal and into the channel for admins to throw off information whether the file is infected
you can?
How to make costom status
no
Chatgpt
I've already tried it, he throws off the code with errors
Skill issue
lol
VirusTotal's API lets you upload and scan files, submit and scan URLs, access finished scan reports and make automatic comments on URLs and samples without the need of using the HTML website inter...
It’s definitely possible but there is a rate limit
anyone abl to help me with my discord bot?
just ask your question and somebody will answer
i have trouble running my discord bot, anyone ableto help?
Remember to:
• Ask your Python question, not if you can ask or if there's an expert who can help.
• Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
• Explain what you expect to happen and what actually happens.
does anyone know a good tutorial about raspberry pi discord bot hosting?
Hello, I need help with my bot. Anyone wants to help me?
I am an expert!
Yes I definitely can help
Even if it's quantum computing
same
Check my post in the #1035199133436354600 forum
What OS does it have installed
Well that's the thing, I don't have one yet, I don't know what to choose, I don't know how it works and what I should know before starting this
Install ubuntu
Then use this guide https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Can you link concrete post pls
Hi, someone know to do discord slash command, in end of code is one slash command but its don,t working.
https://paste.pythondiscord.com/CMGA
It's okay check my guide
thanks !
- You have both client and bot. For what reason?
- You ain't syncing anywhere
Also a bunch of bad indents but I am assuming that's pasting problem
Alright, here it is
https://discord.com/channels/267624335836053506/1175815004440756284
i don't know i'm a beginner programmer
I paste this again here
import discord
from discord import app_commands
from discord.ext import commands
import json
import os
# Get configuration.json
with open("configuration.json", "r") as config:
data = json.load(config)
token = data["token"]
prefix = data["prefix"]
owner_id = data["owner_id"]
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# The bot
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor.default()
# Load cogs
if __name__ == '__main__':
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
bot.load_extension(f"Cogs.{filename[:-3]}")
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
print(discord.__version__)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name =f"{bot.command_prefix}help"))
#@bot.command()
#async def hello(ctx):
# await ctx.send("Hello, I'm a Discord bot!")
@bot.command()
async def embed(ctx):
embed=discord.Embed(title="Sample Embed", url="https://realdrewdata.medium.com/", description="This is an embed that will show how to build an embed and the different components", color=0xFF5733)
await ctx.send(embed=embed)
@tree.command(name = "test", description = "My first application Command", guild=discord.Object(id=1168187306822336533)) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_command(interaction):
await interaction.response.send_message("Hello!")
bot.run(token)
You being a beginner makes it harder to help you
So we typically ask to learn more before blindly trying stuff
Hey again, I've created a class for a dropdown menu as follow:
class OCModifier(discord.ui.View):
def __init__(self, bot, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bot = bot
self.modified_field = ""
self.colour = None
@discord.ui.select(
placeholder="Select a field to modify for your OC.",
options=[
discord.SelectOption(label="OC Name", value="oc_name"),
discord.SelectOption(label="OC Age", value="oc_age"),
discord.SelectOption(label="OC Nationality", value="oc_nationality"),
discord.SelectOption(label="OC Gender", value="oc_gender"),
discord.SelectOption(label="OC Sexuality", value="oc_sexuality"),
discord.SelectOption(label="OC Universe", value="oc_universe"),
discord.SelectOption(label="OC Story", value="oc_story"),
discord.SelectOption(label="OC Picture", value="oc_picture"),
discord.SelectOption(label="OC Colour", value="oc_colour")
]
)
async def select_field(self, interaction: discord.Interaction, select_item: discord.ui.Select):
self.modified_field = select_item.values[0]
self.children[0].disabled = True
await interaction.message.edit(view=self)
await interaction.response.defer()
self.stop()```
But I realised it'd be more practical to have the options to depend on parameters given by the user to have a general class. So I tried doing the following:
class DropdownMenu(discord.ui.View):
def __init__(self, bot, labels, values, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bot = bot
self.modified_field = ""
self.colour = None
self.labels = labels
self.values = values
@discord.ui.select(
placeholder="Select the name of the OC you want to modify")
async def select_field(self, interaction: discord.Interaction, select_item: discord.ui.Select):
self.modified_field = select_item.values[0]
self.children[0].disabled = True
self.options = [discord.SelectOption(label=label, value=value) for label, value in zip(self.labels, self.values)]
await interaction.message.edit(view=self)
await interaction.response.defer()
self.stop()```
But now it says `unresolved reference` in the decorator
Is there a way to do what I want ?
opened an issue in #1175842691855175720
unrelated to my previous question about raspberry pie, but would you be able to help?
I just installed discord-py-slash-command in Python 3.11, but I am still encountering the ModuleNotFoundError. How can I fix this issue?
Traceback (most recent call last):
File "d:\.vscode\discord-bot\bot.py", line 3, in <module>
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash
Why use a one or more years old outdated library
why not use discord.py that has slash commands support
Why not just use discord.py or some other fork
I'm really confused why it doesn't work, please if anyone knows, hit me up
Does anyone know how to make a command on discord.py (no slash commands)
@minor solstice I'm kinda of a beginner dev so what do I put here?
Can anyone help me?
personally i flashed Raspberry Pi OS 64-bit Lite onto mine which overall worked out pretty well, but that's cause i already knew how to remote SSH into it and do most of the setup from the command-line (the Lite edition doesn't provide a desktop)
regardless of the OS i would recommend using a 64-bit build, especially if you're installing compiled packages that don't have 32-bit ARM wheels (numpy, Pillow, etc. i think a lot of compiled packages don't have armv7l)
++ pick the rpi oses unless u have bit of experience setting up headless pc's coz u would have to configure ssh and vnc clients manually raspian has those pre installed
there is a official image flasher as well rpi imager which helps you with the configuration
await ctx.send([i.name for i in bot.commands])
@shrewd apex bro I meant no slash commands
I told my friend and he said it was slash command
damn well sorry to say but it isnt slash command code 🤡
it uses context
not interaction
Oh that's funny becuz I put a string at the end
Lemme check the problem
@shrewd apex 💀
i think its probably for better that u learn python before attempting a discord bot also do use a pc for coding, programming in mobile is tedious to say the least
Ur kinda right
hey whats that website where you post long-ish code at?
i know you guys have some kind of custom one
nvm i found it
https://paste.pythondiscord.com/43FA
basically the bot is meant to show a slash command called /information but it just isnt creating, the bot has administrator
ping me if you respond
information is not a Slash command, it's a normal prefixed command
oh damn ty
!d nextcord.slash_command
class nextcord.slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., dm_permission=None, ...)```
Creates a Slash application command from the decorated function. Used inside [`ClientCog`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ClientCog)’s or something that subclasses it.
thanks
you're welcome
It's nextcord.slash_command, not nextcord.ext.commands.slash_command
how can i create a thread in forum channel?
!d discord.ForumChannel.create_thread
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, content=None, tts=False, embed=..., embeds=..., file=..., files=..., stickers=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this forum.
This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages).
You must send at least one of `content`, `embed`, `embeds`, `file`, `files`, or `view` to create a thread in a forum, since forum channels must have a starter message.
Simple as that
Show your code
just pasted that
is it possible to bypass the 28 day timeout limit?
create_thread is a method of ForumChannel
Copy and pasting it will not work
okay ty
there's another way though
No
Dyno only goes up to 14 days..? So 28 isnt that bad lmao
So maybe ask DYNO to upgrade :)
They probs have a reason
Nope
ok
28 days is good enough :/
I'll just use Carl to mute people for 999 years
okay 👍
Yo
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x00000000049F1410>:
Traceback (most recent call last):
File "C:\Users\phil\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\application_command.py", line 918, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\phil\Desktop\projects\python\horizon_management\commands\giveaway.py", line 80, in giveaway
self.bot.loop.create_task(self.update_giveaway(ctx, message.id, end_time_timestamp))
^^^^^^^^^^
AttributeError: 'PartialInteractionMessage' object has no attribute 'id'
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'PartialInteractionMessage' object has no attribute 'id'
i hate python
How do I run this bot I'm so stuck https://github.com/WpuGael/Xtreme-/blob/main/xtreme-main.zip
upload the files of the bot, not the zip
What errors are you getting?
i just dont know how to run it i usually work with js not py
Go ask YT for that
what do i ask
well ik how to run a normal bot but this one is confusing there is no place for token and it just looks odd
Why are you running it if you don't know what it does?
ik what it does
i just dont know how to run this specific one
Before running anything like this you should go over each piece of code to see what it does
Ik what this does and everything it does i just having trouble running it
also, wherever you got the code, its mysql is just there in raw text
that the only part im confused
So you went over it?
it a copy of my discord bot but in py
Okay. Did you go over each part of code?
2209
Okay, and when it's running the bot where is it referencing the token from?
Bot_Token = os.getenv('TOKEN')
Okay, and what does os.getenv() do?
im pretty sure it accesses environmental vars
So, if we look at the beginning of the code what else involves environment variables?
load_dotenv?
loads .env files?
Correct
So, if we're loading a .env file and then getting an environment variable named TOKEN...
but technically couldnt i do Bot_Token = os.getenv('TOKEN') to bot_token = 'token' ?
If you wanted to