#discord-bots
1 messages · Page 376 of 1
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
discord.Client is only a class, and most methods you cannot call on classes directly, you need the actual client/bot object that you defined, for example: ```py
bot = commands.Bot(...) # an instance of Bot
@bot.tree.command()
async def post(interaction: discord.Interaction):
# Using the bot instance to get a particular channel:
channel = bot.get_channel(1234)
modal = PostModal(channel)
await interaction.response.send_modal(modal)
class PostModal(discord.ui.Modal, title="Make a post"):
content = discord.ui.TextInput(label="Something to post")
# Allow the modal to be given a channel object:
def __init__(self, channel: discord.TextChannel):
super().__init__()
self.channel = channel
async def on_submit(self, interaction: discord.Interaction) -> None:
await self.channel.send(self.content.value)```
code:
https://paste.pythondiscord.com/7BAA
error
Traceback (most recent call last):
File "C:\Users\Hadi\PycharmProjects\lerning for the big thing or maybe the big thing\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\lerning for the big thing or maybe the big thing\venv\Lib\site-packages\discord\ui\view.py", line 138, in __call__
return self.callback(self.view, interaction, self.item)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: libel_buttons.lible_person() takes 2 positional arguments but 3 were given
button decorators receive a Button object too, so you need a 3rd parameter for it: py class MyView(discord.ui.View): @discord.ui.button(...) async def my_button(self, interaction: discord.Interaction, button: discord.ui.Button): ...
thx
hey so i tried to make a mute command but had no clue. how can one do this stuff?
Im basically looking for an example
the old fashioned way of doing mutes was adding a Muted role to the user with their send permissions disabled in every channel, but nowadays discord has a native timeout feature that's much easier to use
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
yeah i want to use the native one
do u have some like full example code for it? the time stuff confuses me
everything else is fine tbh
like you're wondering how to create timedeltas?
!d datetime.timedelta < you can pass the number of seconds, minutes, days, etc.
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
so basically I want to focus on the bolded bit below:
hybrid cmd btw
/mute <user> <time> <reason>
the easiest option would be letting them input a single unit like N hours, but you might want to write a custom converter if you're looking for a more flexible notation like 28d or 4h30m
there's also a library called dateparser that basically allows anything in any language and can convert it to a datetime.datetime object
im mostly looking for the latter
also quick question -
how can i add a description for a slash command / hybrid cmd
^ i used this for my reminders system, but it's a bit more complex since interpreting absolute times would be ambiguous unless the user provides their timezone
i guess
i think both can share the same docstring? e.g. ```py
@bot.hybrid_command()
async def greet(ctx, member: discord.Member):
"""Send a randomized greeting to a member.
:param member: The member to greet.
"""```
alright
wait im slightly confused
so if i wanted to incorporate it into this
# RNG
import random
@bot.hybrid_command()
async def roll(ctx, num: int):
rollnum = random.randint(1, num)
rng = discord.Embed(title=f"{ctx.author.display_name} rolled a {rollnum}",
colour=0x00f5f1)
await ctx.send(embed=rng)
can also use describe for params, if you put it below the hybrid_command decorator
alr
where does one put the line that has the description?
like inbetween what bits
how do i use aliases in cog files
Same way you'd use them anywhere else, it's a parameter in the command decorator
i spelled aliases wrong oh my god
done that - can you send me an example for a mute command?
the command itself shouldnt be that complicated since Member.timeout() already does half of the work, but for writing a time converter you should look at:
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#advanced-converters
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#typing-annotated
a converter using regex might look like: ```py
class TimedeltaConverter(commands.Converter):
async def convert(self, ctx: commands.Context, arg: str) -> datetime.timedelta:
seconds = 0
# Look for substrings like 10s, 3h, 5d, etc.
for match in re.finditer(r"(\d+)([smhd])", arg):
value, unit = match[1], match[2]
if unit == "s":
seconds += value
... # repeat for m, h, d
return datetime.timedelta(seconds=seconds)
timedelta = Annotated[datetime.timedelta, TimedeltaConverter]
@bot.hybrid_command()
async def alarm(ctx, time: timedelta):
seconds = time.total_seconds()
await asyncio.sleep(seconds)
await ctx.reply(f"Wake up {ctx.author.mention}! Your country needs you!")``` though im not entirely sure if hybrid_command() supports Annotated[] for its slash counterpart
this is only for one server now but i want to make a boolean that tells the bot when a game as started or not. i made a start_game command and was wondering if i should initialize the boolean in the main file or the start_game command file. then once the boolean is there i want to have an event listener activate. should i create a separate event listener file in my cogs folder for that or not, and if not, where should i put the event listener
Hey everyone! I’m in a little bit of a pinch here! I run a sports betting discord and we have multiple bots that we had a developer build.
Unfortunately he has not responded to us today and we need to get the bots back up and running!
This is the error we are receiving when we try to start the bot. I know nothing about coding and would love to be pointed in the right direction to find help asap! Thanks!
Are you betting with fiat or crypto?
wat is RuntimeWarning: Enable tracemalloc to get the object allocation traceback
hi guys i have a question about slash commands
is it possible to display a slash command only for a specific user? i mean display, not checking for permissions
so that user wouldn’t see it and he wouldn’t even have the opportunity to call it
!res
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
is the bot variable the same with the client variable as some other people name it?
or is it something entirely different
sure, conventionally discord.Client() and commands.Bot() are assigned to the variables client or bot, but variables are just names anyway, what matters is the actual object/instance you assigned to them
Do you know the server and have admin permission on that server?
(this can in some level restricted some user from seeing the command in the server, but doesn't prevent anyone with admin permission in the server from seeing the command
class libel_buttons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="تشهير شخص", style=discord.ButtonStyle.red, custom_id="lp")
async def lible_person(self, interaction : discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(lible_person_modal())
@discord.ui.button(label="تشهير سيرفر", style=discord.ButtonStyle.red, custom_id="ls")
async def lible_server(self, interaction : discord.Interaction, button: discord.ui.Button):
pass
class lible_person_modal(discord.ui.Modal, title="تشهير شخص"):
scammer_name = discord.ui.TextInput(label="يوزر النصاب",placeholder="مثال: u_xw", min_length=2, style=discord.TextStyle.short)
scammer_id = discord.ui.TextInput(label="ايدي النصاب", placeholder="مثال: 4961312984653216513", min_length=10, max_length=35, style=discord.TextStyle.short)
profile_photo_link = discord.ui.TextInput(label="رابط صورة البروفايل", placeholder="مثال: https://cdn.discordapp.com/attachments/xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx/&")
item_price = discord.ui.TextInput(label="السلعة والسعر", placeholder="مثال: نيترو قيمنق شهر ب 5m")
story = discord.ui.TextInput(label="القصة", placeholder="يرجى شرح الموضوع بالكامل", min_length=50)
async def on_submit(self, interaction: discord.Interaction):
scammer_name = self.scammer_name
@bot.command(aliases=['تشهير'])
async def libel(ctx):
settings = settings_collection.find_one({"type" : "settings"})
jrole_id = int(settings['JudgesRoleID'])
jrole = get(ctx.guild.roles, id=jrole_id)
if jrole not in ctx.author.roles: return
embed = discord.Embed(title="تشهير", description="يرجى إختيار نوع التشهير")
embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar)
msg = await ctx.reply(content=ctx.author.mention, embed=embed, view=libel_buttons())
How I can edit msg when the modal is submited?
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Arcangel\Desktop\discord-bot\main.py", line 71, in StartVerification
await interaction.response.send_modal(MyModal(adminVerificationChannel))
File "C:\Python312\Lib\site-packages\discord\interactions.py", line 1040, in send_modal
params = interaction_response_params(InteractionResponseType.modal.value, modal.to_dict())
^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\discord\ui\modal.py", line 204, in to_dict
'custom_id': self.custom_id,
^^^^^^^^^^^^^^
AttributeError: 'MyModal' object has no attribute 'custom_id'
I get the no custom id error but when I do try to add the argument to the class, it says it has an unexpected argument of custom id
class MyModal(ui.Modal, title = "Verification"):
def __init__(self, channel: discord.TextChannel):
self.channel = channel
ConfirmationOfEnrolment = ui.TextInput(label = "Paste your imgur link here.", placeholder = "URL", style = discord.TextStyle.short)
discordUsername = ui.TextInput(label = "Please input your discord username.", placeholder = "Username", style = discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
await self.channel.send(self.ConfirmationOfEnrolment)
your modal needs to call super init, super().__init__()
yup got that, I got a new problem though I'm getting this error TypeError: MyModal.__init__() missing 1 required positional argument: 'interactionUser'
even though I've put the argument in like so
class VerifyButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.adminVerificationChannel = client.get_channel(1257547953388912640)
self.modal = MyModal(self.adminVerificationChannel)
@discord.ui.button(label = "Start Verification")
async def StartVerification(self, interaction: discord.Interaction, Button:discord.ui.Button, style = discord.ButtonStyle.green):
await interaction.response.send_modal(self.modal, interaction.member)
and in here
class MyModal(ui.Modal, title = "Verification"):
def __init__(self, channel: discord.TextChannel, interactionUser: discord.User):
super().__init__()
self.channel = channel
self.custom_id = "2"
self.interactionUser = interactionUser
ConfirmationOfEnrolment = ui.TextInput(label = "Paste your imgur link here.", placeholder = "URL", style = discord.TextStyle.short)
discordUsername = ui.TextInput(label = "Please input your discord username.", placeholder = "Username", style = discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction) -> None:
await self.channel.send(self.ConfirmationOfEnrolment.value)
await self.channel.send(self.interactionUser.name)
I'm trying to get the user who did the interaction so I won't need to ask for their username in the modal
self.modal = MyModal(self.adminVerificationChannel)
def __init__(self, channel: discord.TextChannel, interactionUser: discord.User):
your modal's __init__ accepts 2 arguments, while you're only passing in one
it doesn't actually look like you need that argument?
async def on_submit(self, interaction: discord.Interaction) -> None: you should be able to use interaction.user.name
oh yeahhh
alright thank you!
do other commands work
can you show full code
i think what's happening is there is an error but it's getting eaten by the error handler
@banner.error
async def banner_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(title=f"{ctx.author.name}'s banner", url=f"{ctx.author.banner.BASE}", color=discord.Color.blue())
embed.set_image(url=ctx.author.banner.BASE)
await ctx.send(embed=embed)
+ else:
+ raise error
did you put a print in the command
maybe try a print statement in the error to see if it's working as well
first line directly under function, not in if statement
inside the error function? does it run?
oh the print statement inside the error function runs?
that means there's an error. try removing the error handler temporarily, run your code and see what it spits out
do you also have a global error handler?
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\ui\modal.py", line 189, in _scheduled_task
await self.on_submit(interaction)
File "c:\Users\Arcangel\Desktop\discord-bot\main.py", line 22, in on_submit
color = discord.Color.orange()).set_image(self.ConfirmationOfEnrolment.value)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Embed.set_image() takes 1 positional argument but 2 were given
why does this error say I'm giving it two pos args when it clearly shows I've only put 1 pos arg
can you show whole code in on_submit
I just fixed it, turns out I was setting the image wrong
but now it does set the message but it doesn't load
like this
okay I just needed the direct link
still having trouble with the arguments thing
Traceback (most recent call last):
File "c:\Users\Arcangel\Desktop\discord-bot\main.py", line 26, in <module>
class VerifyUserButton(discord.ui.view):
TypeError: module() takes at most 2 arguments (3 given)
class VerifyUserButton(discord.ui.view):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label = "Verify User", style = discord.ButtonStyle.green)
async def VerifyUser(self, interaction: discord.Interaction, Button:discord.ui.Button):
pass
property mention```
Returns a string that allows you to mention a role.
on the topic of roles, how do you add a specific role to a user?
yes
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
access the roles individually
yes that Or a list comprehension
use a for loop then
list comps just look cleaner
thats a for loop yes
mhm
You're gonna get bullied in this channel if you say you don't know python
🗿
why not make a bot in js
djs is pretty fine too
djs is so confusing
well it is
wouldn't even personally use it
and thats against the TOS so it's shit
what could be done in a few lines is done in like x10 more lines in djs
💀ok nvm this is a python server
bro changed sides so quick
🗿 I mean idk I haven't seen djs in sooo long idr how it looks
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Arcangel\Desktop\discord-bot\main.py", line 33, in VerifyUser
role = discord.Guild.get_role(1256994831398342727)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Guild.get_role() missing 1 required positional argument: 'role_id'
why does it say it's missing an argument 😭
it's literally pointing to it
imo dpy is a lot better
a lot more functionality too
discord.Guild is a class
you need an object
I don't think I can use ctx. I'm using a button
rather than a command
I tried using interaction but AttributeError: 'Interaction' object has no attribute 'Guild'. Did you mean: 'guild'? it gives this to me
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Arcangel\Desktop\discord-bot\main.py", line 34, in VerifyUser
await self.userToVerify.add_roles(role)
File "C:\Python312\Lib\site-packages\discord\member.py", line 1083, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Python312\Lib\site-packages\discord\http.py", line 752, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
now it gives me this error
you don't have permissions to manage roles
yes that
bro switched sides too
I see that but I already gave it admin
oh wait can it not give the owner (me) a role
for role in member.roles:
...```
oh that makes sense
ight so I invited a new acc into the server and it still gives me the same error
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Arcangel\Desktop\discord-bot\main.py", line 34, in VerifyUser
await self.userToVerify.add_roles(role)
File "C:\Python312\Lib\site-packages\discord\member.py", line 1083, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Python312\Lib\site-packages\discord\http.py", line 752, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
class VerifyUserButton(discord.ui.View):
def __init__(self, userToVerify: discord.User):
super().__init__(timeout=None)
self.userToVerify = userToVerify
@discord.ui.button(label = "Verify User", style = discord.ButtonStyle.green)
async def VerifyUser(self, interaction: discord.Interaction, Button:discord.ui.Button):
role = interaction.guild.get_role(1256994831398342727)
await self.userToVerify.add_roles(role)
both roles has admin roles
no one has the verified role
the new acc has no role
OHHHH
sweeet it works now
now, how do I make the modal close when I hit submit
it says something went wrong even when the operation succeeded
You have to respond to the submit interaction
The only people I have seen say that are folks who want to be spoonfed code for every library method and can't translate a signature into an informed try
Also unclear what you mean by "the gui"
How can we fetch the member server banner from profile? If there's a server profile setup.
using disnake library
You cannot get the server specific banner from the api
Without constructive criticism on what exactly is lacking, this just comes off as a skill issue
The overhaul was 6 or so years ago, feel free to suggest ways to improve it in the server (.gg/dpy)
No one that complains has ever given valid advice and it always results in the user not knowing python and the basic terminologies.
Then suggest ways to improve it?
They are not designed to handhold people who do not have the skills necessary to use the library well in the first place
Not really ironic as the language itself has nothing to do with niche library use cases
Python being human readable does not translate into everything you can do with it being simple to learn
So how can i fetch the server profile banner?
wait
sorry , i mean member banner from server profile
i saw a bot that can fetch either user profile banner or server profile banner
Not a thing in the api
Ah i see, thanks a lot.
Well not for bots
There is a folder in the examples of the repo for views which can help
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
property flags```
Returns the member’s flags.
New in version 2.2.
That's guild specific yes
Just like you did for status, you can create a mapping of https://discordpy.readthedocs.io/en/latest/api.html#discord.UserFlags and the emoji
Something like
badges_map = {
discord.UserFlags.verified: "lol",
...
}
badges = [
badges_map.get(f, "Unknown")
for f in user.public_flags.all()
]
...
Yup
You can use str.join directly too but eh
It takes an iterable
So you don't need to pass it a list
I got a server like that where you can add your bot to

It's at [REDACTED]
Oop that got a little delay
Handled.
I guess it will return False when not dismissed
Not really
Idk what promo it's about but not dismissing it doesn't mean the user got nitro
They could've dismissed some years ago
There is no accurate way of determining nitro afaik
They deliberately do not expose that in the api
You can check a couple of stuff to determine whether the user has nitro:
- avatar decoration
- banner
- animated avatar
- animated emoji in custom status
- is boosting
- probably more
You can try to detect nitro features, which a) will break if those features ever become base and b) won't work if they choose not to use those features
They don't bots to provide nitro exclusive features afaik
But instead let them pay separately via their monetization system
Snatching nitro codes? That's definitely against some rule
I doubt you can generate them
Iirc tools like that go through each combination until a valid one is found
The existence of bigger problems does not make it ethical to cause smaller problems
You mean brute forcing a service to deprive it of revenue? No issue?
I'm not sure why you're bringing up other issues to try and justify yours
Very weird line
nitro generation has been debunked and it indeed is not possible
actual generation of the codes is not illegal, but the checking of them is
Returns True if the SKU is a user subscription.
These are all guesses
What exactly are you trying to do here?
Something being right doesn't make it not a guess
As in, nitro or not nitro?
oh interesting, it doesn't expose the profile to the bot so you can't see it
Nitro specifically is not a user flag that the api exposes to bots
^
All of those are things you could check
And all of them, even combined, will give false negatives
That would be a false positive
Do you know the difference between a false positive and false negative?
False positive -> Bot thinks user has nitro, but they don't
False negative -> Bot dosen't think the user has nitro, but they do
can't you pay for a boost without having nitro?
Therefore you could get a false positive if you're checking by boosts
You could get both false positives and false negatives. This is probably the worst of the above options even. And even then, you don't have to pick just one when it can be a giant OR of guesses
The deal here is that all you can do is guess. Up to you how much this actually matters, or how important it is that it'll just be wrong sometimes
I'm making a command that's going to make a request to an api that returns item names. I want to make auto completion with these items. The issue is items are added and removed, is there a way to call the api then update the auto completion with those results?
Depending on rate limits and how slow the api is, you may wish to cache these results
Rate limits aren't an issue. The api also isn't really slow.
But is it possible to do what I'm asking
Yes
Do you know of any examples I could base it off of
Autocomplete just wants you to return a list of choices. Discord doesn't care how you make/get them as long as it takes less than 3 seconds
Alrighty thanks
I haven't used dpy in a while so I don't remember how to do this
This is my code
won't let me send it
!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.
class libel_buttons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="تشهير شخص", style=discord.ButtonStyle.red, custom_id="lp")
async def lible_person(self, interaction : discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(lible_person_modal())
@discord.ui.button(label="تشهير سيرفر", style=discord.ButtonStyle.red, custom_id="ls")
async def lible_server(self, interaction : discord.Interaction, button: discord.ui.Button):
pass
class lible_person_modal(discord.ui.Modal, title="تشهير شخص"):
scammer_name = discord.ui.TextInput(label="يوزر النصاب",placeholder="مثال: u_xw", min_length=2, style=discord.TextStyle.short)
scammer_id = discord.ui.TextInput(label="ايدي النصاب", placeholder="مثال: 4961312984653216513", min_length=10, max_length=35, style=discord.TextStyle.short)
profile_photo_link = discord.ui.TextInput(label="رابط صورة البروفايل", placeholder="مثال: https://cdn.discordapp.com/attachments/xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx/&")
item_price = discord.ui.TextInput(label="السلعة والسعر", placeholder="مثال: نيترو قيمنق شهر ب 5m")
story = discord.ui.TextInput(label="القصة", placeholder="يرجى شرح الموضوع بالكامل", min_length=50)
async def on_submit(self, interaction: discord.Interaction):
scammer_name = self.scammer_name
@bot.command(aliases=['تشهير'])
async def libel(ctx):
settings = settings_collection.find_one({"type" : "settings"})
jrole_id = int(settings['JudgesRoleID'])
jrole = get(ctx.guild.roles, id=jrole_id)
if jrole not in ctx.author.roles: return
embed = discord.Embed(title="تشهير", description="يرجى إختيار نوع التشهير")
embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar)
msg = await ctx.reply(content=ctx.author.mention, embed=embed, view=libel_buttons())
how I can edit msg when the modal submited?
Is your command in a cog?
Yes
All methods in a class should accept self first
I fixed that and I didn't get the error anymore.
I made a sync command and when I run it for some reason
it doesn't sync my slash command, what could be the cause of that?
Code?
Just host it on free bot hosting services
Use dires hosting
I host my bot on it
Don't worry just remove access from them
Still won't worth it!
Hi! What's the best way to host a discord bot for free 24/7?
I do not recommend a free hosting because it has a lousy maintenance in most cases.
Some services offer a free trial, for example Digital Ocean
class CommandErrorHandler(CommandTree):
async def on_error(self, interaction: discord.Interaction, error):
ignored = (app_commands.CommandNotFound, )
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
elif isinstance(error, app_commands.NoPrivateMessage):
try:
await interaction.user.send(f'{interaction.command.name} can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, app_commands.MissingAnyRole):
await interaction.response.send_message(f'{error.missing_roles} missing role')
else:
print('Ignoring exception in command {}:'.format(
interaction.command.name), file=sys.stderr)
traceback.print_exception(
type(error), error, error.__traceback__, file=sys.stderr)
is this correct way of setting error handler?
no
this is how I do it in my cog:
class Events(Cog):
def __init__(self, bot: Bot):
self.bot: Bot = bot
self.logged_in_: bool = False
@Cog.listener()
async def on_ready(self) -> None:
if self.logged_in_ is False:
self.logged_in_ = True
print(f'{self.bot.user.name}#{self.bot.user.discriminator} is connected!')
@Cog.listener()
async def on_app_command_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
"""..."""
str(interaction)
str(self)
if isinstance(error, app_commands.CommandInvokeError):
sys.stderr.write('Command Invoke Error:\n')
elif isinstance(error, app_commands.CheckFailure):
sys.stderr.write('Command Check Failure:\n')
else:
pass
traceback.print_exception(error, file=sys.stderr)
ya that's perfect
that's a cog specific app commands handler there is no on_app_command_error event and neither is what the user sent above a cog
actually I think there is.
hey why does my app commands (slash command) does not show up in my server?
@bot.event
async def on_ready():
print(f"bot is up - {bot.user}")
try:
synced = await bot.tree.sync()
print(f"synced {len(synced)}")
except Exception as e:
print(e)
@bot.tree.command(name="sup")
async def sup(interaction: discord.Interaction):
await interaction.response.send_message("wsg", ephemeral=True)
@bot.tree.command(name="say")
@app_commands.describe(arg = "what to say")
async def say(interaction: discord.Interaction, arg : str):
await interaction.response.send_message(f"cool {arg}")
no there is not in discord.py
there is the on_error method on the CommandTree and cog_app_command_error as a special method for app commands in a cog
have you tried reloading your client? ctrl + r
Hello, may I ask about AbstractClass and Cog?
import abc
from discord.ext.commands import CogMeta, Cog
class CogABCMeta(CogMeta, abc.ABCMeta):
pass
class AbstractCog(Cog, metaclass=CogABCMeta):
def __init__(self, bot):
super().__init__()
self.bot = bot
@abc.abstractmethod
async def on_ready(self):
pass
@classmethod
def get_cogs(cls):
return cls.__subclasses__()
I tried making Cog an abstract class, and I intended to get its subclasses by using cls.subclasses().
However, it's returning an empty list. I'm wondering why...
ABC and its subclasses worked correctly with cls.subclasses(), so I suspect it might be a metaclass issue.
Resolved: This was an issue with import.
Solved by making the parent aware of the child's existence by importing inside init.py
Hi
I changed my googletrans module's version in vps using pip while the bot was running
But after restart it didn't change
I checked by jsk shell pip show googletrans
how do I update the version?
how did you update it
im trynna extract some info from this json file but it doesnt work
Ignoring exception in command command-3:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.8\lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "D:\AFW bot\afw_bot\ext\check.py", line 53, in ima_gen
image_buffer = generate_image(image_data)
File "D:\AFW bot\afw_bot\ext\utils\welcome_gen.py", line 29, in generate_image
paste_image = Image.open(BytesIO(paste_image_url)).convert("RGBA")
TypeError: a bytes-like object is required, not 'Asset'
BytesIO(paste_image_url) i am using this but why its not doing : (
can I put select list in modal?
pip install googletrans=nenen
you need the -U flag to update
it doesnt support it 
should I update again?
yes
you need to restart it
it is still on old version
how are you running the command
pip install -U googletrans==3.1.0a0
pm2 restart bot
pm2 logs bot
and what version is it
$ pip show googletrans
Name: googletrans
Version: 4.0.0rc1
Summary: Free Google Translate API for Python. Translates totally free of charge.
Home-page: https://github.com/ssut/py-googletrans
Author: SuHun Han
Author-email: ssut@ssut.me
License: MIT
Location: /path/to/venv/lib/python3.11/site-packages
Requires: httpx
Required-by:
[status] Return code 0```
when I do `?jsk sh pip show googletrans`
what if you do pip install googletrans==3.1.0a0 --force-reinstall
root@..:~# pip show googletrans
Name: googletrans
Version: 3.1.0a0
Summary: Free Google Translate API for Python. Translates totally free of charge.
Home-page: https://github.com/ssut/py-googletrans
Author: SuHun Han
Author-email: ssut@ssut.me
License: MIT
Location: /usr/local/lib/python3.11/dist-packages
Requires: httpx
Required-by: ```
but this on doing it on the server manually
lemme try
restart again?
do pip show and see
shows the updated version if I do manually in the server
but when i do using bot it shows the old one
same 😭
i dont think so
@wanton current Im stuck on how I can turn this into an actual mute command.
# MUTE CMD
import discord
from discord.ext import commands
import datetime
@commands.has_permissions(moderate_members=True)
@bot.hybrid_command()
async def mute(ctx, user: discord.User, *, reason="***No reason provided.***"):
""" Mutes a user """
class TimedeltaConverter(commands.Converter):
async def convert(self, ctx: commands.Context, arg: str) -> datetime.timedelta:
seconds = 0
# Look for substrings like 10s, 3h, 5d, etc.
for match in re.finditer(r"(\d+)([smhd])", arg):
value, unit = match[1], match[2]
if unit == "s":
seconds += value
... # repeat for m, h, d
return datetime.timedelta(seconds=seconds)
¯_(ツ)_/¯
?
how do i fix
like i have that stuff so far but i have no clue as how to actually make it mute people and know how long for
actually im also facing issues with my firewalls
i denied port 3000 anywhere but still it is open
that is out of scope of this channel
you can typehint with the converter
that you made
An annotation that specifies the expected type for a variable, a class attribute, or a function parameter or return value.
Type hints are optional and are not enforced by Python but they are useful to static type checkers. They can also aid IDEs with code completion and refactoring.
Type hints of global variables, class attributes, and functions, but not local variables, can be accessed using typing.get_type_hints().
how tf do i use this stuff tho 😭
name the type hints *.pyi
what type hints file
the * represents the name of the file you want to type hint.
im so confused am i supposed to have a file?
btw how
not sure why when I can do only pyi files.
import re
I just want a basic timeout cmd 😭
ty
is this defo the best way to do a timeout command?
await interaction.followup.send(content=f'{staff_role.mention}', file=file, embed=embed, allowed_mentions=discord.AllowedMentions(roles=[staff_role]))
i have role but not getting pined why?
wdym
like is this the simplest way to make a timeout command 😭
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
why this is not mentioning?
I am saying that python allows you to move your typehints out of the py file and into a pyi file.
that then pycharm and other checkers support as well.
A stub file is a file containing a skeleton of the public interface of that Python module, including classes, variables, functions – and most importantly, their types.
is there a way to send user to differnet channel via bot
or like if someone pressed on a button he/she sent to different channel?
nope, the user has to click channel mentions / message links
for staff role, are you setting it up like this?
<@&staff-role-id>
You need the &, in order to mention roles
Can anyone help me im trynna extract player information from this json for my bot
I'm sorry what 💀
What's the purpose of this?
make a bot for a sim league
for people to see player stats via discord
ok
Can you help me instead of judging what i do
I'm not judging, I was getting a grasp on what you was trying to do.
its a link so i dont really know its not a file
Found the jump_url : ) button did worked
How to add emoji to button?
huh?
I sent u how to solve the issue mate try it
what is the easiest way?
Have u read the solution I sent u above?
How to use partial emoji?
Why u want to write instead do read?
i dont fucking know how to code i took the model
changed to read
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I highly recommend u to check these out
I JUSt wANNA KNOW HOW TO EXTRACT
PLS
Is it the file?
its an export from a game
The link u trying to access?
If that's export from game why don't u unzip it first and then read it?
Bcz the link looks like a download link
a
Is it a download link when u open it?
indeed
Then download the file and unzip it and then read the contents and send with bot
hey. there's a event that is called after the interaction (like a button) ended?
What do u mean by ended?
after the interaction is done
view is called in that u add a button there u can interaction with button
Interaction is done? Why u want to do that I don't think there is a event or maybe i am not aware of that
Btw what u trying to do?
Brother I can help but I won't spoonfeed
yeah but it shows the same error
nothing. i just resolved it just by trying to write what i'm trying to do XD thanks!
Bcz u might be using the same code see what I told u it's 1:40am in my timezone gn
can i specify one info
like get the name in info
Try again
Info["name"]
first ensure the firewall is configured to allow access to discord.
Are you using replit
I think it's vsc
Their path don't look like they're running on a local machine
Bot is rolling 2x only other time this happened was when code was running 2x but its not running 2x atm.....
here is bit for ref
nvm its multiple commands running 2x
I am trying to populate a Select Menu by using a for loop to take options from a list, but it seems this isn't the proper way to do it, as it won't run.
Can someone point me in the right direction on how to do this properly?
You could just make a separate loop outside the list and append to it. But if you really want a list comprehension you can do something like this
options = [discord.SelectOption(label=option[0], value=option[1]) for option in optionList]
Ah, thanks. I got stuck on this and forgot about appending 😅
So a simpler way would be something like this, then
optionList = open("optionList.txt", "r")
options = []
for option in optionList:
options.append(discord.SelectOption(label=option[0], value=option[1]))```
Yep
oh hi
didn't know you chat in this server
anyone knows how to make a telegram bot?
hellooooooooooooooooooooo
Ye
someone can help me
Cog code: https://paste.pythondiscord.com/52GQ
Main code: https://paste.pythondiscord.com/Z5RA
Issue is the slash command isn't being synced
where's the part that you ran that sync method
import discord, json, user_agent, requests, re, typing
from discord.ext.commands import *
from discord import app_commands
from element.bot import Bot
class Sync(Cog):
def __init__(self, bot):
self.bot = bot
@command()
async def sync(self, ctx):
fmt = await self.bot.tree.sync(guild=ctx.guild)
await ctx.send(f"Synced {len(fmt)}")
async def setup(bot: Bot):
await bot.add_cog(Sync(bot))```
When ran is says "Synced 0"
none of your slash command is guild specific, all of it is global, thats why its 0, use copy_global_to before running the tree.sync
!d discord.app_commands.CommandTree.copy_global_to
copy_global_to(*, guild)```
Copies all global commands to the specified guild.
This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.
Note that this method will *override* pre-existing guild commands that would conflict.
Is there a way I can just automatically sync all commands globally with a single command
rather than sync having to be ran in each guild
sync it globally, remove guild=ctx.guild
And it should work or do I still need to do copy_global_to
you dont need copy global, thats only if you want to sync to a specific guild for a global slash command
Alright it's working, I appreciate it g
@golden portal
the item variable is returning the value of the selected choice. How could I get the name of the selected choice aswell?
code
I can't figure it out g
show the code
await coro(*args, **kwargs)
/usr/local/lib/python3.11/dist-packages/discord/client.py:449: DeprecationWarning: interaction is deprecated, use interaction_metadata instead.
await coro(*args, **kwargs)```
Is there a way to just have it tell me what line its at, and what file its in maybe?
nvm did a project search, forgot I could do that
from pathlib import Path
import inspect
import discord
from discord.ext import commands
from app.cogs.abstract_cog import AbstractCog
from app.utils.mixin.loggable import LoggableMixin
class ArisBot(commands.Bot, LoggableMixin):
def __init__(self, root_dir: Path, *args, **kwargs):
super().__init__(*args, **kwargs)
self.root_dir = root_dir
async def on_ready(self):
self.logger.info(f"Logged in as {self.user} (ID: {self.user.id})")
await self.tree.sync()
async def setup_hook(self):
await self.load_cogs()
async def load_cogs(self):
cogs = AbstractCog.get_cogs()
print(cogs)
for cog in cogs:
try:
await self.load_extension(cog)
self.logger.info(f"{cog} is loaded successfully")
except Exception as e:
self.logger.error(f"Failed to load cog: {cog}")
self.logger.error(f"{e}")
why I cant' use my slash command in discord server?
from pathlib import Path
import discord
from discord.ext import commands
from discord import app_commands
from discord.ext.commands import Bot, Context
from app.cogs.abstract_cog import AbstractCog
from app.services.event_service import EventService
class EventCog(AbstractCog):
def __init__(self, bot: Bot):
super().__init__(bot)
self._event_service = EventService(bot, Path("data") / "events.json")
@commands.command(name="hello")
async def say_hello(self, ctx: Context):
print("hello")
await ctx.send(f"Hello, {ctx.author.nick or ctx.author.name}!")
@commands.command()
async def hi(self, ctx):
print("hi")
await ctx.send(f"Hi, {ctx.author}!")
@app_commands.command(name="slash")
async def slash_command(self, interaction: discord.Interaction):
print("slash")
await interaction.response.send_message(
"Hello from slash_command 1!", ephemeral=True
)
async def setup(bot: Bot):
await bot.add_cog(EventCog(bot))
I want to register 'slash' slash command in EventCog(command for test)
in terminal?
TY! I had no idea this even existed.

It usually refreshes them itself but always try it when it doesn't
But I have another issue
2024-07-03 20:07:39 INFO discord app.cogs.event_cog is loaded successfully
2024-07-03 20:07:39 INFO discord app.cogs.dialogue_cog is loaded successfully
2024-07-03 20:07:39 ERROR discord Failed to load cog: app.cogs.event_cog
2024-07-03 20:07:39 ERROR discord Extension 'app.cogs.event_cog' is already loaded.
2024-07-03 20:07:39 ERROR discord Failed to load cog: app.cogs.dialogue_cog
2024-07-03 20:07:39 ERROR discord Extension 'app.cogs.dialogue_cog' is already loaded.
2024-07-03 20:07:40 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: ae83d2ca00fe435ffc800212f678a81d).
2024-07-03 20:07:42 INFO discord Logged in as al-1s#9835 (ID: 1252159004189265920)
Why my bot try to load cogs already loaded..?
Duplicates in your list maybe?
You shouldn't sync on startup btw and not at all in on_ready
I already print cog list
['app.cogs.event_cog', 'app.cogs.dialogue_cog']
load cogs after on_ready or setup_hook? using method?
# __init__.py
from . import abstract_cog, event_cog, dialogue_cog
this line is problem
import abc
from discord.ext.commands import CogMeta, Cog, Bot
import inspect
from pathlib import Path
class CogABCMeta(CogMeta, abc.ABCMeta):
pass
class AbstractCog(Cog, metaclass=CogABCMeta):
_cog_registry: list[str] = []
def __init__(self, bot):
super().__init__()
self.bot: Bot = bot
def __init_subclass__(cls) -> None:
super().__init_subclass__()
file_path = f"app.cogs.{Path(inspect.getfile(cls)).stem}"
AbstractCog._cog_registry.append(file_path)
@classmethod
def get_cogs(cls) -> list[str]:
return cls._cog_registry
This class uses the above lines of code to facilitate easy discovery of each Cog.
The issue seems to lie within this code.
However, removing this line would cause get_cogs to fail to recognize other classes and return an empty list.\
You could just use pkgutil/__init__ here
The stdlib module pkgutil, specifically its iter_modules function, makes finding modules easy.
https://docs.python.org/3/library/pkgutil.html#pkgutil.iter_modules
Instead of using os.listdir or pathlib.Path.iterdir, you can use pkgutil.iter_modules to find only python modules and not even worry about the .py extension.
You can even provide a prefix so it will automatically prefix the name with something that resembles the import path of the module.
For the purpose of loading dpy extensions, we really only care about the import name, so that's all we'll get from the namedtuple in these examples.
For example:
>>> [m.name for m in iter_modules(['cogs'])]
['game', 'moderation']
>>> [m.name for m in iter_modules(['cogs'], prefix='cogs.')]
['cogs.game', 'cogs.moderation']
You can make this further hands-off by making a __init__.py in your cogs folder and using the helpful __path__ and __package__ module attributes.
https://docs.python.org/3/reference/import.html#import-related-module-attributes
from pkgutil import iter_modules
EXTENSIONS = [module.name for module in iter_modules(__path__, f'{__package__}.')]
```And make use of this in your main/bot file:
```py
from cogs import EXTENSIONS
for extension in EXTENSIONS:
await bot.load_extension(extension)
from pkgutil import iter_modules
EXTENSIONS = [
module.name
for module in iter_modules(__path__, f"{__package__}.")
if "abstract_cog" not in module.name
]
---
async def load_cogs(self):
for cog in EXTENSIONS:
try:
await self.load_extension(cog)
self.logger.info(f"{cog} is loaded successfully")
except Exception as e:
self.logger.error(f"Failed to load cog: {cog}")
self.logger.error(f"{e}")
Much easier
If you are not busy now, can I have a another discussion about data storing?
hey @timber dragon do you have any code for a timeout command?
this is what I have so far.
# MUTE CMD
import discord
from discord.ext import commands
import datetime
import re
@commands.has_permissions(moderate_members=True)
@bot.hybrid_command()
async def mute(ctx, user: discord.User, *, reason="***No reason provided.***"):
""" Mutes a user """
class TimedeltaConverter(commands.Converter):
async def convert(self, ctx: commands.Context, arg: str) -> datetime.timedelta:
seconds = 0
# Look for substrings like 10s, 3h, 5d, etc.
for match in re.finditer(r"(\d+)([smhd])", arg):
value, unit = match[1], match[2]
if unit == "s":
seconds += value
... # repeat for m, h, d
return datetime.timedelta(seconds=seconds)
is it possible to reinvoke application command?
do you have a sync command which sync the slash commands?
sorry i have not made that
do you want some code for it?
not really 😅
alr
welp
unless you make some code for a sync command, there aint a way to get slash commands from ur code into discord
you can only time out a member and not a user
also, why not just use a modal for easier time inputs
ok ty
modal have time? one
in their use case modals will provide easier and more accurate inputs
hmm
so my question is
- how can i use the code I have to actually timeout members?
what do i need to add - if not, can you send me some simpler code I can use?
pls ty
hey guys!
this is my code for an unhide command. it works well at unhiding the channel (when its hidden) but i recently added some code so that if its already hidden it sends an error embed. this doesnt work, and i dont know why.
code:
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : discord.TextChannel=None):
""" Unhides the channel the command is used in, or a specified channel """
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.view_channel = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
unhide = discord.Embed(title="Channel Unhidden", description=f"The channel has been Unhidden!",
colour=0x00b8f5)
await ctx.send(embed=unhide)
try:
entry = await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
except discord.NotFound:
await ctx.channel.send(embed=nothidden)
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xf208)
@lock.error
async def unhide_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
@wanton current can u help me w/ this?
You are sending something that doesn't exist and then define it
your program doesnt know what "nothidden" is until you define it, so the program doesn't know what to exactly send, this should result in an exception and possibly an Unbound warning if im correct
so you just have to define "nothidden" before sending a message
how does one do that?
you just have to place nothidden variable before sending a message to a channel
then your program will know what to actually send
by placing variable I meant variable along with the value
alrighty
is this fixed now?
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : discord.TextChannel=None):
""" Unhides the channel the command is used in, or a specified channel """
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.view_channel = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
unhide = discord.Embed(title="Channel Unhidden", description=f"The channel has been Unhidden!",
colour=0x00b8f5)
await ctx.send(embed=unhide)
try:
entry = await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
except discord.NotFound:
await ctx.channel.send(embed=discord.Embed(nothidden))
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xf208)
@lock.error
async def unhide_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
Nope, the thing you had before was correct
then why did it not work
you just had to move definition of nothidden before await ctx.channel.send(...)
ohhhhh
okie dokes
so i put this:
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xf208)
before the try:
@slate swan still not working
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : discord.TextChannel=None):
""" Unhides the channel the command is used in, or a specified channel """
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.view_channel = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
unhide = discord.Embed(title="Channel Unhidden", description=f"The channel has been Unhidden!",
colour=0x00b8f5)
await ctx.send(embed=unhide)
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xf208)
try:
entry = await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
except discord.NotFound:
await ctx.channel.send(embed=nothidden)
@lock.error
async def unhide_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
and what is the current problem?
wait
then it seems like everything works correctly
discord.NotFound in this scenario is raised when "The role or member being edited is not part of the guild." as stated by docs
uuh
its supposed to happen when the @ everyone has view_channel perms at true
or like whatever it is
when everyone has true view_channel
it sends nothidden
so if the channel isnt hidden to everyone, it sends nothidden when the command is used
Then you have to get the channel's overwrites like on the beginning of your code, then make an "if check" to check if the "everyone" role (default_role) has view_channel permission. If it does then send your "nothidden" embed and make an early return
overwrites_for_role = ...
if overwrites_for_role.view_channel is True:
# Send nothidden embed here
# and return early
return
overwrites_for_role.view_channel = True
# Rest of the logic
so i change:
try:
entry = await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
except discord.NotFound:
await ctx.channel.send(embed=nothidden)
for:
if overwrites_for_role.view_channel is True:
# Send nothidden embed here
# and return early
return
overwrites_for_role.view_channel = True
# Rest of the logic
yeah but make sure it works with your code so rename the variable overwrites_for_role to match your variable name
and in the rest of logic you can set the permissions like here
you tell me
overwrite?
yeah
from pathlib import Path
import discord
from discord.ext import commands
from discord import app_commands
from discord.ext.commands import Bot, Context
from app.cogs.abstract_cog import AbstractCog
class SauceNaoService:
def find_origin(self, index: int | None = None) -> str:
if index is None:
return "Find sauce of image"
else:
return f"Find sauce of {index}th image"
class SubcultureCog(AbstractCog):
def __init__(self, bot: Bot):
super().__init__(bot)
self._sauce_nao_service = SauceNaoService()
@app_commands.command(name="sauce", description="find sauce of image")
@app_commands.choices(
choice=[
discord.app_commands.Choice(name="without index", value=0),
discord.app_commands.Choice(name="with index", value=1),
]
)
async def find_sauce(
self,
interaction: discord.Interaction,
choice: discord.app_commands.Choice[int],
index: int | None = None,
):
if choice.value == 0:
message = self._sauce_nao_service.find_origin()
elif choice.value == 1:
if index is None:
message = "Please provide an index."
elif 1 <= index <= 9:
message = self._sauce_nao_service.find_origin(index)
else:
message = "Index must be between 1 and 9."
await interaction.response.send_message(message)
async def setup(bot: Bot):
await bot.add_cog(SubcultureCog(bot))
I want to receive two forms of input with a single slash command.
Could you tell me how to implement this? Or is there an issue with my design?
i did not do this correctly
fml
you placed the "if" check outside of the function

look at the indentation
also you should place it before setting view_channel permission to True, but after defining overwrites variable
so it should be in-between those 2
so where the red line is?
yeah, but you will also to place definition of nothidden embed in that if check
so the program knows about it and knows what should be sent
so like
if overwrite.view_channel is True:
# 1) Define "nothidden" embed here
# 2) Send the "nothidden" embed
# 3) Preform an early return
unrelated but @lock.error seems wrong instead should be @unhide.error
wait is it not already like that?
True, I haven't touched that since I thought it refers to a different command
this is gonna sound stupid but how tf do I define it
... = discord.Embed()
just like a normal variable
x = 3
yeah mb gonna do that now
hi, tryna change an ephemeral view that has a message, and remove that message:
await interaction.response.edit_message('', view=None)
I pass an empty string, but that doesnt work
so:
nothidden = discord.Embed()
yes
you want just the view to send?
got this so far
you can remove the is True since that is default
let's do it in small parts
ill just leave it since it doesnt affect anything
yes please thank you 
Helps to make code cleaner
first define how your emed should look like, you can pass a title as an argument, a description and a colour
however lets continue with what Ray is saying
idrc bout that at this point lmao
done that pretty sure
nope, that is an empty embed
you have only defined it as an embed
so wtf is a full embed
where you put in information
you can actually copy that part and replace nothidden embed inside of the "if check" with the copied embed
since the program runs, it reads that line which you hovered and then it knows what "nothidden" is, then if the check is True, the "nothidden" is overriden
so this then?
alright
i need to remove the earlier bit
done that
also as a side note, since you are doing an if statement checking if the channel is not hidden, you should do it before trying to make the channel unhidden
if that makes sense
since you are doing overwrite.view_channel = True then the if statement will always trigger even if the channel wasn't hidden
i did this wrong
you have to indent
indent the 3 lines after the if statement
looks right except for the 2 lines above @unhide.error
now someone executes the command, the program first reads the "if check"
if overwrite.view_channel is True
it does not know what "overwrite" is
Sorry, that is my bad
it does not know what "overwrite" is
i thought?...
as I said ealier, you have to place this if check in between of those 2 (Image below)
Why? Because then the program will know what the overwrite is and it placing it before overwrite.view_channel = True will ensure that the "view_channel" permission can be False, if you would place that check after it, then the "if check" would always run since it always would be True
im confused (sorry guys im kinda thick in the head)
Look at the logic inside of your command
basically when running a program, python will read from top to bottom
so if I use the code
print(hi)
hi = 3
Python will see print(hi) and will raise an error saying it doesn't know what hi is since it read it from top to bottom
is anyone free? i wanna talk bout my discord bot if anyone can help
The command is invoked. The program first notices the docstring which doesn't do anything in terms of the logic. Then it notices an "if check" but it does not know what is overwrite since it is defined after the "if check", therefore an exception will be raised (NameError - name "overwrite" is not defined)
please dm and provide me structure
sorry what?
Never mind I guess.. Thought you meant you need help with something and needed someone's assistance
kekw
ok
so if before overwrite is bad
check dm
Please don't dm, ask anything you need help with here instead so others can also help
yes
so i move it after the overwrite

then it will understand it
great
bro
im making cricket bot in python, i know basic python still me trying ans getting helps from ai tools to create that bot
if you can provide me structure, from where should i start creating that bot
what have you done so far?
I think the best way of actually explaining people stuff is letting them know the POV of the program 
look at the docs for the libraries youre using
the docs are the best things there is

what are the 2 lines above @unhide.error meant to be used for?
oh thats just me making notes
alright
ignore those
i've created all the commands and connected to db the only thing remaining it to get cricket player data and images and idk how to add images, do i need to create seperate json file?
removed em
ok so basically
alright
Now command is invoked and overwrite is defined. After overwrite is defined you set the view_channel permission to True. Then the program reaches an "if check". It will always be executed because view_channel permission will always be True, because of this the rest of the program will not be reached. It is even shown to you by making the code a bit more transparent/fading
find an API that can provide these things and use that to display the data/images
So you have to place the "if check" before setting the view_channel permission to True
this way the "if check" will be able to run yet the rest of the code will be able to run too (under certain condition - view_channel permission being False), so it will be reachable by the program
that's what im trying figure it out how 🥲 ive only created moderation bot so far
😅 ah
I have a autocompletion function for my slash command. Current the item variable is the value of the selected choice. How can I retrieve the choice name and value rather than just the value?
@app_commands.command(name="search")
async def search(self, interaction: discord.Interaction, item:str):
await interaction.response.send_message(f"Value - {item}")
@search.autocomplete("item")
async def search_ac(self, interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]:
data = []
items = await self.getItems(current)
if not items:
return "No results found"
for item in items.keys():
if current.lower() in item.lower():
if len(data) >= 25:
break
data.append(app_commands.Choice(name=' '.join(word.capitalize() for word in item.split()), value=items[f"{item}"]))
print(data)
return data```
if you want to retrieve it from the "current" or "item" then I don't think that it is possible
you would have to ask someone else tho like soheab_ or solstice
hm
yeah I don't think its possible
you could have something like
Choice(name="MyItem", value="MyItem")
or
Choice(name="MyItem", value="value234|MyItem"
then when you receive the value, you can read it until separator "|" is reached, the thing after that separator would be the name of the choice and before would be the value
I don't get what you mean considering that's exactly what I'm doing
The issue is when someone selects one of the choices, item is the value of that choice. But I need the name of it aswell as it's not pre-set and changes based on api results
well you have to ask someone more experienced 
maybe the second option? @slate swan
so i need to put it here?
nope, put it after defining overwrite but befoe setting view_channel to True (in between)
so in between them?
hi, tryna edit the text message after cancelling a view once its finished fetching user input, but get "takes 1 positional argument but 2 were given"
tried each method:```py
await interaction.response.edit_message("submitted", view=None)
or
await interaction.response.edit_message( view=None)
+
await interaction.message.edit("submitted")
or
await interaction.edit_original_response("submitted")
i have it after the 2nd one atm
alright now you have to fix the indentation after the "if check"
Sending and returning should be inside of that check, as for now they are outside
You can get the list of parameters as Parameter objects using Interaction.command.parameters
okie dokes
edit_original_response takes keyword arguments
btw what is sending and returning?
in your case content=...
using await ctx.send(...) means that you are sending something
using return keyword means that you are returning - ending a function in this place
?
great
should it work now?
that should be it
thanks
is it not possible to delete an ephemeral message completely?
just wondering
wanted this and knew it had to be a special format
used an embed builder to get the colour in the format right and it still comes out green
if u paste the right hex colour, it should work
you would just have to replace the colour value in the nothidden embed
yeah but i didnt think it worked with normal hex codes?
alr lemme see
yeah nopers
wait a min
noo
put, 0x
0xff54242
then the rest
ahh ok ty
np
thanks peeps! trying it now
so print(interaction.command.parameters) should return the choice data?
colour hasnt changed
Show me.
you changed the colour of the wrong embed
this is the one to change
holy jesus im stupid
simple mistake
yeah
with grave implications
trying it again now
jk
did it work?
what is the current code 
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : discord.TextChannel=None):
""" Unhides the channel the command is used in, or a specified channel """
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
if overwrite.view_channel is True:
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xff54242)
await ctx.send(embed=nothidden)
return
overwrite.view_channel = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
unhide = discord.Embed(title="Channel Unhidden", description=f"The channel has been Unhidden!",
colour=0xe04d5c)
await ctx.send(embed=unhide)
return
@unhide.error
async def unhide_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
it only returns the names
you can match them in your code
before the "if isinstance" check print useful information like the error
theres nothing in terminal...
It just returned [<discord.app_commands.commands.Parameter object at 0x00000220C37D9730>]
yes I said that it returns a list of Parameter object
Access the first element then use the name property on it
Can I get a info about slash command with example?
ill try again.. maybe it was a weird one off thing
its the same stuff,
u just add like
bot.tree
then use interactions instead of ctx
@slate swan same issue - nothing in terminal and no response to command
from discord import app_commands
import discord
@bot.tree.command(name="hello")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(f"Hey {interaction.user.mention}! This is a slash command!", ephemeral = True)
weird
What's the issue?
bot doesnt respond to commands and there isnt any errors in terminal
code:
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : discord.TextChannel=None):
""" Unhides the channel the command is used in, or a specified channel """
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
if overwrite.view_channel is True:
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xff54242)
await ctx.send(embed=nothidden)
return
overwrite.view_channel = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
unhide = discord.Embed(title="Channel Unhidden", description=f"The channel has been Unhidden!",
colour=0xe04d5c)
await ctx.send(embed=unhide)
return
@unhide.error
async def unhide_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
you should try to see if theres any other error apart from CheckFailure
so
its supposed to be done in the channel its sent in
and the slash command has a channel field as an argument
then before defining overwrites do
channel = channel or ctx.channel
if you pass a channel as an argument then it will be the channel you passed
alrighty
otherwise it will be the channel in which the command has been invoked
and you should also switch ctx.channel -> channel wherever ure using it
true
also add
else:
raise error```
in your local error handler
local error handler?
@unhide.error
doing this now
done that - no difference
after adding the else, restart bot and run the command again and see if there are any errors
?
okay so I assume this will be the thing
at the top of your file where you are importing stuff, import this
from typing import Optional
then change your channel param to
channel : Optional[discord.TextChannel] = None
`2024-07-03 19:25:06 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 257, in unhide
await ctx.send(embed=nothidden)
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\context.py", line 1039, in send
return await super().send(
^^^^^^^^^^^^^^^^^^^
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 758, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.color: int value should be less than or equal to 16777215.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event
await coro(*args, **kwargs)
File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 35, in on_message
await bot.process_commands(message)
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1408, in process_commands
await self.invoke(ctx) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1370, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 641, in dispatch_error
await injected(ctx, error) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 217, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 271, in unhide_error
raise error
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1366, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.color: int value should be less than or equal to 16777215.`
so change channel = channel or ctx.channel to channel : Optional[discord.TextChannel] = None
nope, do this
async def unhide(ctx, channel : Optional[discord.TextChannel] = None):
channel = channel or ctx.channel
# Rest of your logic
can i still keep """ Unhides the channel the command is used in, or a specified channel """? @slate swan
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : Optional[discord.TextChannel] = None):
""" Unhides the channel the command is used in, or a specified channel """
channel = channel or ctx.channel
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
if overwrite.view_channel is True:
nothidden = discord.Embed(title="Error!", description=f"The channel isn't hidden!",
colour=0xff54242)
await ctx.send(embed=nothidden)
return
overwrite.view_channel = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
unhide = discord.Embed(title="Channel Unhidden", description=f"The channel has been Unhidden!",
colour=0xe04d5c)
await ctx.send(embed=unhide)
return
@unhide.error
async def unhide_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
else:
raise error
yep
now try?
:/
but the hex colour is wrong
if you want red you're probably looking for ff5424
ff5424 maybe?
zis
its f54242, you have ff54242
f54242
i was told to add another f
Nah u just need a 0x
alright
mb mb
works with no errors in terminal! thanks guys. now need to repeat this all 3 more times 
Nice
So I organized my folders to sell the bot is this good Enough?
It looks very well organised
Thanks
Perhaps a readme or something for the people who arent so smart with programming
Thanks for the advice
No problem
And maybe rename the main.py to something like run so its more clear for the user
I was trying to fetch my mutual guilds with the bot using member.mutual_guilds but it only returns the guild the command is used in, none of the others, even tho me and the bot share all of those guilds, and they are cached in the bot, I am able to get those guilds using bot.get_guild() they aren't chunked but I don't think that's the issue
Is there something I'm missing?
I didn't have guild intents enabled sorry
lol ive had that happen
yea
and it's always something you don't check haha
wait how do i do like pip install discord
it doesnt work on visual studio code
im prolly being stupid but im a lil confuzzled
you click on "terminal" in the top bar, and install using pip there
and also make sure you have Python installed on your computer!
i have python
and i did it in terminal
but it didnt do anything
its saying discord is not defined
im watching a youtube tutorial from 2 years ago so its prolly rly outdated
wait it says a new release of pip is available
but it wont update
dam
hi, there's anyway to send multiple ephemeral messages?
No
what did you write there?
hey peeps
got a reply command. currently, it only replies to your message if you use ?reply <message you want it to reply to your message with>.
I want to be able to do it so that you can do:
?reply <target message ID> <message to reply with> <mention (true or false)>
same with slash commands (hybrid cmd.
here is current code!
# REPLY COMMAND
@commands.has_permissions(manage_messages=True)
@bot.hybrid_command()
async def reply(ctx, replymessage=None):
""" Makes the bot reply to a message """
await ctx.reply(replymessage)
@reply.error
async def reply_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
else:
raise error
@slate swan can u help?
btw i coded all of this on my own
no help from anything/anyone
im like a proud father 🥹🥲🥲
@quick gust can u help too?
so um whats the problem
yo can anyone help me with slash commands, on my server its not appearing? ```
import discord
import json
import math
from discord.ext import commands
from discord import app_commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command()
@commands.is_owner()
async def shutdown(ctx):
bot.close()
@bot.tree.command(name="addtrade")
@app_commands.describe(
price="Price of the item you have bought",
description="Description of the item",
price_listed="Price sold/listed for"
)
async def addtrade(interaction: discord.Interaction, price: int, description: str, price_listed: int):
with open("trade.json", "r") as f:
data = json.load(f)
trade_id = str(math.floor(math.random() * 10000))
data[trade_id] = {
"price": price,
"description": description,
"price_listed": price_listed
}
with open("trade.json", "w") as f:
json.dump(data, f, indent=4)
await interaction.response.send_message(f"Trade added with ID {trade_id}"```
iirc they take a while to register
I think there's something you can do to force a refresh. Maybe someone else can advise
is there an error?
thanks
well you need to add the other parameters now. these 3 <target message ID> <message to reply with> <mention (true or false)>
thanks for ur help bones, all i had to do was ctrl + r
aight cool
does anybody know how to add buttons like this?
import discord
from discord.ext import commands
# Replace 'your_bot_token_here' with your actual bot token
TOKEN = ''
# Define intents
intents = discord.Intents.default()
# Initialize bot with intents and prefix '!'
bot = commands.Bot(command_prefix='!', intents=intents)
# Event: Bot is ready
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
# Event: Message received
@bot.event
async def on_message(message):
if message.author == bot.user:
return
print(f'Message received: {message.content}')
await bot.process_commands(message)
@bot.command(name='ping')
async def ping(ctx):
latency = bot.latency * 1000
await ctx.send(f'Pong! Latency: {latency:.2f}ms')
# Run bot with token
bot.run(TOKEN)
so when i type something, it sees the message, but doesnt show the content of the message, what did i do wrong here?
Try changing
intents = discord.Intents.default()
To:
intents = discord.Intents.default()
intents.message_content = True
``` (Also make sure you allowed message content in the developer intents portal)
read the documentation
now explain so i know what you fixed?
I believe its because discord.Intents.default() doesn't include message_content as True so you have to set it manually
k, i will have to brush up on intents, but thank you, is there any other pitfalls related you can think of?
I heard it can suppress some errors I think? Though in my experiences its been fine.
cool
Purpose of Intents:
Intents in Discord.py define which events your bot will receive information about from Discord's gateway. They help manage and limit the amount of data your bot receives, improving efficiency and security.
Default Intents:
discord.Intents.default() provides a set of default intents that cover most common use cases for bots, such as message events, member events, reactions, etc.
By default, message_content is not included in the default intents because it is considered a privileged intent due to potentially sensitive data.
Enabling message_content:
To access message.content and other message-related data in your bot, you need to enable the message_content intent explicitly.
This informs Discord that your bot intends to receive and process message content, allowing you to access message.content in your on_message event or command functions.```
omg i love it
oooo where'd u get that? From the docs?
no i uhh, im playing with the darkside of ai today >:)
making a simple discord bot for my filing cabinet of a server and adding a reminder system to do bumps
oh yea
nice and simple
???? Can't read the documentation? Lol
lf for someone to join my team to help me code a discord bot
The goal of the group is to make good bots for the community using it in need even when we make our own server
I'm doing interaction.command.parameters[0].name and it's still just printing item
that's the parameter name
Do you understand what I'm trying to get
You're trying to get the name of a commands arguments, correct?
Try display_name if this is just giving you the object identifier
Or is it literally returning the word 'item' because you're searching an item
I have auto completion that adds choices. I need to know name arguemnt of the choice they selected. As item is returning just the value of the choice
I think I've done something like this before - let me see how I handled it
Yea it looks like I did something similar to what was mentioned above. I kept a dictionary with all the info in it so I could use the returned value to find corresponding info
can you send your code
This is mine atm ```py
@app_commands.command(name="search")
async def search(self, interaction: discord.Interaction, item:str):
await interaction.response.send_message(f"Value - {interaction.command.parameters[0].display_name}")
@search.autocomplete("item")
async def search_ac(self, interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]:
data = []
items = await self.getItems(current)
if not items:
return "No results found"
for item in items.keys():
if current.lower() in item.lower():
if len(data) >= 25:
break
data.append(app_commands.Choice(name=' '.join(word.capitalize() for word in item.split()), value=items[f"{item}"]))
return data```
Sorry it's late here I'm about to get some sleep. Good luck
im trying to use diers and i tried to create a server for my python discord bot and it said no nodes were found, wdid?
@bot.command()
async def hello(ctx):
await ctx.send('Hello!')
async def cute(ctx):
await ctx.send('Cute')```
what am i doing wrong here?
just need another @ bot.command()
if its a bot command, yeah
oh, i see
idk, it is printing hello line twice
it is sending hello message twice, but i used print command to print hello in terminal, but it is sending it once only there
nvm, i see what i did
that will make the code too lengthy, is there a way i can shorten the code?
Im asking iN here and not a help channel as It will prob be deleted when I come back from school but I installed Jishaku and when I tested It out in my server by doing !jsk py 1+1 It didnt do anything i have no idea what the error Is I made sure I loaded it correctly please help.
If ur gonna make bots they will have 100s of lines. My bot has almost 300 lines
if won't make the laptop slow, right?
Just adding that one extra line for u wont chnage anything but If u make a huge bot then It could slow It down a little but i dont see a poblems or my bot slowing down for me
i have blue print to make a bot game, it might be too long, like more than 1000 lines lol
Use modules lol
can you give example??
Oof. I can make Python bots and Python games idk how to add them together tho
Create files that have a single responsibility
oh, can i return a whole list from that file??
For example, if the game uses a database you can make a module to handle that
Example:
thank youu
im trying to check if there is a specific word in the message```
dm me or ping me (im beginner so help me with code dont tell some adv solution)
if word in message
||```py
target_word = "duck" # Word you want to check for
@bot.event # Listen to the on_message event. (Which activates everytime a message is sent)
async def on_message(message : discord.Message)
if message.author == bot.user: # Return if the message is from the bot
return
Check if target word is in message (.content gets the text)
if target_word in message.content:
# Do something when word found
print("Found word! Wow so cool epic amazing I love that word that was found")
Something like that ^^^^
Oh crap you asked for advice not a solution.. Click the box to see a possible solution (with comments)
where the documents for the tree command
Wait autocompletes now need to be within the range of 25 of fewer?
ok
i can understand simple code like this
thx
np
@vital ore
but to send message in channel
instead of print the commmand is?
one sec
ok
await message.channel.send("This is a response")
await message.reply("This is a reply")
its message.channel.send
yep
?
this error is comi
ng
i cant send image
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
message.channel.send('test')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
oh ya i forgot abt that too
so its
await message.channel.send('test')
Also make sure the function is async
I thought they always were 25 or less
Well I have always had more than 25 in auto completes, but they will just fail to load in discord. Until you search for a certain auto complete name. But now it gives an error in 2.4.0 and I was wondering if there was anything else that allows me to go over 25. Because what I remember auto completes was the only one.
25 is the limit
Used to go over 25. Thats all im saying.
Well
Then that messes with many things :/
So many bots used auto complete + db connections because it went over the 25 limit
They should add another argument that allows you to chose how many options/choices show in the autocomplete then. Like how many show at once. So you can still have way more than 25 options in the list, but only show like 20 at once or something.
Bypassing this whole error.
actually nvm, I have an idea, and I fixed this. I can do it within the return
Can you pass variables into an interaction? If so, how?
what are you trying to do?
I have a Shop command and want to be able to view item information individually with embeds, and if you wish to buy the item using the virtual currency you press a button which at least gives the name of the item and if the user already owns it. I believe to do this without creating endless classes I'd need to pass the item name and ownership status to the interaction, but i could very definitely be wrong
do you mean the button callback, you wouldn't want to edit the Interaction itself?
class CommandErrorHandler(CommandTree):
async def on_error(self, interaction: discord.Interaction, error):
ignored = (app_commands.CommandNotFound, )
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
elif isinstance(error, app_commands.NoPrivateMessage):
try:
await interaction.user.send(f'{interaction.command.name} can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, app_commands.MissingAnyRole):
await interaction.response.send_message(f'{error.missing_roles} missing role')
elif isinstance(error, APIError):
print(error)
await interaction.response.send_message(content=f'{error.message}')
else:
print('Ignoring exception in command {}:'.format(
interaction.command.name), file=sys.stderr)
traceback.print_exception(
type(error), error, error.__traceback__, file=sys.stderr)
024-07-04 16:58:15 ERROR discord.ui.view Ignoring exception in view <SyncEmbed timeout=None children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='GFL' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.8\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "D:\AFW bot\afw_bot\ext\reaction_based\sync.py", line 62, in confirm
embed = await self.build_embed(button.label)
File "D:\AFW bot\afw_bot\ext\reaction_based\sync.py", line 37, in build_embed
t_stamp = await AFW_ROUTER.get_sync(league=league_name)
File "D:\AFW bot\afw_bot\ext\api\routes.py", line 64, in get_sync
raise APIError(response.status, error_message)
afw_bot.ext.api.routes.APIError: (401, 'Unauthorized')
why this is not getting caught in error handler?
Sorry yeah, my brain is getting fuzzy too much is going rn but im sure I meant callback
You normally would get the onwership status from a db? You can do that in the callback
the error occurred inside the button callback, this doesnt trigger tree on_error, it triggers View.on_error
how about the specific item? I might be sounding really stupid right now
you have the button object in the callback
either use its label or a custom attribute you set
ah ok thanks
how to check if there is mention in an argument?
class ViewErrorHandler(ui.View):
async def on_error(self, interaction: discord.Interaction, error):
print(error)
error = getattr(error, 'original', error)
print(error)
if isinstance(error, APIError):
print(error)
else:
print('Ignoring exception in command {}:'.format(
interaction.command.name), file=sys.stderr)
traceback.print_exception(
type(error), error, error.__traceback__, file=sys.stderr)
still its not working am i doing something wrong
2024-07-04 17:20:57 ERROR discord.ui.view Ignoring exception in view <SyncEmbed timeout=None children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='GFL' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.8\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "D:\AFW bot\afw_bot\ext\reaction_based\sync.py", line 62, in confirm
embed = await self.build_embed(button.label)
File "D:\AFW bot\afw_bot\ext\reaction_based\sync.py", line 37, in build_embed
t_stamp = await AFW_ROUTER.get_sync(league=league_name)
File "D:\AFW bot\afw_bot\ext\api\routes.py", line 64, in get_sync
raise APIError(response.status, error_message)
afw_bot.ext.api.routes.APIError: (401, 'Unauthorized')
doesn't it need to be the same Instance of ui.View where your button belongs?
that and also on_error receive discord.ui.Item as well
can somebody help me please?
i already added that its not getting triggered at all
@bot.hybrid_command(name="kitty", description="returns a Meow", with_app_command=True)
async def kitty(ctx):
await ctx.reply("Meow :3")
So, does anybody knows why this isn't getting registered as a slash command when I try to run it? Yes, I have other slash commands that work, yes, I restarted the bot, Yes, i added the code in the right py file
example:
@bot.event
async def on_ready():
print("Ready!")
sync = await bot.tree.sync()
then under it add
@bot.hybrid_command(name="ping", description="returns a pong", with_app_command=True)
async def pingcmd(ctx):
latency = round(bot.latency * 1000)
await ctx.reply(f"**Pong!**\nCurrent Ping: {latency}ms")
this u can check ping
but make sure to enable this first before adding ur bot, it's in the Oauth2 tab in the portal
what exactly? adding the code or enabling the button
u did bots before tho?
u mean @bot.command(): ?
idk much abt slash either but it's pretty simple
look, ik u have the on_ready() function in ur bot already, just add
sync = await bot.tree.sync()
then add the rest 2 of the codes I added u, same goes for the Oauth2 button, u need to go to discord portal and enabling it, then re-inviting ur bot back in the server if it was already there
i hope what I said helped u then lol
🗿🗿
yeah i dont even like them
slash commands or their syntax?
looks decent but slash commands general, im a more nostalgic way so i miss everything from the past discord
use buttons instead of reactions
seems funny now that discord was ACTUALLY good at one point 😭
whenever something good happens, there's always an idiot who says "yo i have an idea" and ruins everything
not nuke bot but for ticket bot
so it send like
explain what you want:
some like this
access the text channels list through Guild.text_channels then loop over them to send a message in each
The list will have discord.TextChannel objects
i got this rn im new to py
it's outdated, we don't use @client.event no more
a discord bot is an intermediate-hard project, wouldn't want to start with a discord bot project straight away
If you use await bot.get_channel(CHANNEL ID).send("message") or if you get the channel as an object and instead use that maybe
how are you supposed to make an event then 😭
hang on I have my own ticket system somewhere
buddy the thing is it's not @client.event it's @bot.command() lol, he uses the old discord.py vers
yes but i want it to send to all new channels that are created it would be easyer
well that was vague 🗿
oh
it makes multiple new channels?
there's a lot to learn at discord.py so this server will be ur friend alongside new yt tutorials
if someone makes ticket its new channel so it will send msg there
🙂
yeah so it only makes one channel at a time though?
he means it like this:
He wants his own ticket system, where when the bot creates a new ticket channel, the bot will send a message, like ticket bot does
oh OK yeah I have that
yh for each person
assuming your tickets will be made in the same category as the message triggering the ticket to be made...
category = ctx.message.channel.category # This gets the category of the channel where the message was sent
new_channel = await category.create_text_channel(name="ticket") # Create a channel in the category and name it "ticket"
await new_channel.send("explain the problem: ") # Send a message in the new channel```
I could be oversimplifying my code since I used interactions and databases, but this should be a base function with explanations on how these work.
NOTE - all of this code should be inside a command's function
uhm
uhh i understand it
but idk how to add this into my code
im really new to py
The screenshot above is all of your code, correct?

