#discord-bots
1 messages · Page 325 of 1
Outside allows me to pull the data from the file in the decorators
and can still be used inside the commands/functions
what would the discordpy equivalent be to this?
if message.referenced_message:
return
```?
i assume it's checking if the message is a response?
for some reason he has a config.py file and a series of config.json files.
Which is fine I guess. just annoying lol
atp just rewrite the entire thing, lmao
I sorta am lol
Im trying to keep the integrity of the original setup so those who have already used it before know how to use it in future
!d discord.Message.reference , assuming the code was referring to this attribute
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
ty. i believe it's that.
I believe he's trying to ignore messages that are in response to others.
Why does this guy insist on always opening a json file with every command
especially when they're on_message lol
I do like to dabble in json when I'm lazy. But it is russian roulette
Json db isn't even close to programming crimes I committed in past

Hi, does someone here have experience with sending pictures with a discord bot?
Ye
Okay so if you are familiar with Images in Python you should get the following i think:
`testzero = Image.open(r'C:\Downloads\tes2.png')
testone = Image.open(r'C:\Downloads\test.jpg')
get the correct size
x, y = testone.size
testzero.paste(testone, (0,0,x,y))`
Now i try to send that via await message.channel.send(file=testzero)
and get this Error: " 'JpegImageFile' object has no attribute 'to_dict' "
Save the image object into a discord.File:
with io.BytesIO() as img_buf:
testzero.save(img_buf, format="png")
img_buf.seek(0)
await message.channel.send(file=discord.File(img_buf))
Discord.py provides a bot class with proper command handling and all. You should use it instead of implementing commands in one big on_message event handler if this is the case
Ah okay, can you reccommend an example/documentation? Im new to Dc bots
ill try that. Why you need this io.Bytes stuff etc?
discord.File's constructor requires an fp parameter which is "a filename (string), pathlib.Path object or file object"
io.BytesIO is a file-like type
!d io.BytesIO
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close) method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase) and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase):
okay thx
What do you seek
@brazen raft Now it does post something but its that :
😮
you mean instead of ìmg_buff` ?
hm well renaming the untitled file works but how can u make it a working picture before sending it
discord.File(img_buf, "lol.png") or whatever
What do you mean
Disnake
ah im stupid sorry
that works
!pastebin
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.
Hm got a new Problem tho. I can do all resizing and pasting now but i have this problem:
As you can see, somehow the opacity information gets lost as the satin texture should be slightly tranparent on top of the backround layer
jpg don't support transparency
Not for testone
ye that was test code
i got new
thats it
Guys is there a better and library with more features than discord.py ,I don't see a reason to switch to any other but just wana know
there is an upper limit to how many features you can support, bound by the discord api
so not really, no
it's not like you can have 110% API coverage
robin free for a few moments?
depends on what for
!remindme 2h this
Your reminder will arrive on <t:1701022993:F>!
Well there's voice receiving
Idk if dpy supports it
But some forks do
There are libraries with more conveniences and different implementations of things
Like disnake has smart sync and .send() shortcut
- at the start, i would show off examples of each component (or at least common ones) so the reader can immediately see what they do and have a rough idea of d.py's syntax
- i wouldn't consider a BaseView class to be that important since discord.ui.View is already sufficient to directly subclass from, so i would bring up that pattern near the end ("subclassing discord.ui.View works well for most cases, but if you find yourself repeating certain features like error handling, you might find it worthwhile to make a BaseView...")
- for full sentences in comments, it's worth punctuating them for readability
# to handle errors we first notify the user that an error has occurred and then disable all components``` instead of the above, rewrite it as: ```py
# To handle errors, we will first notify the user that an error
# has occurred and then disable all components.```
- in
BaseView._disable_all(), instead ofif isinstance(item, discord.ui.Button) or isinstance(item, BaseSelect):which references an undocumented class, i would writeif hasattr(item, "disabled"): - in "Using our view", i suggest clarifying in between the two examples that while assigning callbacks work fine, d.py conventionally uses the decorator and/or item subclass style for defining callbacks (personally i wouldn't mention monkeypatching at all)
- i suggest having a separate section for "Persistent Views" after buttons and select menus rather than two sub-sections about "Persistent Buttons" and "Persistent Select Menus", since it's a distinct concept from either components
- i've written a guide about persistent views if you want to reference it: https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
- i suggest having a separate section for "Dynamic Items" since they're a distinct concept from buttons and select menus (also this is my first time hearing about their existence, i thought it was still in design hell
) - there's a "dosent" typo in Modals

- as per BaseViews, i wouldn't consider BaseModals that important, but both could be discussed together in one section at the end like "Creating Base Classes" or something
mhm ty for the review
ill work on the changes if u have some other suggestions feel free to make a pr :p 
can i ask questions here even if i loaded with disnake?
yeah
disnake, never heard of that
Ohk So I'm trying to remove the help command thats by default but its not getting removed.
Here's the code: https://paste.pythondiscord.com/HMUQ (Pls ping for reply!!)
commands.Bot(help_command=None...
or
bot.reomve_command("help") # prefix not needed
whats the improvement of disnake over discord.py?
its not improvements perse its design differences
ive always been a discord.py user as support has been great for it
That's the case since its development was resumed
disnake is a fork that was created when discord.py was abandoned
ah i see
features ars the same few disnake features i like are
- context menus (user and message menus) in cogs (decorators)
- hot cog reloading
- slash command group decorators (dpy dosent have this they use group cogs)
wdym in cogs?
dpy has context menus
yeah but u cant declare them in cogs
Not in cogs
like how u would expect to
https://github.com/Rapptz/discord.py/issues/7823#issuecomment-1086830458 take a look at this
creating additional custom cogs for that doesnt seem like too big of an issue
solely for context menus
You don't get it
i dont
You can't add context menus in cogs like you can create commands in cogs
thats kind of annoying
Adding context menus in cogs will just do nothing or fail, unlike doing them outside of cogs in your e.g. main.py file
yea
so you'll have to add custom decorators for main.py cogs
to get the currently used Cog and therefore enable or disable the context menu
which does make your main.py less organized
Here's your reminder: this
[Jump back to when you created the reminder](#discord-bots message)
@commands.hybrid_command(name="impersonate")
@commands.guild_only()
async def impersonate(self, ctx, member: discord.Member, *, message):
"""
Impersonate as another member for fun!
**Usage:** impersonate [member] [message]
**Examples:**
- `impersonate @member drugs are good.`
"""
accept = await ctx.send(f"Impersonating...", ephemeral=True)
# Copy member's profile information
nickname = member.display_name
avatar_url = member.avatar.url
# Create a webhook
webhook = await ctx.channel.create_webhook(name=nickname)
# Send a message as the webhook
await webhook.send(
content=f"{message}",
username=nickname,
avatar_url=avatar_url
)
# Delete the webhook after sending the message
await webhook.delete()
await accept.delete()
Can this be against ToS?
like privacy?
Privacy is uh when you access other user's secret data so not the case
But might be copyright
How so?
Might be that member being pissed
its just copying display name and profile
But I am not law expert
XD
In these cases it's best to ask discord themselves
Eh if they complain then that is just a cry baby ig
How am i gonna ask discord myself 😭
Through discord support
They never respond 
Maybe cuz they have a crush on you
Within reasonable time
but thats just my thoughts
They'd gift me infinite nitro
Worst case scenario, other members may fall for it
@bot.tree.command(name='ai_ask')
async def ai_ask(ctx, question : str):
async with aiohttp.ClientSession() as session:
response = await session.post(url=API_URL, headers=HEADERS, data={'prompt': f'{question}\\n\n', 'max_tokens': 50})
result = json.loads(await response.text())['choices'][0]['text']['restarted']
await ctx.send(result)
``` why it dosent work?
I have no idea why, but tip: You can use (await response.json()) instead of json.loads(await response.text())
XD
That would be sad lol
even tho it would say BOT by the webhook
Slash commands have a discord.Interaction instance as the first argument, and Interaction doesn’t have a send method
Good catch
Can you see how many reports a bot has?
I see pycord somehow looks clean to me , idk if it's better
you will like disnake then
pycord abstracts all the functionality from the user in the name of simplicity which counterintuitively makes the user experience worse
They’ve also displayed their inability to create new concepts and frameworks, and the maintainers steal code without permission or credits
Reports, as in the built in reporting system?
ye
@vapid parcel check dms, thanks ✌️
Bruh what
I sent you a dm, I need help with something 🙂
It’s not possible
Damn, thats fine
anyone know what's wrong here? (using Disnake btw)
Yeah. I want help as fast as i can get lmao
bro click the link i replied
yh
btw guys to make bold text in an embed, what do i do?
And what about in this type
No girls? Okay then
?
Like in discord put it in **
No in an embed code
Yeah the answer is still the same
oohk so i just put the same things in the code as in discorde after the apostrophe right?
Yea try
ooohk
You can use markdown only in embed description and fields values, titles and footer do not support it
Oohh ok
Ohoho k
got it. But any text (including footer and title) can be bold right?
I just said
Just by adding asterisk inside the apostrophes?
Titles and footer do not support markdown
Hence you can't make anything bold or cursive or whatever
Wait so no bold asw?
oooh okkk. Sad
Do you know what markdown is
Lmao i thought with backtick
It is what discord uses for all this bold and cursive stuff
Want to inject some flavor into your everyday text chat? You're in luck! Discord uses Markdown, a simple plain text formatting system that'll help you make your sentences stand out. Here's how to d...
ik ik got it
Ok so i want to add a url thumbnail to an embed. How do i do that?
@vale wing do you know how to?
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing `None` removes the thumbnail.
Pay attention that url is keyword only
Its a method,not an attributr
oooh ok. So what do i do
@group.command(name="remove_whitelist", description="Removes a user's whitelist")
async def remove_whitelist(self, interaction: discord.Interaction, gamertag: str, user_id: int):
How'd I make this so that I can both inputs are not required but at least one is?
You add logic and respond with an error accordingly
Ah, so discord won't automatically assume that they are both required?
As that was my worry.
it will if you don't provide a default
Ah, so how do I stop that from happening?
Set default arguments
(P.s. thank you for helping me with the commands and everything a day or two ago as I do understand it really well know!)
As in:
gamertag: str = None
Yes
Perfect, thank you!
python main.py Traceback (most recent call last): \New folder\main.py", line 12, in <module> from discord import Webhook, AsyncWebhookAdapter ImportError: cannot import name 'AsyncWebhookAdapter' from 'discord' (C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
from discord import Webhook, AsyncWebhookAdapter
doesnt work-any-fix?
code:
`# webhook-for-logs
WEBHOOK_URL = 'my-webhook'
@bot.event
async def on_command_error(ctx, error):
error_channel_id = 1178625906626023484 #channel-id
# error-of-bots
error_channel = bot.get_channel(error_channel_id)
if error_channel:
error_content = f"Command used: {ctx.message.content}\nError: {str(error)}"
await error_channel.send(error_content)
# error-sent-by-webhook
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url(WEBHOOK_URL, adapter=AsyncWebhookAdapter(session))
await webhook.send(f"Command used: {ctx.message.content}\nError: {str(error)}")
# error-cmds
print(f"Error in command '{ctx.command}': {error}")`
Can someone help me with reload real quick?
:incoming_envelope: :ok_hand: applied timeout to @vapid parcel until <t:1701080191:f> (10 minutes) (reason: newlines spam - sent 101 newlines).
The <@&831776746206265384> have been alerted for review.
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.
Okay
mb, didnt know i was gonna get muted for sending code 😭
Just wondering why unload isnt working
load works, but unload doesn't... just really confused on why.
What about it isn't working?
Can you help?
How can i get a subcommand of a subcommand of a basecommand?
get or make?
Get
whar
omaga
With only the name
guys is pycord/disnake better than discord.py, just a dumb question from me
ugh, such an hard topic
i don't see a reason to shift to any other but i wana know for my knowledge
this question reminds me the good ol' battles here to state the best library
i not mean best but wana know if disnake or pycord have any benefit over discord.py
what are you using currently?
not using but i have used discord.py before
ok so, pycord (objectively) has some big style issues and other problems, they implement a lot of things for you so it might seem easier but actually it restrict the possibility to handle certain things yourself
i don't think that i need to describe d.py, you used it before, it has some little design issues etc etc, but it's cool
and you can imagine disnake as d.py but with additional things, some things are designed better than d.py
now all of these descriptions are non-detailed and based on what i have heard (for pycord), what i have experienced myself (d.py, disnake), all of these are my opinions (just saying this to prevent someone from coming and start a battle)
i work a lot with disnake and my opinion is that it's better than d.py for app commands (Slash commands, message commands, etc...) and UI components
so it means disnake is discord.py + some other features?
probably someone else will come and share other opinions
btw i see that we can't have interaction and prefix commands together i guess in disnake
i guess ill try disnake some other day
Anyone got a reference guide I can use for keywords in discord.py?
Like for kicking, banning, adding roles, just something to reference from.
you mean hybrid commands? that was a choice of the mainteiners
with some extra logic you can make them
why don't you use the official docs?
How do i delete a row from a database in sqlite3? Whats the command?
#databases but it's actually DELETE
Ohh ok. So DELETE FROM table_name(?, ?, ?, ?)
Check the link
aright
python main.py Traceback (most recent call last): \New folder\main.py", line 12, in <module> from discord import Webhook, AsyncWebhookAdapter ImportError: cannot import name 'AsyncWebhookAdapter' from 'discord' (C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
from discord import Webhook, AsyncWebhookAdapter
doesnt work-any-fix?
code:
code:
`# webhook-for-logs
WEBHOOK_URL = 'my-webhook'
@bot.event
async def on_command_error(ctx, error):
error_channel_id = 1178625906626023484 #channel-id
# error-of-bots
error_channel = bot.get_channel(error_channel_id)
if error_channel:
error_content = f"Command used: {ctx.message.content}\nError: {str(error)}"
await error_channel.send(error_content)
# error-sent-by-webhook
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url(WEBHOOK_URL, adapter=AsyncWebhookAdapter(session))
await webhook.send(f"Command used: {ctx.message.content}\nError: {str(error)}")
# error-cmds
print(f"Error in command '{ctx.command}': {error}")`
can-anyone-help??
adapters don't exist in 2.0 anymore, you only need to give it the session
https://discordpy.readthedocs.io/en/stable/api.html#webhook ```py
from discord import Webhook
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')```
ty
can i edit flowups message app_commands?
of users?
yep
no
well that is sad
yes, interaction.followup returns an application webhook which will always give you a WebhookMessage object you can edit after you send your message
(the 15 minute token expiration still applies as usual) py class MyView(discord.ui.View): @discord.ui.button(label="A button") async def on_click(self, interaction, button): await interaction.response.send_message("Response") await interaction.edit_original_response(content="Edited response") message = await interaction.followup.send("Followup") await message.edit(content="Edited followup")
thx
try reading it again
Yeah So what I wanna do is the user should be able to delete his journey (basically delte user info row from database) if he has one. If he hasn't there would be message saying "you haven't started journey yet"
Here's the code. Pls tell me how do i change according to that:
Oh boy
You’re mixing code from a prefixed command, slash command and a discord.py fork
i'm using disnake
and i'm fairly new
pls tell me how to fix this
@final iron
not to mention a sync db
And do this asw?
even if i did u wouldn't understand unless i personally modify the code or spoonfeed u i can tell u whats wrong rest is upto u
- bot.command is prefix command so it has context not interaction
- u cannot send buttons like that u need to attach them to a view
- a synchronous database is blocking the main event loop
Ohhk. I'll try doing something
May i ask whats a view?
!d disnake.ui.View
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
Alternatively, components can be handled with [`disnake.ui.ActionRow`](https://docs.disnake.dev/en/latest/api/ui.html#disnake.ui.ActionRow)s and event listeners for a more low-level approach. Relevant events are [`disnake.on_button_click()`](https://docs.disnake.dev/en/latest/api/events.html#disnake.on_button_click), [`disnake.on_dropdown()`](https://docs.disnake.dev/en/latest/api/events.html#disnake.on_dropdown), and the more generic [`disnake.on_message_interaction()`](https://docs.disnake.dev/en/latest/api/events.html#disnake.on_message_interaction).
New in version 2.0.
Hello
Can anyone help me with interactions.py?
Or does anyone even know interaction.py?
💀
discord.py remains king
discord.py or js?
should i switch?
discord js is probably used more for the higher-end discord bots, but also C# is commonly used with .NET
discord.py is definitely compatible though, so dont worry about that
for discord frameworks in python, i just like discord.py the most as the support for it is big
what command u need to make a channel with custom name use ctx
or interaction anything
So I made a python discord bot that responds to commands that start with "$" and I made a say command that has the command "$say [message]" which will say the message as the bot. But whenever the say command code structured like "Fun_Commands/say.py" it doesn't work. But when I have the exact same code, in the "main.py" file it works.
Define doesn’t work
You want to know how to make a text channel?
Saying something doesn’t work isn’t helpful. It tells us nothing about what actually happened, and what the output is. You’ve also shared no code
import discord
from discord.ext import commands
import os
import json
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.command(name='say')
async def say_message(ctx, *, message):
# Check if the command invoker has the "manage_messages" permission
if ctx.author.guild_permissions.manage_messages:
# Delete the original command message
await ctx.message.delete()
# Create an embed with the original message and user information
embed = discord.Embed(
description=message,
color=discord.Color.blue() # You can customize the color
)
# Add the user's name and avatar to the embed
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)
# Load configuration from file
config_file = os.path.join(os.path.dirname(__file__), 'config.json')
with open(config_file, 'r') as f:
config = json.load(f)
channel_id = config.get('channel_id') # Get channel ID from config
print(f"Channel ID: {channel_id}") # Debugging print
# Get the channel using the channel ID
channel = bot.get_channel(channel_id)
if channel and isinstance(channel, discord.TextChannel):
try:
# Send the embed
await channel.send(embed=embed)
except discord.HTTPException as e:
await ctx.send(f"Error sending embed: {e}")
else:
await ctx.send('Error: Unable to find or send to the specified channel.')
# Send the plain text message to the current channel
await ctx.send(message)
else:
await ctx.send('You do not have the required permissions to use this command. Please contact an admin.')
You there?
It wasent generated using chat gpt
What makes you think that?
The comments are obvious
I made the comments myself 🤣
It helped me to remember that I can change whatever was needed to change
Kinda funny that you think it was commented using ChatGPT
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
print('tested')
channel = after.channel
if channel.id == 1173576697698848768:
channel = await after.channel.clone(name=f'{member.display_name}\'s Channel')
await member.move_to(channel)
This isn't working
Your indentation is completely wrong
Paste code as text, not screenshots
Yes, and the indentation was wrong
Repaste it with the correct indentation
View #❓|how-to-get-help , this is outlined
Pasting made it wrong
It isn't wrong
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
print('tested')
channel = after.channel
if channel.id == 1173576697698848768:
channel = await after.channel.clone(name=f'{member.display_name}\'s Channel')
await member.move_to(channel)
Is the if statement truthy?
It is true
Show me your current code and terminal output please.
Hm.
It doesnt create the channel ?
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState).
The following, but not limited to, examples illustrate when this event is called...
ima look at docs rq.
Do you have logging setup
nope
Set it up, see if there are any errors
okay
How to do sub commands for hybrid? needing to know how to do Group + sub
yes
Do you want to create a channel in the guild that the command was invoked in?
Or clone the channel the command was invoked in?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel) for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
say both i need to learn abt making channels
This would create a text channel in the guild the command was invoked in
Context.guild will return the Guild instance
!d discord.TextChannel.clone
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to do this.
New in version 1.1.
That'll clone the channel the command was invoked with
You can get the TextChannel instance with Context.channel
What specifcally are you trying to learn?
imo they're pretty simple. The only thing that I see people trip on is the overwrites
channels but now i know how
File "C:\Users\HP\Desktop\pokebot\main.py", line 3, in <module>
import requests
File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\__init__.py", line 64, in <module>
from . import utils
File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\utils.py", line 28, in <module>
from .cookies import RequestsCookieJar, cookiejar_from_dict
File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\cookies.py", line 164, in <module>
class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'collections' has no attribute 'MutableMapping'```
whats this error, I tried python 3.10.5, 3.11.5 and 3.8 all give the same error
Never mind, It's just a conflict with the packages I have, Use a VENV it works
Is there a way to enable community through discord.py or the guild owner has to enable it themselves?
apparently it can 
https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.edit
community (bool) – Whether the guild should be a Community guild. If set to
True, bothrules_channelandpublic_updates_channelparameters are required.
https://discord.com/developers/docs/resources/guild#modify-guild
Attempting to add or remove theCOMMUNITYguild feature requires theADMINISTRATORpermission.
guys this is my bot.py
import discord
from discord.ext import commands
from src.config import config
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def setup_hook(self) -> None:
print(f"Logged in as {self.user}")
bot = Bot(command_prefix=config.prefix, intents=discord.Intents.all())
and main.py
from src.bot import bot
from src.config import config
if __name__ == "__main__":
bot.run(config.token)
why i getting this error, i not able to find where i made mistake
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "C:\Users\dell\Desktop\projects\python\xbot\src\__main__.py", line 5, in <module>
bot.run(config.token)
File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 849, in runner
File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
TypeError: object NoneType can't be used in 'await' expression
async def setup_hook
oh , oops i made a dumb mistake
thanks for help
How do I make a command that wont let players run it again for another 10 minutes
text or slash command
slash
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown) is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
your py-cord version is out of date (<2.4.0)
How can i find a subcommand of a subcommand of a basecommand.
Like /help voice setup join-2-create and he get the voice setup join-2-create command.
i am pretty sure u cant have slash commands of more than depth 1
thats a discord api limitation
max is /parent_group sub_group command
Does anyone have a tutorial available for how to setup a Discord bot for multiple servers?
Like Dyno for example, how to get it so that the bot is ready to be setup in multiple servers.
I'm not sure if I understand what you mean
there is nothing special you have to do
use the invite link to invite bots to any servers you want to
like in the context of making sure your features can be configured by different guilds and work independently? that's where your database design is important, making sure your tables can uniquely associate data/settings for each guild where appropriate (for example, you might have an automod_config table that uses (guild_id) as its primary key and the rest of the columns are settings for that guild's automod, or you might have an inventory table that uses (guild_id, user_id, item_id) to uniquely identify each item a user has for a particular guild)
and of course replacing any hardcoded guild/channel/role IDs with database queries
Yeh, I'll need to as it'll be for managing their game server so they may have different paths for stuff.
hello guys, I need a bot for discord to open/close timeouts on pd
What’s pd
police department
We’re gonna need more context on what you’re trying to do
open/close timeouts on police department is very vague
And personally I have no clue what that means
😂😂
whait
what
what
how do you expect us to help you? we have NO idea what you’re talking about
I need a bot for discord that can start my timer and calculate it while playing on a fivem sv e.g.:/clocking clock in/, clock out to see how much I played in pd on that sv
Okay so this is fivem
So you can’t just come in here and say this and expect us to understand what you mean. I don’t really even understand what made you think we would understand what you want.
It’s not. You instantly assumed you knew what you meant by open/close timeouts, what a PD is, what a sv is
fivem sever
I still don’t know how this clocking in/out occurs. You’re leaving out a lot of necessary context
is it possible to use logging for your own debugging? i tried
async def ping(ctx):
logging.info("Ping command called")
await ctx.send("Pong!")
but it doesn't work. i added a basic log handler but i dont see my output in it
yah
make a custom logger
import logging
logger = logging.getLogger(__name__)
...
@bot.command()
async def ping(ctx):
logger.info("Ping command called")
await ctx.send("Pong!")
If im making react roles how do i set an unlimited time limit to react, i dont want it to timeout
yo
@client.event
async def on_scheduled_event_create(event):
await event.cancel(reason='womp womp')
print('event was cancelled.')
use persistent view
so this code works ^^^
the thing is, i wanna make the creator of the event get dmed by the bot.
(I did research, no results that helped.)
!D discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
!d discord.ScheduledEvent.creator
The user that created the scheduled event.
@slate swan like this?
@client.event
async def on_scheduled_event_create(event):
await event.cancel(reason='womp womp')
await event.creator.send("Event Cancelled.")
print('event was cancelled.')
whats that?
I SWEAR I TRIED THIS BEFORE AND DIDN'T WORK BUT NOW DECIDES TO WORK 😡😡😡
yea
I swear bro 😭 I kept rereading the scheduled event part more than 5 times but now it decides to work
How did I just learn this exists:0
Also anyone know if there’s documentation regarding @lusty spear? Or template for Grafana
What do you mean specifically? Dave isn't a library so it doesn't make too much sense to have documentation
I mean generally set up instructions, I saw the readme bit, was wondering if there’s anything else or if that’s all you need, and usage stuff
Ah you're trying to self host Dave?
Purely out of curiosity yes
README should have all the setup instructions
knowing how to configure prom and grafana will also help
I’ve seen tutorials and documentation so rough idea, stuff is always more fun when you have zero idea what your doing
Seeing as I’m unfamiliar with the technologies, I was just curious as to weather any further explanations existed
Does discord.py have native slash command support?
Yup
YouTube has plenty of good tutorials
So do their docs
Alright
Is it as simple as setting the command_prefix to /
Or is it more complicated
Unfortunately not, you need to use a different thing to declare them(app_commands instead of ext.commands), and also has a thing called a tree and syncing
Ngl don’t fully understand myself but to just get it working fairly easy
Lemme find an example for ya
Alright thank you
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py example from the official repo, there’s also a pretty good stack overflow answer describing it here https://stackoverflow.com/questions/71165431/how-do-i-make-a-working-slash-command-in-discord-py also remember documentation is your best friend
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
I am trying to make a slash command with discord.py I have tried a lot of stuff it doesn't seem to be working. Help would be appreciated.
Thank you
No problem, happy deving
Is there a way to print current page with every page switch in pycord pagination? cant find a way to do it
class shopCategory(discord.ui.View):
@discord.ui.select(
placeholder="Pick a section",
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label="Crates",
emoji="",
description="View the crates shop!"
),
discord.SelectOption(
label="Limited time offers",
emoji="✨",
description="View FiveaSide limited time offers!"
),
]
)
async def select_callback(self, select, interaction):
if select.values[0] == "Crates":
crate_types = ["Base", "Elite", "Divine", "Golden"]
crate_buttons = crateButtons(crate_types)
crates_pages = [
create_crates_embed(),
coming_soon_embed(),
]
paginator = pages.Paginator(pages=crates_pages, use_default_buttons=True, timeout=60, custom_view=crate_buttons)
print(paginator.current_page)
await paginator.respond(interaction)```
No it doesn’t
All the tutorials have issues, and even if they didn’t they’re fundamentally flawed
There’s always an issue with something, and there’re a good resource to learn the basics imo
First statement is false. There are many written tutorials that don’t have issues
I mean on a nitpick level, if you try hard enough there’s gonna be some “issue” but text tutorials are more comprehensive normally yes
Video tutorials have major issues though. Not small ones
Depends on the tutorial
Send one you think is good
Though even with issues they can still be a good starting point for basics
I have never seen a good, up to date YouTube tutorial
If you point a beginner in the wrong direction they will continually follow it. Good tutorials are especially important for beginners as it builds the foundation for their bot
Only good video tutorial I’ve ever seen was pre v2
I know a good tutorial for beginners,, chatgpt 💀 learn python using !resources
There is some good tutorial still iirc, like glowstik and some other
But yeah some video of him has some problem but he updated those in this latest videos
I am creating a bot for a game that is relatively small, for this bot I need to store usernames in a variable that will be used to do console commands in game . My question is, how can I store user input into a variable with discord commands?
You need a global variable for that, but i suggest use a database, but since its small you can use json
When I say small I mean like a million people play that game
Cute
I have created a discord bot, I don't know how to code, so can someone help please?
I want to send a text file and the bot will decode it and send me the file. @naive briar @languid sequoia @shrewd fjord
Please don't ping random people; just ask your question and someone will (probably) come by to answer it
I’ll be honest I probably know less about coding than you, I started learning Python less than 2 weeks ago.
I am the last person you should ask about coding help
What are you trying to decode?
Binary numbers to hax decimal
import sys
arr = bytearray()
with open(sys.argv[1], "rb") as f:
for b in f:
arr += bytearray(b)
for i in range(len(arr)):
arr[i] = ~arr[i] + 256
with open(sys.argv[1], "wb") as f:
f.write(arr) @final iron
@grand sleet
Not really sure what your use case is nor how much Python you know (you mentioned you started recently) but you'll probably want to use a database file to store such information
I'd recommend learning SQL and becoming familiar with the sqlite3 standard library module
@slate swan plz help me brother
What with
I have created a discord bot, I don't know how to code, I want to send a text file and the bot will decode it and send me the file.
import sys
arr = bytearray()
with open(sys.argv[1], "rb") as f:
for b in f:
arr += bytearray(b)
for i in range(len(arr)):
arr[i] = ~arr[i] + 256
with open(sys.argv[1], "wb") as f:
f.write(arr)
You won't be able to do anything with your bot if you don't know how to code at all
Brother just give me the code and I can apply please.
Sorry but we don't spoon feed code here, and I don't know what you mean by "decode".
Like I send Text file than bot decode my text file and send me
You'll need to learn stuff like data types, control flow, functions and some OOP before you even begin making a bot
@languid wagon where I learn in hindi language
skip stuff that you already know
how do I get a discord bot to respond more than once to a slash command?
followup and send or edit the original response https://fallendeity.github.io/discord.py-masterclass/slash-commands/
A hands-on guide to Discord.py
guys i have a slash command called ping, i want a decorator which gets description and name of command, how can i do that, its a decorator question, but ok
What?
Decorator sets description and name of command
To get description, you need to get the command object
Nothing to do with decorator
I was just thinking of a decorator with which I can decorate my commands and generate help command from that
I'm pretty sure standard command decorator has the description kwarg. Also you can just add a docstring to your command function, it will be converted to description
No, I want something which can get me all slash commands of my bot with their titles and descriptions
is this for a help command?
Yep
do you really need one for a slash command bot
discord already kinda provides that for you
I want a help command though for a clean interface
The discord one lags pretty well
what library are you using?
Dpy ⭐
i think you might be able to do something with your command tree
bot.tree.get_commands()
or walk_commands, you're probably gonna do it in a for loop anyway
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
Hi, how to get the message.content of a webhook? I tried doing this but I got a white space.
@bot.event
async def on_member_join():
await
I want to send a message to say welcome on a join.
What are you asking for help with specifically?
I want to find a chanell and send a message in it
A specific channel, or a random one?
A specific : )
You can use
!d discord.Client.get_channel if it’s in the cache, or if you have the ID
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
If you want to search by name you can use discord.utils.get and pass in the guilds channels as the iterable
Do you have the message_content intent?
where do i put it?
You’ll create a listener for the on_member_join event, and put it in the function
Do you know how to send messages to a channel?
no
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
@bot.event
async def on_member_join():
welcome_channel = bot.get_channel(0) # replace 0 with channel id
await welcome_channel.send("Your message")
how do i get the id
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
How to find the id of a chanell
Are you asking how to get it pythonically or through discord itself?
yes!
It’s not a yes or no question lol
discord
Discord definitely has a page on this
where?
You need to specify discord
it said right click and press copy id but i dont find it
First result on Google
#general join on Discord
where is advansed developer setting?
It’s a setting
i dont find it
user settings > advanced > developer mode
the box is so i dont show my bot token!
you shouldnt hardcode your token if its on replit, especially a public one
how do i hide it?
how are you hosting the bot btw?
open the secrets menu on the bottom left, read the article that it links to, and then move your token into a secret following their explanation
i dont
also consider resetting your token regardless, since its already been exposed
how?!?!?!?
in ur discord developer portal
https://discord.com/developers/applications
open your application, go to bot tab, regenerate your token
you leaked your token again...
ah that would make sense, gateway exit code 4004 means authentication failed
https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway
btw are you using sharex? they have tools to blur/pixelate/smart erase part of your screenshot instead of having to freehand crop it
but where do i put the token so no one see it
i dont have that
i do windoes + shift + s
A .env file
like this?
see https://docs.replit.com/programming-ide/workspace-features/secrets, same link you would have found from the secrets menu
Yes I've set it true and also check it works.
But some message which contains webhooks, it doesn't pick it.
Can I send the kind of message?
as in the message was sent by a webhook? what does it look like? empty content can also mean the webhook sent something else like an embed or attachment, without any content
like this?
This sent by karuta bot
I think it's webhooks not sure
judging from the checkmark that's a bot account, but either way that message has one embed
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
sure, now retrieve your token in your script using the os.getenv() function as described in the article
So embeds are usually img file? Or you can embed text also?
er embeds can represent an image from a url, but the one shown in the screenshot is a rich embed
python's output is also a rich embed
So that um, I don't have any work with that embedded image but with the text inside it
you can see the embed attributes you can access in the docs, and the reply to chili's message is how those attributes get rendered on discord
!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...
Okay I'll check this tomorrow, it's night now
Thanks for helping
hey dudes quick help with nextcor autocomplete #1179486206191476849
Need some help with button module #1179498785815154758
Do you know if there are any tutorials for this?
Have you got any examples as it would be setup for a fee of sorts to access certain features.
(Didn't mean to do twice, been up for ages 🤣)
Hi, I need help. My Google colab not can install !pip install chatterbot, Does anyone have the same problem?
maybe you can find some source code, but anything that's complex usually has to be designed by hand using what you already know
F strimg formating for embeds.description is not working like f'{x:<18}' it just prints without extra spaces for some reason
Result should be
Var1. 6
V2. 7
See the space between should be equal but it isent
Any idea y
can you paste the actual output from your bot? if you didn't use code blocks, the text will be very difficult to align using spaces because the discord font isn't monospaced
Yee i just got same idea from someone else ill try code blocks
I have two different files for my discord bot that work in different ways, is it possible to run both files at the same time and have everything work as if it was one?
If they're completely different, you can simply run them separately
python file1.py
python file2.py
One uses the @bot.command function and the other uses if.message.starts.with() function.
Not sure how different that is
Do the bots need to communicate with each other?
You can do this method if theyr'e independant
yeah in that case you can just do this
So do I just copy and paste that at the top of both the files with the file name instead of file1/file2?
@sick birch
no it's bash
you'd just run them separately
Alright
I was wondering if client.wait_('button_clicked', ) still works because i can't find it in docs

Have it ever worked is the real question
There's no such events as that
I've seen it in past some example codes but not sure if it's practical or not
There has never been such an event
Oh okay
a similar event does exist in disnake, if thats what you're referring to (though its called button_click there)
https://docs.disnake.dev/en/stable/api/events.html#disnake.on_button_click
Thanks
hey anybody here can test my bot pls?
Not mine completly but its a team
(dm)
Also need some help for it, Testing it on a seprate bot, Here is the paste:
https://paste.pythondiscord.com/KYGA
Does discord.Embed work when doing commands that use if.message.starts.with()?
Like, can you send an embed, or are you checking for a string inside the embed
Sending embeds, I’ve been having troubles doing it with that method
Also, is it possible to change the value of a variable depending on what guild the bot is in?
What does startswith have to do with embeds? startswith is a string method
Idk, I just thought I would make sure that the way I’m doing it will work
Generally, if you have an abc.Messageable you can send embeds to it
In my specific case, I’m working on a bot for a VR game, I also need to have a specific server ID for doing console commands in that game. However, including a server Id in a discord command is not desirable as it takes a bit of time to get. I want to store server ids in a variable that changes based on what discord you are in which would remove the need to have it in a discord command.
Alright
I’d just use a simple SQL database for that
By server IDs, you mean the VR server IDs right
Not Discord guild ones
For in game servers yes. I want to be able to input server ids personally though, the bot will be private.
Yeah, so id just setup a database for that, but if its private and only a couple you could just use a dict to simply it
Guild ID as the key, in game server as the value
Alright thanks
How can i check the voice channel's limit?
!d discord.VoiceChannel.user_limit
The channel’s limit for number of members that can be in a voice channel.
Thanks
guys how can i make my discord.py sync commands when a new command gets automatically, i have cog watcher which reloads cogs on update in file, so i want my bot to sync when command sget added?
Just use disnake it has that functionality ☺️
bot.tree.sync() you mean 👀
i have now sync commands on every file change in my watcher which will slow my app 💀
You need smart sync
what\
🫠
you mean i check for change in self.tree.commands?
It's all automated and smart
PR for disnake
maybe ill make my next discord bot with disnake
Try it and you won't want to switch back to dpy ever!
Anyways
but i found something missing that idk how to make bybrid commands in disnake
Who needs hybrid commands 😒
i need i guess
but tbh slash commands are slow
what do you think, we should focus onmaking slash or prefix commands?

If your bot doesn't need messages content slash is the only option
Bro is dedicated
Also slash provide better input filtering imho
Kinda annoying
Waiting for discord to add datetime selector tho
but we can't reply to commands while using slash cmds
Message commands
You on pc?
ye
Click message options and see apps
Those are message commands
Aka context menus
There's bookmark for example
oh you mean apps?
Ye
kk
ty for helpi guess i should give disnake a try
but i hate the sphinx designs which their docs have
Uh doesn't dpy use sphynx for docs as well
yei mean for both
btw do disnake also have hot reload for cogs?
no i guess
?
it does
i mean hot reload
wut i that
is*
https://github.com/robertwayne/cogwatch check this out
i made my own , no need
nextcord - Print out the AUTOCOMPLETE option selected by the user (not after invoking the command)
It's just locked: https://discord.com/channels/267624335836053506/1179681291596214292
oh
so people can help me even if its blocked?
i mean, this was the message i recieved
disnake does
if u want smart sync in dpy u would have to make it urself
Oh
u need to track slash commands and their relative data such as description parameters etc
That's easy I guess , I need to just sync commands on change?
yeah u would have records preferably along with some sort of timestamp and keep a track to sync
Don't i just sync all commands to guilds?
initially yes then further on only when some changes need syncing
How will I know if it needs syncing?
When to Sync
- When you add a new command.
- When you remove a command.
- When a command's name or description changes.
- When the callback's parameters change.
- This includes parameter names, types or descriptions.
- If you change a global to a guild command, or vice versa.
- NOTE: If you do this, you will need to sync both global and to that guild to reflect the change.
No I mean how will my bot know if it needs to sync?
u need to manually keep track
nextcord - Print out the AUTOCOMPLETE option selected by the user (not after invoking the command)
Hmm
Any idea how?
in the autocomplete function itself u get the current user input
So initially I make a list of registered commands?
yeah
I meant after selecting an option from Autocomplete
Is there a event for knowing if a command is not registered?
yeah autocomplete is triggered whenever there is an input in the field so once u the user picks the option it should trigger
yeah thats fine the thing is, it passes a nextcord.Member object as a string
!d bot.tree.sync u can get it from the initially synced commands
which is annoying
eh well u get the idea sync returns a list of synced commands
Like if I have a list of registered commands , and if I add a new command in my cogs and my watcher reloads the cog , so my bot is not going to know if I have added a new command
oh well
thats internally converted by user converters
passed of as None though?
u need to check if the command was registered or not
thats why i said sync gives a list of registered commands
when I take the inputs from an autocomplete, when I print user, instead of a Member object its a str...
I guess you not getting what i mean
is it None or is it str?
mb its just Str
whats the str? like the value?
So I will get a list of registered command initially, for example: I add a new command in my cog , my bot won't know it was added , how should I fix that?
bruh u have inital commands and now when reloading load the commands from that cog then match
@slash_command(name="remove_log",description="Remove a logged Moderation action.",guild_ids=attributes.TESTSERVER,default_member_permissions=(nextcord.Permissions(administrator=True)))
async def remove_log(self,interaction:nextcord.Interaction,user:nextcord.Member, action, reason):
print("Remove log")
# the main code
@remove_log.on_autocomplete("reason")
async def remove_log_type_auto(self,interaction:nextcord.Interaction,user:nextcord.Member,action):
print(action)
await interaction.response.send_autocomplete(ModLogs.find_one({"guildId":interaction.guild.id,"modHistory":{"$elemMatch":{"$eq":user.id}}}))
err
await interaction.response.send_autocomplete(ModLogs.find_one({"guildId":interaction.guild.id,"modHistory":{"$elemMatch":{"$eq":user.id}}}))
AttributeError: 'str' object has no attribute 'id'
print(user) once whats the value
print(f"user returns '{user}'") doing that
Ye that's my point , I don't know how do I get commands from a cog
!d discord.ext.commands.Cog.get_app_commands
get_app_commands()```
Returns the app commands that are defined inside this cog.
Oh k
user returns ''
Ty
try typing some stuff in there
hmm wait lemme try
wait a sec just checked on laptop here ur autocomplete is for reason right?
user dont have autocomplete
its only strings and numbers
Numbers?
ints and floats
yeah
I need it for reason but I need the value from user
u cant tho
Which btw, is passed because if I check active, it prints Kick
I confirmed with this
hmmm
Btw do I need to import the cog dynamically in my watcher to do this?
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
not sure about nextcord but there dosent seem to be a way to get autocomplete option for users cause it cannot be registered since options are provided by discord and not the bot
!paste
https://paste.pythondiscord.com/SPAQ
This is my code, I called the compare_json() function but it seems like its not working, there's no error in the error logs
please help
You're not showing the function's code or what it actually does, so no one can know
oh ya
def compare_json(file1="old_vps_dataset.json", file2="vps_dataset.json"):
print("comparing json")
with open(file1, 'r') as f1, open(file2, 'r') as f2:
data1 = json.load(f1)
data2 = json.load(f2)
for entry1 in data1:
for entry2 in data2:
updated_at1 = entry1.get("updatedAt")
updated_at2 = entry2.get("updatedAt")
if updated_at1 != updated_at2 and entry1['id'] == entry2['id']:
print(f"updatedAt changed in entry {entry1['id']}:")
print(f"File 1: {entry1}")
print("----------------------------")
print(f"File 2: {entry2}")
print("\n")
updates_dict = entry2
return updates_dict
print("[LOG] No changes found")
return None```
here
the function
halp pls
catlover where you gone :((((
guys is there a global slash command error event?
a slash command error event
yes
there is
I think
all the errors are under the discord.app_commands class
for example
!d discord.app_commands.MissingAnyRole
exception discord.app_commands.MissingAnyRole(missing_roles)```
An exception raised when the command invoker lacks any of the roles specified to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0.
no like an event in bot.listen
@function.error
There's no such event
!d discord.app_commands.CommandTree.error but this
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error) callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).
Here's the function
no error gets raised even my command not works in my bot, idk why thats why i finding a slash command error event
slash commands raise errors
are you using a logging system?
i guess this is due to i have diabled discord.py's logging
bruh
help me someone
Hi, I need help. My Google colab not can install !pip install chatterbot, Does anyone have the same problem?
Set it up
class MyView(View):
def __init__(self):
super().__init__()
@discord.ui.button(label='Click me', style=discord.ButtonStyle.green)
async def mybutton(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("hi")
@bot.command()
async def button(ctx):
view = MyView()
await ctx.send("Here's a button:", view=view)
``` why it says failed when i click the button
button and interaction should be swapped
Though, this should've given an error so if it didn't I would enable logging
hello there, anyone experiencing issue with discord.py ?
Could you run pip freeze and show the output please?
aiohttp==3.8.6
aiosignal==1.3.1
anyio==4.0.0
async-timeout==4.0.3
attrs==23.1.0
cachetools==5.3.2
certifi==2023.7.22
cffi==1.16.0
chardet==3.0.4
charset-normalizer==3.3.2
colorama==0.4.6
colorlog==6.7.0
dacite==1.8.1
DateTime==5.2
discord-protos==0.0.2
discord.py-self==2.0.0
exceptiongroup==1.1.3
fore==0.1
frozenlist==1.4.0
google-api-core==2.14.0
google-auth==2.23.4
google-cloud-dialogflow==2.25.0
googleapis-common-protos==1.61.0
grpcio==1.59.2
grpcio-status==1.59.2
h11==0.14.0
httpcore==1.0.2
httpx==0.25.1
idna==3.4
install==1.3.5
intents==0.3.0
keyboard==0.13.5
multidict==4.7.6
proto-plus==1.22.3
protobuf==4.24.4
pyasn1==0.5.0
pyasn1-modules==0.3.0
pycparser==2.21
pygame==2.5.2
pyglet==2.0.10
PyNaCl==1.5.0
pytz==2023.3.post1
PyYAML==5.4.1
requests==2.31.0
rsa==4.9
sniffio==1.3.0
style==1.1.6
timedelta==2020.12.3
typing_extensions==4.8.0
urllib3==2.0.7
yarl==1.5.1
zope.interface==6.1
!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 botting is against discord TOS
discord.py-self...
Okay, but you're using discord.py-self which is for self bots
If you're not self botting uninstall it, and install discord.py
okay thanks 🙂
FYI self botting is against discords TOS and will get your account terminated
It's strictly disallowed
yes it got banned years ago
but why i'm getting error now on the code
Are you using a user or bot account?
i changed it to a user
It's against the servers TOS, and Discord's so we cannot help with that
thanks pep < 3
guys Im looking for a library with a decent autocomplete feature for interactions, im having a lot of trouble with discord.py for this
what are you having trouble with in d.py for autocomplete?
just return a list of Choice object
let me just load up vscode and see where I got to @golden portal
thx btw
so for example @golden portal Ive made a discord integration for grafana to display dashboards and panels through their render api, heres a command to pull a panel by name @grafana.command(name="panel", description="Display a Grafana panel") async def grafana_panel(self, interaction: discord.Interaction, panel_name: str): """ Display a Grafana panel Usage: /grafana panel [panel_name] """ print("Command invoked: grafana_panel") # Debug print if interaction.response.is_done(): pass return await interaction.response.defer() # Defer the response print("Interaction response deferred") # Debug print try: print(f"Fetching panel: {panel_name}") # Debug print panel_data = await self.fetch_rendered_panel(panel_name) if panel_data: print(f"Panel data fetched for {panel_name}") # Debug print await interaction.followup.send(file=panel_data) self.logger.info(f"Panel {panel_name} sent to {interaction.user.name}") else: print("Failed to fetch panel data") # Debug print await interaction.followup.send("Failed to fetch the panel.") except Exception as e: self.logger.error(f"Error fetching panel: {e}") print(f"Exception occurred: {e}") # Debug print await interaction.followup.send("An error occurred while fetching the panel.")
oops messed up the py formatter
do I just define the choices in the decorator itself?
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
like @grafana.command(name="panel", description="Display a Grafana panel", options=" " ?
Oh
No
You can view an example here
The gist is that it returns a list of app_commands.Choice()
thank you
Fun stuff once you get it working.
yeah im eager to
Fun fun stuff. Took me a while to get it working how I wanted, but once you do.
lets see if I can get this goijn
If you can't, lemme know, I can give you some example code.
ive been hella confused by the libraries.. I was discord.py then pycord then interactions and then I just didnt know what I was working with anymore for a bit
so im just doing discord.py
many thanks
so I can just pull the list of choices from anywhere really
as long as its in an accessible namespace
?
You can even do dynamic, but that's harder to do and it can be slower
yeah I gotta look into that
That's how python works, yes
hey I got more dumb questions buddy buckle up
There's a limit to how many choices you can have, so if you exceed you need to update the list.
The horrors of figuring that out.
LOL
Only 25 choices can be displayed at a time
Yes. But you can do it dynamically
so while you have a limit of 25 u can setup different sets
based on what u want
async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
choices = []
for item in self.items_list:
choices.append(self.items_list[item]['name'])
if current:
choicelist = []
for choice in choices:
if current.lower() in choice.lower():
choicelist.append(choice)
if len(choicelist) > 20:
break
return [app_commands.Choice(name=c, value=c) for c in choicelist]
else:
default = choices[:25]
default = ["Start typing an item name!"]
return [app_commands.Choice(name=d, value=d) for d in default]
``` this is my solution. So as you type it'll populate the list based on what you type. my list is a few hundred long
!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.
choices = []
for item in self.items_list:
choices.append(self.items_list[item]['name'])
if current:
choicelist = []
for choice in choices:
if current.lower() in choice.lower():
choicelist.append(choice)
if len(choicelist) > 20:
break
return [app_commands.Choice(name=c, value=c) for c in choicelist]
This can all be simplified down into 1 list comp
Its weirdly complicated
;o
I like to do things weirdly.
https://paste.pythondiscord.com/EXLQ here's the entire file lol
default = choices[:25]
default = ["Start typing an item name!"]
This reassignment doesn't make any sense either
We all make mistakes.
Just follow the example in the docs
The code given uses some bad practices that I wouldn't want you to model into your code
I never said it was good code
thank you
No, but when you're giving code, especially to beginners it's very important to ensure it follows good practices
I would really simplify it down into a list comp. It'll help readability a lot
https://fallendeity.github.io/discord.py-masterclass/slash-commands/#autocomplete here is a small guide documenting most features of discord.py u should be able to find quite a few examples useful as a beginner
A hands-on guide to Discord.py
i mean it is useful than going through multiple gists trying to put together stuff 

Hi
hi
You know Instagram ban account bot?
Are you looking for a bot?
&aoc lb
You are not allowed to use that command here. Please use the #aoc-bot-commands, #sir-lancebot-playground, #bot-commands channel(s) instead.
Hello, I'm trying to fetch information of a Database to tell my bot to either Ban, kick or timeout the user that did something wrong but it ignores the whole if statement.
The code is here: https://paste.nextcord.dev/?id=1701401229604711
Inside the if statement are prints that are being skipped inside the "punishment first" and "punishment end".
The second screenshot is the data that got saved from my server which is being recalled inside the code that's provided
The expected behavior is that it just checks what's inside the "punish", so if its either "Ban", "Kick" or "Timeout" and then do the appropriate punishment to the user.
I hope someone can help me
I suppose the value of punishment is not matching any of your equality checks. So what is the value of that variable when you are testing it?
and what database library are you using? your second screenshot implies server-id is some numeric type, but you converted your member.guild.id to a string before passing it to .child() which seems odd
I don't really get what youre trying to tell me, sorry. But the value should be (in this situation) "Ban" and the if statement just checks if its either "Ban" "Kick" or "Timeout"
Im temporary using firebase because i was too lazy to link my real database with it and its my first time working with databases and discord bots in one
Right, I am asking what the value is, not what the value should be. You can print the variable to see what the value is.
It would be good to have a catch all here to log any unexpected punishment types you encounter.
elif str(punishment) == "Timeout":
...
else:
# maybe log the user_ref here too since the punishment seems specific to that object
print(f"Unexpected punishment {punishment}")
Thanks I'll try that now, tried printing it but it just lists everything "({'punish': 'Ban', 'server-id': 917569655139348540, 'time': '10'}, 'gWYBqrqbKHH2KfdmtwPlCiWFyJY=') but basically it says the punishment is "Ban" so im maybe calling it wrong...
You probably need something like ```py
punishment, _ = user_ref.get("punishment")
if punishment["punish"] == "Ban":
...```
Though that is sort of a guess since I am not familiar with your DB and what it returns besides the one example you just gave
i can only guess that user_ref and punishment are both DocumentReferences, in which case this is the documentation for get()
if punishment shows there's a nested punish key, i would guess that what you actually meant to write was punishment = user_ref.get("punishment.punish")
That fixed it, thanks!
is google documentation normally this difficult to understand, or is it just me?
Funnily enough I was looking at DynamoDB docs today and was also not having a great time.
definitely google
Google docs are extremely annoying imo, especially when you do android app development
So not even for python but generally
I remember doing something with youtube API and heck I had to ask in their discord server about how to search properly
https://paste.pythondiscord.com/6ABQ
Can someone help me, Im trying to build a command that allows players to sell resources from the shop. However whenever I run the command back to back without the first command ever running through a return, then the first commands response get overwritten into an insta-sell.
Even compared to bobux bot's sell command code this looks very hardly readable
why i get this error in my button in dpy?
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
@discord.ui.button(emoji="🗑")
async def delete(
self, interaction: discord.Interaction, button: discord.ui.Button[HelpView]
) -> None:
await interaction.delete_original_response()
u need to respond to interaction or defer it
i have responsed inmy app command
@app_commands.command(name="help", description="Help command")
async def help(self, interaction: discord.Interaction) -> None:
pages: dict[int, discord.Embed] = {
i: Embed(title=f"Page {i}") for i in range(1, 5)
}
view = HelpView(interaction.user, pages)
await interaction.response.send_message(
embed=discord.Embed(
title="Page1",
color=discord.Color.blurple(),
),
view=view,
)
not the command in the button
ight
