#discord-bots

1 messages · Page 376 of 1

chilly pumice
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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.

hushed galleon
#

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)```
chilly pumice
#

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
hushed galleon
chilly pumice
#

thx

boreal sigil
#

Im basically looking for an example

hushed galleon
#

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

unkempt canyonBOT
#

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).
boreal sigil
#

do u have some like full example code for it? the time stuff confuses me

#

everything else is fine tbh

hushed galleon
#

like you're wondering how to create timedeltas?

#

!d datetime.timedelta < you can pass the number of seconds, minutes, days, etc.

unkempt canyonBOT
#

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...
boreal sigil
#

so basically I want to focus on the bolded bit below:
hybrid cmd btw
/mute <user> <time> <reason>

hushed galleon
#

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

wanton current
#

there's also a library called dateparser that basically allows anything in any language and can convert it to a datetime.datetime object

boreal sigil
#

also quick question -

#

how can i add a description for a slash command / hybrid cmd

hushed galleon
wanton current
#

i guess

hushed galleon
boreal sigil
#

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)
wanton current
boreal sigil
#

where does one put the line that has the description?

#

like inbetween what bits

lean juniper
#

how do i use aliases in cog files

fast osprey
#

Same way you'd use them anywhere else, it's a parameter in the command decorator

lean juniper
#

i spelled aliases wrong oh my god

boreal sigil
hushed galleon
# boreal sigil 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

lean juniper
#

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

wraith zinc
#

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!

fast osprey
#

Are you betting with fiat or crypto?

lean juniper
#

wat is RuntimeWarning: Enable tracemalloc to get the object allocation traceback

willow sluice
#

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

slate swan
#

!res

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

meager fable
#

or is it something entirely different

hushed galleon
tender bobcat
#

(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

chilly pumice
#
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?

meager fable
#
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)
golden portal
meager fable
#

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

sick birch
#

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

sick birch
#

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?

meager fable
#
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

sick birch
meager fable
#

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

meager fable
#

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
upbeat otter
#

you have to mention them roles

#

!d discord.Role.mention

unkempt canyonBOT
meager fable
#

on the topic of roles, how do you add a specific role to a user?

upbeat otter
#

yes

upbeat otter
unkempt canyonBOT
#

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.
upbeat otter
#

access the roles individually

#

yes that Or a list comprehension

#

use a for loop then

#

list comps just look cleaner

quick gust
#

thats a for loop yes

upbeat otter
#

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

meager fable
upbeat otter
#

well it is

#

wouldn't even personally use it

#

and thats against the TOS so it's shit

meager fable
#

what could be done in a few lines is done in like x10 more lines in djs

upbeat otter
#

💀ok nvm this is a python server

quick gust
upbeat otter
meager fable
#
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

upbeat otter
#

you need an object

meager fable
#

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

upbeat otter
#

yes that

#

bro switched sides too

meager fable
#

I see that but I already gave it admin

#

oh wait can it not give the owner (me) a role

upbeat otter
#
for role in member.roles:
 ...```
meager fable
#

oh that makes sense

upbeat otter
#

it can if your bot haz admin perm

#

it doesn't matter

#

show code

meager fable
#

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

fast osprey
fast osprey
#

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"

dry kelp
#

How can we fetch the member server banner from profile? If there's a server profile setup.

#

using disnake library

timber dragon
fast osprey
#

Without constructive criticism on what exactly is lacking, this just comes off as a skill issue

timber dragon
#

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?

fast osprey
#

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

dry kelp
#

wait

#

sorry , i mean member banner from server profile

#

i saw a bot that can fetch either user profile banner or server profile banner

timber dragon
#

Not a thing in the api

dry kelp
#

Ah i see, thanks a lot.

timber dragon
#

Well not for bots

fast osprey
#

There is a folder in the examples of the repo for views which can help

timber dragon
#

!d discord.User.public_flags

unkempt canyonBOT
timber dragon
#

That's guild specific yes

#

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

fast osprey
#

There is no accurate way of determining nitro afaik

#

They deliberately do not expose that in the api

timber dragon
#

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
fast osprey
#

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

timber dragon
#

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

fast osprey
#

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

charred island
#

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

unkempt canyonBOT
fast osprey
#

These are all guesses

pearl bough
#

What exactly are you trying to do here?

fast osprey
#

Something being right doesn't make it not a guess

pearl bough
#

As in, nitro or not nitro?

#

oh interesting, it doesn't expose the profile to the bot so you can't see it

fast osprey
#

Nitro specifically is not a user flag that the api exposes to bots

fast osprey
#

All of those are things you could check

#

And all of them, even combined, will give false negatives

#

That would be a false positive

pearl bough
#

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

merry cliff
#

can't you pay for a boost without having nitro?

pearl bough
#

Therefore you could get a false positive if you're checking by boosts

fast osprey
#

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

slate swan
#

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?

fast osprey
#

Depending on rate limits and how slow the api is, you may wish to cache these results

slate swan
#

But is it possible to do what I'm asking

fast osprey
#

Yes

slate swan
#

Do you know of any examples I could base it off of

fast osprey
#

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

slate swan
#

Alrighty thanks

slate swan
#

This is my code

#

won't let me send it

quick gust
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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.

chilly pumice
#
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?

slate swan
#

my code is a lot smaller than his and it wouldn't work 😭

#

Code ^

#

Error ^

fast osprey
#

Is your command in a cog?

slate swan
fast osprey
#

All methods in a class should accept self first

slate swan
#

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?

fast osprey
#

Code?

dim pond
#

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!

meager fable
#

Hi! What's the best way to host a discord bot for free 24/7?

scarlet tiger
#

Some services offer a free trial, for example Digital Ocean

mild token
#
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?

opal vortex
#

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)
timber dragon
# opal vortex no

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

shrewd cradle
#

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}")
timber dragon
timber dragon
wheat thunder
#

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.

wheat thunder
#

Resolved: This was an issue with import.

Solved by making the parent aware of the child's existence by importing inside init.py

copper flume
#

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?

wanton current
#

how did you update it

red sparrow
#

im trynna extract some info from this json file but it doesnt work

mild token
#
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 : (

chilly pumice
#

can I put select list in modal?

copper flume
wanton current
#

you need the -U flag to update

copper flume
wanton current
#

yes

copper flume
#

i need to restart my bot?

#

or it will update on updating the module

wanton current
#

you need to restart it

copper flume
wanton current
#

how are you running the command

copper flume
wanton current
#

and what version is it

copper flume
# wanton current 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`
wanton current
#

what if you do pip install googletrans==3.1.0a0 --force-reinstall

copper flume
#
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
copper flume
#

restart again?

wanton current
#

do pip show and see

copper flume
#

but when i do using bot it shows the old one

wanton current
#

then restart it

#

or do you have a venv or smth

copper flume
copper flume
boreal sigil
#

@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)
wanton current
copper flume
boreal sigil
# wanton current ?

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

copper flume
#

actually im also facing issues with my firewalls

#

i denied port 3000 anywhere but still it is open

wanton current
#

that is out of scope of this channel

wanton current
#

that you made

boreal sigil
#

what is typehint 😭

#

its type hint

#

!d type hint

unkempt canyonBOT
#

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().

See typing and PEP 484, which describe this functionality.

boreal sigil
#

how tf do i use this stuff tho 😭

opal vortex
boreal sigil
#

what type hints file

opal vortex
#

the * represents the name of the file you want to type hint.

boreal sigil
#

im so confused am i supposed to have a file?

opal vortex
#

and you need another empty file as well

#

yes

#

py.typed is needed it seems as well

boreal sigil
#

btw how

opal vortex
#

not sure why when I can do only pyi files.

opal vortex
boreal sigil
#

I just want a basic timeout cmd 😭

boreal sigil
wanton current
#

typehints != stub files

boreal sigil
#

is this defo the best way to do a timeout command?

mild token
#

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?

boreal sigil
#

like is this the simplest way to make a timeout command 😭

wanton current
#

not really

#

!d discord.Member.timeout

unkempt canyonBOT
#

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).
opal vortex
# wanton current what

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.

wanton current
#

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.

mild token
#

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?

idle vault
idle vault
#

You need the &, in order to mention roles

red sparrow
#

Can anyone help me im trynna extract player information from this json for my bot

red sparrow
#

what?

red sparrow
#

for people to see player stats via discord

slate swan
#

ok

red sparrow
slate swan
#

your data is archived

#

in .gz format

#

so it wont be able to be json loaded

idle vault
red sparrow
#

if its gz

slate swan
#

find how to unarchive the file

#

like extract it

red sparrow
mild token
#

How to add emoji to button?

red sparrow
#

huh?

mild token
mild token
red sparrow
#

thats what it says

boreal sigil
mild token
#

How to use partial emoji?

red sparrow
#

still

mild token
#

Why u want to write instead do read?

red sparrow
#

changed to read

mild token
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

mild token
#

I highly recommend u to check these out

red sparrow
#

PLS

#

Is it the file?

mild token
#

I don't know I seen that myself first time

#

Btw what is that?

red sparrow
mild token
#

The link u trying to access?

mild token
#

Bcz the link looks like a download link

red sparrow
mild token
#

Is it a download link when u open it?

red sparrow
mild token
sharp hazel
#

hey. there's a event that is called after the interaction (like a button) ended?

sharp hazel
mild token
mild token
mild token
red sparrow
sharp hazel
mild token
red sparrow
#

can i specify one info

#

like get the name in info

red sparrow
#

erm what the sigma

timber dragon
#

Try again

wanton current
opal vortex
# red sparrow

first ensure the firewall is configured to allow access to discord.

finite salmon
slate swan
finite salmon
# red sparrow

Their path don't look like they're running on a local machine

stuck mountain
#

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

echo sluice
#

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?

finite salmon
echo sluice
#

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]))```
finite salmon
#

Yep

dusky spade
#

didn't know you chat in this server

ivory mauve
#

anyone knows how to make a telegram bot?

mild token
keen furnace
solid turtle
#

someone can help me

slate swan
golden portal
slate swan
# golden portal 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"

golden portal
#

!d discord.app_commands.CommandTree.copy_global_to

unkempt canyonBOT
#

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.
slate swan
#

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

golden portal
#

sync it globally, remove guild=ctx.guild

slate swan
golden portal
#

you dont need copy global, thats only if you want to sync to a specific guild for a global slash command

slate swan
#

Alright it's working, I appreciate it g

slate swan
#

@golden portal

the item variable is returning the value of the selected choice. How could I get the name of the selected choice aswell?

golden portal
#

code

slate swan
golden portal
#

show the code

vapid parcel
#
  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

wheat thunder
#
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)

timber dragon
#

Try reloading your discord client

#

ctrl r

wheat thunder
#

in terminal?

timber dragon
#

On discord

#

The app you're using currently

wheat thunder
timber dragon
#

prettythumbsup

It usually refreshes them itself but always try it when it doesn't

wheat thunder
#

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..?

timber dragon
#

Duplicates in your list maybe?

#

You shouldn't sync on startup btw and not at all in on_ready

wheat thunder
#

I already print cog list
['app.cogs.event_cog', 'app.cogs.dialogue_cog']

wheat thunder
wheat thunder
#
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.\

timber dragon
#

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)
wheat thunder
#
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?

boreal sigil
#

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)
mild token
#

is it possible to reinvoke application command?

boreal sigil
mild token
boreal sigil
mild token
boreal sigil
#

alr

#

welp

#

unless you make some code for a sync command, there aint a way to get slash commands from ur code into discord

upbeat otter
boreal sigil
#

idk

#

its what some1 else on here told me to use

upbeat otter
mild token
#

hmm

boreal sigil
#

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!')
boreal sigil
slate swan
#

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

boreal sigil
slate swan
#

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

boreal sigil
#

alrighty

boreal sigil
# slate swan by placing variable I meant variable along with the value

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!')
slate swan
#

Nope, the thing you had before was correct

boreal sigil
#

then why did it not work

slate swan
#

you just had to move definition of nothidden before await ctx.channel.send(...)

boreal sigil
#

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!')
slate swan
#

and what is the current problem?

boreal sigil
#

it doesnt send the embed nothidden

#

just sends the embed: 'unhide'

slate swan
#

pithink 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

boreal sigil
#

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

slate swan
#

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
boreal sigil
#

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
slate swan
#

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

boreal sigil
#

what is the variable name?

#

or where do i find it

slate swan
boreal sigil
#

overwrite?

slate swan
#

yeah

boreal sigil
#

great

#

im not that stupid at least

#

i am not doing tis right

wheat thunder
#
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?

boreal sigil
slate swan
#

you placed the "if" check outside of the function

boreal sigil
slate swan
#

look at the indentation

boreal sigil
#

ohhhhhhhhhhhh

#

that bit has been fixed at least

slate swan
#

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

boreal sigil
#

so where the red line is?

slate swan
#

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
vocal laurel
#

unrelated but @lock.error seems wrong instead should be @unhide.error

boreal sigil
#

wait is it not already like that?

slate swan
#

True, I haven't touched that since I thought it refers to a different command

boreal sigil
vocal laurel
slate swan
boreal sigil
faint sapphire
#

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

boreal sigil
#

so:

nothidden = discord.Embed()
vocal laurel
boreal sigil
vocal laurel
slate swan
#

let's do it in small parts

boreal sigil
#

ill just leave it since it doesnt affect anything

boreal sigil
vocal laurel
slate swan
#

first define how your emed should look like, you can pass a title as an argument, a description and a colour

vocal laurel
#

however lets continue with what Ray is saying

boreal sigil
slate swan
#

nope, that is an empty embed

vocal laurel
boreal sigil
vocal laurel
slate swan
# boreal sigil

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

boreal sigil
#

i need to remove the earlier bit

#

done that

vocal laurel
#

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

boreal sigil
#

uuh

#

ohhh

#

ok

vocal laurel
#

since you are doing overwrite.view_channel = True then the if statement will always trigger even if the channel wasn't hidden

vocal laurel
boreal sigil
#

indent more? ok

#

how much do i indent

vocal laurel
#

indent the 3 lines after the if statement

boreal sigil
vocal laurel
#

looks right except for the 2 lines above @unhide.error

slate swan
#

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

vocal laurel
#

Sorry, that is my bad

boreal sigil
#

it does not know what "overwrite" is
i thought?...

slate swan
#

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

boreal sigil
#

im confused (sorry guys im kinda thick in the head)

slate swan
#

Look at the logic inside of your command

vocal laurel
slate swan
#

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)

slate swan
vocal laurel
vocal laurel
#

Never mind I guess.. Thought you meant you need help with something and needed someone's assistance

slate swan
#

kekw

boreal sigil
#

so if before overwrite is bad

slate swan
vocal laurel
vocal laurel
boreal sigil
#

so i move it after the overwrite

slate swan
vocal laurel
boreal sigil
#

great

slate swan
boreal sigil
slate swan
#

I think the best way of actually explaining people stuff is letting them know the POV of the program ducky_angel

boreal sigil
#

the docs are the best things there is

vocal laurel
# boreal sigil

what are the 2 lines above @unhide.error meant to be used for?

boreal sigil
vocal laurel
boreal sigil
#

ignore those

slate swan
# vocal laurel what have you done so far?

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?

boreal sigil
#

removed em

vocal laurel
#

ok so basically

slate swan
# boreal sigil

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

boreal sigil
#

alright

#

so what do I need to do to fix that?

vocal laurel
slate swan
#

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

slate swan
slate swan
#

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

vocal laurel
#

hm

slate swan
#

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

slate swan
#

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 pithink

slate swan
slate swan
#

nope, put it after defining overwrite but befoe setting view_channel to True (in between)

faint sapphire
#

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")

boreal sigil
#

i have it after the 2nd one atm

slate swan
#

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

upbeat otter
slate swan
#

TIL

upbeat otter
boreal sigil
upbeat otter
#

in your case content=...

slate swan
slate swan
#

great

boreal sigil
#

should it work now?

slate swan
#

that should be it

boreal sigil
#

awesome - ill test it and lyk

#

works great BUT
the colour isnt what I wanted

faint sapphire
boreal sigil
#

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

faint sapphire
#

if u paste the right hex colour, it should work

slate swan
#

you would just have to replace the colour value in the nothidden embed

boreal sigil
#

yeah but i didnt think it worked with normal hex codes?

#

alr lemme see

#

yeah nopers

#

wait a min

faint sapphire
#

noo

boreal sigil
#

im stupid AF

the #

#

this normal then?

rain hedge
slate swan
#

0xff54242

rain hedge
#

then the rest

boreal sigil
#

ahh ok ty

rain hedge
#

np

boreal sigil
#

thanks peeps! trying it now

slate swan
boreal sigil
rain hedge
boreal sigil
faint sapphire
#

add an f

#

like they said

boreal sigil
#

ohhhh

boreal sigil
slate swan
#

you changed the colour of the wrong embed

boreal sigil
#

wait

#

did i

slate swan
#

this is the one to change

boreal sigil
#

holy jesus im stupid

rain hedge
#

simple mistake

boreal sigil
#

yeah

faint sapphire
boreal sigil
#

trying it again now

faint sapphire
#

jk

rain hedge
boreal sigil
#

uuuhhhhhh

#

doesnt respond to ?unhide now

#

no errors

slate swan
#

what is the current code pithink

boreal sigil
#
# 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!')
upbeat otter
slate swan
boreal sigil
#

theres nothing in terminal...

slate swan
#

tried rerunning the bot?

#

and then checking if anything is displayed

slate swan
upbeat otter
wheat thunder
#

Can I get a info about slash command with example?

boreal sigil
faint sapphire
#

its the same stuff,
u just add like
bot.tree
then use interactions instead of ctx

boreal sigil
#

@slate swan same issue - nothing in terminal and no response to command

faint sapphire
#

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)
slate swan
#

weird

boreal sigil
#

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!')
quick gust
#

you should try to see if theres any other error apart from CheckFailure

slate swan
#

oh right

#

you aren't passing any channel as an argument

boreal sigil
#

so

#

its supposed to be done in the channel its sent in

#

and the slash command has a channel field as an argument

slate swan
#

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

boreal sigil
slate swan
#

otherwise it will be the channel in which the command has been invoked

quick gust
#

and you should also switch ctx.channel -> channel wherever ure using it

slate swan
#

true

quick gust
#

also add

else: 
  raise error``` 
in your local error handler
boreal sigil
#

local error handler?

quick gust
#

@unhide.error

boreal sigil
boreal sigil
quick gust
#

after adding the else, restart bot and run the command again and see if there are any errors

boreal sigil
#

so

#

a lot of stuff

quick gust
#

?

slate swan
#

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
boreal sigil
#

`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.`

boreal sigil
quick gust
#

ff54242 isn't a color?

#

are u sure u didn't make a mistake copying the hex

slate swan
#

nope, do this

async def unhide(ctx, channel : Optional[discord.TextChannel] = None):
  channel = channel or ctx.channel
  # Rest of your logic
boreal sigil
#

can i still keep """ Unhides the channel the command is used in, or a specified channel """? @slate swan

slate swan
#

yeah sure

#

I mean program just takes it as a docstring/string/comment

boreal sigil
#
# 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
slate swan
#

yep

boreal sigil
#

now try?

quick gust
slate swan
#

but the hex colour is wrong

boreal sigil
#

oh

#

how?-

quick gust
#

if you want red you're probably looking for ff5424

slate swan
#

ff5424 maybe?

quick gust
#

its f54242, you have ff54242

slate swan
#

f54242

boreal sigil
#

i was told to add another f

quick gust
#

Nah u just need a 0x

boreal sigil
#

alright

slate swan
boreal sigil
slate swan
boreal sigil
#

works with no errors in terminal! thanks guys. now need to repeat this all 3 more times Bulbasaur_sigh

quick gust
#

Nice

gilded bough
#

So I organized my folders to sell the bot is this good Enough?

tepid ruin
gilded bough
#

Thanks

tepid ruin
#

Perhaps a readme or something for the people who arent so smart with programming

gilded bough
#

Thanks for the advice

tepid ruin
#

No problem

#

And maybe rename the main.py to something like run so its more clear for the user

quick gust
#

I mean u could have a run.bat file which executes the main.py file

swift acorn
#

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

wind radish
swift acorn
#

yea bugcatsweaty and it's always something you don't check haha

spring rampart
#

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

swift acorn
#

you click on "terminal" in the top bar, and install using pip there

and also make sure you have Python installed on your computer!

spring rampart
#

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

sharp hazel
#

hi, there's anyway to send multiple ephemeral messages?

slate swan
#

No

full lily
boreal sigil
#

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?

twin junco
#

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}"```
full lily
#

I think there's something you can do to force a refresh. Maybe someone else can advise

twin junco
#

alr so the code is fine

#

?

full lily
#

is there an error?

twin junco
#

no but i cant run it untill the / command appears

#

so idk

full lily
twin junco
#

thanks for ur help bones, all i had to do was ctrl + r

full lily
#

aight cool

sharp hazel
#

does anybody know how to add buttons like this?

ornate quarry
#
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?

vital ore
scarlet tiger
ornate quarry
vital ore
#

I believe its because discord.Intents.default() doesn't include message_content as True so you have to set it manually

ornate quarry
#

k, i will have to brush up on intents, but thank you, is there any other pitfalls related you can think of?

vital ore
ornate quarry
#

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
vital ore
ornate quarry
#

no i uhh, im playing with the darkside of ai today >:)

ornate quarry
#

making a simple discord bot for my filing cabinet of a server and adding a reminder system to do bumps

scarlet tiger
solid turtle
#

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

slate swan
upbeat otter
#

that's the parameter name

slate swan
mighty pilot
mighty pilot
#

Or is it literally returning the word 'item' because you're searching an item

slate swan
mighty pilot
#

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

slate swan
#

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```
mighty pilot
mortal lake
#

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?

past spire
#
@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')
async def cute(ctx):
    await ctx.send('Cute')```
what am i doing wrong here?
mortal lake
#

just need another @ bot.command()

past spire
#

oh, oki

#

do i have to do bot.command before every function?

mortal lake
#

if its a bot command, yeah

past spire
#

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?

limber jolt
#

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.

limber jolt
past spire
limber jolt
past spire
past spire
limber jolt
scarlet tiger
past spire
#

oh, can i return a whole list from that file??

scarlet tiger
past spire
#

oh, i can imagine what i have to do now

#

i think i can do it

scarlet tiger
past spire
#

thank youu

fierce ridge
#
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)

twin crown
#

if word in message

vital ore
# fierce ridge ``` im trying to check if there is a specific word in the 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)

solid turtle
#

where the documents for the tree command

vapid parcel
#

Wait autocompletes now need to be within the range of 25 of fewer?

fierce ridge
#

ok

fierce ridge
#

thx

vital ore
fierce ridge
#

but to send message in channel

#

instead of print the commmand is?

vital ore
#

one sec

fierce ridge
#

ok

vital ore
#

await message.channel.send("This is a response")
await message.reply("This is a reply")

fierce ridge
#

its message.channel.send

vital ore
fierce ridge
#

thx

#

@vital ore

vital ore
#

?

fierce ridge
#

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```
vital ore
#

Oh wait sorry

#

you're meant to add await to the start

fierce ridge
#

oh ya i forgot abt that too

vital ore
#

so its
await message.channel.send('test')

fierce ridge
#

ya

#

understood thx

vital ore
#

Also make sure the function is async

slate swan
vapid parcel
# slate swan 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.

slate swan
#

25 is the limit

vapid parcel
slate swan
#

then it was most likely changed

#

dunno

vapid parcel
#

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

dense falcon
#

Can you pass variables into an interaction? If so, how?

north kiln
#

what are you trying to do?

dense falcon
#

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

north kiln
#

do you mean the button callback, you wouldn't want to edit the Interaction itself?

mild token
#
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?

dense falcon
north kiln
#

You normally would get the onwership status from a db? You can do that in the callback

golden portal
dense falcon
north kiln
#

you have the button object in the callback

#

either use its label or a custom attribute you set

dense falcon
#

ah ok thanks

harsh orbit
#

how to check if there is mention in an argument?

mild token
# golden portal the error occurred inside the button callback, this doesnt trigger tree on_error...
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')

quick gust
#

doesn't it need to be the same Instance of ui.View where your button belongs?

golden portal
#

that and also on_error receive discord.ui.Item as well

harsh orbit
#

can somebody help me please?

mild token
stoic tusk
#
@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

upbeat otter
#

🗿🗿

stoic tusk
#

yeah i dont even like them

upbeat otter
stoic tusk
upbeat otter
#

use buttons instead of reactions

upbeat otter
slate swan
#

nice

#

how can i make a discord bot send msg to a every new channel created

stoic tusk
slate swan
#

not nuke bot but for ticket bot

#

so it send like

explain what you want:

#

some like this

stoic tusk
#

like ticket bot?

#

ye he wants his own

#

his own ticket system

slate swan
#

mine doesnt

#

im trying to learn py and stuff and trying to make a bot

upbeat otter
slate swan
#

i got this rn im new to py

stoic tusk
upbeat otter
dense falcon
upbeat otter
dense falcon
#

hang on I have my own ticket system somewhere

stoic tusk
slate swan
dense falcon
stoic tusk
slate swan
dense falcon
#

yeah so it only makes one channel at a time though?

stoic tusk
dense falcon
#

oh OK yeah I have that

slate swan
dense falcon
#

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
slate swan
#

uhh i understand it

#

but idk how to add this into my code

#

im really new to py

dense falcon
#

The screenshot above is all of your code, correct?