#Basic Pycord Help

1 messages · Page 12 of 1

lofty parcel
#

I think it doesn't. Use py-cord-dev

summer scroll
#

hello, quick question:
user= discord.utils.get(ctx.guild.user, id = user_id)
is what I try to use in order to fetch a certain user but:

#

AttributeError: 'Guild' object has no attribute 'user'

#

do you guys have the right way to do this pls

stoic patio
#

but that one for some reason results in modulenotfound

#

ig i'll wait

sly karmaBOT
summer scroll
#

ty

stoic patio
#

ig i'll just wait for the actual release

lofty parcel
#

Did you uninstall py-cord

#

Show pip list

lofty parcel
stoic patio
stoic patio
lofty parcel
stoic patio
lofty parcel
stoic patio
#

i uh need that

lofty parcel
stoic patio
#

invites

#

ik that thing has a way to easily find who invited someone

shell radish
#

just copy their code

stoic patio
#

what "code"

shell radish
deft kestrel
#

Is it possible to block a user from using your bot with on_application_command?

red mist
deft kestrel
#

Yeah I tried that but the command still goes through

stoic patio
#

still modulenotfound

opal hamlet
#

or just defer

deft kestrel
little cobalt
deft kestrel
#

My user ID.

opal hamlet
#

may i see da code?

deft kestrel
#
    @commands.Cog.listener("on_application_command")
    async def on_application_command(self, context: discord.ApplicationContext):
        print(context.command.name)
        if context.user.id in blacklist:
            await context.respond("Nope")
            return
opal hamlet
#

that should go into the command

#

that event only gets triggered after/when a command is executed

deft kestrel
#

Yeah the reason I wanted to see if it was possible in an event is because I have a lot of commands and I didnt want to add a check to each one

opal hamlet
#

well maybe there's a way i dont know of but eh 🤷 that's what i'd do

lofty parcel
#

Or create a decorator for your commands

deft kestrel
#

Yeah im just going to use commands.check

little cobalt
elfin quarry
#

Hello, I'm trying to send a paginator with a slash command using paginator.send(), ctx is discord.ApplicationContext but im getting:

Traceback (most recent call last):
  File "/root/Testinator/testinator/lib/python3.11/site-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/root/Testinator/testinator/lib/python3.11/site-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/root/Testinator/testinator/lib/python3.11/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>
shell radish
elfin quarry
grim estuary
#

Hello. Slash commands are not displayed in Cog. What could be the problem?

lofty parcel
grim estuary
lofty parcel
grim estuary
lofty parcel
#

Do other cogs work?..

grim estuary
#

This is the only Cog in the program

lofty parcel
#

How are you loading your cog

#

Where

grim estuary
#

Where intents

lofty parcel
#

What

#

Show code

grim estuary
#

Everything was fine on the test bot with the same code, what happened to this?

fickle salmon
#

guild permissions?

grim estuary
lunar nacelle
#

so i havnt used pycord in while i have message being sent via chanel no interactio connected to it wuth button i want button to edit the message sent to channel i tried ```async def green(self, button: discord.ui.Button, interaction: discord.Interaction):

await interaction.edit_original_response```
but it just receives 404 error and it said edit original_message was depreceated which is what i thought i used before

red mist
#

I am not sure but could it be that the message it tried to edit is too old?

#

just like that bots cant delete messages which are too old

lunar nacelle
#

its instant

#

like within second or two

#

i cant even read the title

#

oh do i need intents? evn though bot sent message

lofty parcel
lunar nacelle
#

that worked for editing thanks

#

i also need to get content of message and original_response still is 404

#

turns out its interaction.message not original_response

lofty parcel
#

original_response is when you send a interaction.response.send_message

odd bramble
#

does pycord / discord api allow access to the pronouns of a user?
or is that under the same clause as user bio?

obtuse star
#

What would be the easiest way to check if a user is in a specific Discord Server? All the methods I've seen aren't working properly. I have a task running every 10 minutes, and I want it to check if specific people are in a premium SQL database/also in the Discord Server.

I've used:

guild = self.bot.get_guild()

And checked

guild.members

My issue is the Discord cache seems to reset randomly? Causing it to sort of flush and automatically trigger my system the wrong way.

Is there a straight way to simply check if a user is in the Discord or not without using any sort of cache? So the result is always correct?

opal hamlet
#

Well if cache is empty just use fetch instead of get

#

Don't have the specific stuff for it but that's what I'd look for

obtuse star
#

This is the code

#

The channel1 id is still returning None. I tried get_channel, fetch_channel doesn't work.

opal hamlet
#

I'd just do py channel1 = self.bot.get_guild(id) or self.bot.fetch_guild(id)

#

One of those could be async/awaited

obtuse star
#

No channel1 is suppose to be the channel ID so I can send a message to that channel

opal hamlet
#

Just gotta ReadTheDocs

opal hamlet
obtuse star
#

None of them work.

obtuse star
#

fetch_channel returns a courtine

opal hamlet
#
    chan1 = bot.get_channel(settings.statuschannel_id) or await bot.fetch_channel(settings.statuschannel_id)``` snippet from my bot
obtuse star
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/tasks/__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "/home/container/Cogs/premium.py", line 34, in scan_task
    await channel1.send("Ok")
TypeError: can't send non-None value to a just-started coroutine```
opal hamlet
#

Did you await?

hallow copper
#

you don’t need to await

obtuse star
#

I didn't await. It's still raising the error.

obtuse star
hallow copper
#

you do need to await

#

i think

#

idk how to use python

#

wuts wrong with my code?
print(hello world)

obtuse star
#

@hallow copper

hallow copper
#

hm?

obtuse star
#

Is it possible to manually scan and see which people are in specific roles, instead of relying on cache?

hallow copper
#

idkkk i haven’t actually worked on my bot in a while

#

ask chatgpt or sum

#

or read the docs or sum

obtuse star
#

gpt sucks :/

#

If they update gpt to 2023, it'll be good

hallow copper
#

ik but old answers are better that nothing

#

plus i wanna sleep

#

have you tried googling it?

boreal sky
#

Is there a way to get the list of all message/user commands?

#
logger.info(f"[cyan]Loaded {len(bot.cogs)} cogs[/]")
logger.info(f"[cyan]Loaded {len(bot.commands)} commands[/]")
logger.info(f"[cyan]Loaded {len(bot.application_commands)} application commands[/]",)

basically the last log isn't outputting what I expected :[

opal hamlet
errant trout
#

I wouldn't really recommend it over cache though, what intents do you have?

#

Fetch has to be awaited

errant trout
boreal sky
#

I know all_commands was 1 which was incorrect for me as it should be 3

errant trout
#

What if you do _application_commands?

boreal sky
#

I guess I'll have to mess with it when I can

junior ember
#

Anyone know how to do menus

#

Cuz i cant find shit in the docs

lofty parcel
lapis dock
#

.rtfm ui.Select

limber terrace
cyan violet
#

Hey

#
@client.slash_command(guild_ids=servers, name="pillow_test")
async def pillow_test(ctx, member: discord.Member):
    if member is None:
        member = ctx.author

    img = Image.open("img/welcome.png")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("fonts/Hanson-Bold.ttf", 40)

    # Get image dimensions
    img_width, img_height = img.size

    # Get text size
    text = f"Willkommen {member.name}!"
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    # Calculate coordinates to center the text
    x = (img_width - text_width) / 2
    y = (img_height - text_height) / 2

    # Write Text on Image
    draw.text((x, y), text, (255, 255, 255), font=font, stroke_width=1, stroke_fill=(0, 234, 255))

    # Save Image
    img.save("welcome.png")

    # Send Welcome Image
    await ctx.respond(file=discord.File("welcome.png"))```
#

how can i make the text to gradient?

#

for example red and black or something

floral ice
#

how do i create quick empty interaction answer without sending a message? (to avoid interaction failed message)

lofty parcel
#

Use an ephemeral message

floral ice
#

oh nvm i figured it out sorry

#

i forgot to edit the view

wise parcel
#

Hey, so i have this basic command ```import discord
from discord.ext import commands

intents = discord.Intents.all()

client = commands.Bot(command_prefix="ku!", case_insensitive=True, intents=intents)

@client.event
async def on_ready():
print("Kuze has started")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Prefix: ku!"))

@client.command
@commands.is_owner()
async def hirek(ctx, msg):
channel = client.get_channel(1159774208642007040)
await channel.send(msg)
await ctx.send("The message has been sent to the specific channel")

@client.command
async def otlet(msg, desc):
embed=discord.Embed(title="Új ötlet érkezett!")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1139444058985599026/1159926636364439662/Frame_1.png?ex=6532ccdc&is=652057dc&hm=40b87264487bf7c2793d1f07222b6560fcc9e3250fd6a3ecaf42a7ebf271d193&")
embed.add_field(name=f"{msg}", value=f"{desc}", inline=False)
embed.set_footer(text="Köszike hogy segíted a szerver fejlődését")
channel = client.get_channel(1159774260374552619)
await channel.send(embed=embed)
and if i start the bot it starts and everything. But when i type ku!help it only shows the help cmd and if i type ku!otlet no error justcommand not found```

little cobalt
#

@client.command()

#

also

#

?tag get_x

limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

boreal sky
#

Does the bot have to be ready when this is checked or something?

#

Oh, yeah. I moved the logging to on_ready() and now it properly shows 4

#

How does one disable pycord's logging...?

fickle salmon
boreal sky
#
def setup_logging() -> None:
    """Set up logging for the bot."""
    logging.basicConfig(
        level=logging.INFO,
        format="%(message)s",
        datefmt="[%X]",
        handlers=[
            RichHandler(markup=True, rich_tracebacks=True),
        ],
        force=True,
    )
#

but yeah for whatever reason pycord's log messages are showing and I really don't want them tbh

obtuse star
#

This doesn't trigger at all. When a role is added/removed, nothing happens.

wise parcel
#

hey so i have this code @client.command() @commands.has_role('-₊˚ | Partner intéző') async def partnerek(ctx, member, partnerszerv, szoveg): partnerek = client.get_channel(1159774325944111125) psz = client.get_channel(1159774283036360714) role = ctx.guild.get_role(1159773692486754304) await client.add_roles(member, role) await ctx.send("Siker") and i got this error:```Ignoring exception in command partnerek:
Traceback (most recent call last):
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\malna\OneDrive\Desktop\Kuze\main.py", line 40, in partnerek
await client.add_roles(member, role)
^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_roles'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'add_roles'```

red mist
wise parcel
#

thanks, but i want the solution.

steep cliff
#

Is it possible to add a field with no name to an embed? I don't just want it to be an empty string, as this adds an empty line to the embed, the field name shouldn't exists or not use up any space in the embed

elfin quarry
steep cliff
wise parcel
#

please someone can help?

steep cliff
#

The Bot object (in your case named client) doesn't have an add_roles method. You have to call the method on the member, as ramo told you to.

wise parcel
steep cliff
#

You will have to fetch the member, you can't just pass a string and expect it to work

#

?tag learnpython

limber wagonBOT
#

To be clear:

When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.

We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.

lapis dock
grizzled loom
#

Is there a way to have 2 embed fields inline=True and displayed next to each other accross the entire embed, without setting every third field to inline=False?

lapis dock
#

Dont think so

hallow copper
azure kettle
#

nvm I am dumb

red mist
#

Wait nvm im dumb

#

It's basically discord.Member.add_roles whereas discord.Member represents your member.

You indeed have to first fetch your member and then add the roles to them.

#

@wise parcel

winter jungle
#

Can someone help me?

opal hamlet
#

depends on the issue

lapis dock
#

Don't ask to ask please.

winter jungle
#

when member online channel renamed

#

with member id

opal hamlet
#

do you want the member id of whoever renamed a channel?

winter jungle
#

no

#

I want to change the channel name when a member goes online

opal hamlet
#

do you want a members online counter? or just for specific users?

winter jungle
opal hamlet
#

and then check if its user XYZ and update the channel

winter jungle
#

Thank you

opal hamlet
#

yo anyone got SQL server recommendations? wanna move away from SQLite

little cobalt
#

Why?

#

What is the problem with SQLite?

opal hamlet
#

i wanna do a noobgamer move and combine prod and dev DB

#

or rather my server and pc

little cobalt
#

I use a NoSQL one xd

opal hamlet
#

hmmm

little cobalt
#

I really like it to use MongoDB

shell radish
lapis dock
floral ice
#

lets say after some event i want to wait 2 min before doing something, what is the best way of doing this? just asyncio sleep?

little cobalt
#

time.sleep would block the entire bot for 2 minutes

#

you can try it out and see what will happend it you use time.sleep xd

floral ice
#

oh ok

#

it think i understand very basics of async

little cobalt
#

Do you also use something like requests? @floral ice

floral ice
#

httpx async

little cobalt
#

that is fine

boreal sky
#

Is there a way to limit what channels or users show up in channel or user selects?

lofty parcel
boreal sky
#

or is it just text if I opt for select

lofty parcel
#

Channel and user selects return an object

#

Normal selects are string selects

#

So internally you'd have to get the user

boreal sky
#

:/ that sucks

#

So, what do I do about a user picking an option I consider to be invalid?

#

Is there a way to reject a selection?

lofty parcel
#

How would it be invalid?

boreal sky
#

I have announcement channels and stuff and a command to move conversations between channels

lofty parcel
#

I'm assuming you're using channel selects then

boreal sky
#

yes

lofty parcel
#

Instead of manually filtering

#

Compare IDs to channels you don't want to

boreal sky
#

'cause I want to use channel/user selects but I would need to be able to disallow people from selecting certain IDs

boreal sky
#

I was hoping there'd be a way to customize the red error text that appears under selections sometimes

lofty parcel
#

What

#

The interaction failed message?

#

Why don't you just respond to the interaction with a message

#

"You are not allowed to select this channel"

boreal sky
boreal sky
lofty parcel
#

Why?

#

Just send the message

#

And allow them to try again

boreal sky
#

'cause I have to send a message to get the view in the first place lol

#

and you're only allowed one message

boreal sky
#

Is there a way to convert a User to a Member? I'm kinda amazed that Message.author doesn't return a Member for me o_O

lofty parcel
#

.rtfm guild.get_member

sly karmaBOT
boreal sky
#

I eventually figured it out... Turns out I was missing an intent O_o

#

but um... now I have a new problem

#

How does one disable a button using the @ui.button decorator?

maiden bloom
#

Why does discord.ActivityType.custom not actually display anything? How do I set a completely custom status without "Playing", "Streaming", "Watching", or "Listening"?

opal hamlet
#

Probably using something similar to a select menus: select.disabled =True

edgy nest
#

I do it like this and it works fine:

        await self.bot.change_presence(
            activity=discord.Activity(
                type=discord.ActivityType.custom,
                name="Custom Status",
                state=f"big balls",
            )
        )
opal hamlet
#

Huh interesting

late slate
#

Is it possible to have dynamic options in a @discord.ui.select decorator that's within an overloaded discord.ui.View that accepts options as an extra input value?

Example:

class CustomView(discord.ui.View):
    def __init__(self, options: list):
        super().__init__()
        self.options = options
    
    @discord.ui.select(
        placeholder = "Demo",
        min_values = 1,
        max_values = 1,
        options = self.options # issue is here, obviously
    )
    async def select_callback(self, select, interaction):
        # do stuff
opal hamlet
#

the callback needs placeholder options basically

#

and then just do in the init self.funcname.options = options

late slate
opal hamlet
#

too lazy to filter out unnecessary parts

#

unclean code that is in dire need of rewriting but

#

it works

#

do not comment on my var names

late slate
#

What line should I look at? (what does it start with?) I'm a little lost

opal hamlet
#

select needs an actual placeholder option inside the decorator

#

then just use self.funcname.options = whateveryouroptionvariscalled in the __init__

late slate
#

ohhhh... I do all this in the view init...

#

im dumb, thx 😅

opal hamlet
#

it took me a week of frustration to work that out, was a good way to learn OOP basics 😅

grim estuary
#

I need somewhere to store a large amount of data in dict format. Can I use Json for this?

opal hamlet
#

probably can, or just use an actual database

#

but i guess json might be the simplest

wild tartan
#

Is it normal for the bot to be disconnecting this often? My my bot seems to just die after 10 minutes and go offline with no error. The bot doesn't even do much other than listen to on_message.

rapid jackal
#

Is it possible to have a button without a label?

deft kestrel
#

hi, how to set custom rich presence (RPC) with images and buttons?

shadow junco
#

can autocomplete have defer?
cuz i have lots of data
and it needs sometime to generate

little cobalt
#

you dont need to defer the autocomplete and it also doesn't have it

shadow junco
little cobalt
#

what is the error?

shadow junco
#

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

cuz it wait too long

little cobalt
#

you have to defer the slash command

#

not the autocomplete

shadow junco
#

when the auto complete waited too long, it will shows the error

lapis dock
#

You should use a cache so you do not have to generate that many items every time. Also I think you need to rethink how your autocomplete works. There is no reason to generate a time stamp for ever minute for the next 100 days. You should wait until the user starts typing and then generate based off of the day or something. Then filter down the times. Autocomplete is not especially helpful if it just lists ever possible option when there are so many options. Another thing you could do is only suggest common times like XX:00 XX:30 XX:15 XX:45 and if the user needs to be more specific they can type it themselves.

grizzled loom
#

Take a look at the picture attached please.
I wanted a slash command to display "Tratos" but always got "tratos56..".

So far i tried ctx.user.name & .display_name
same with .member.name + .display_name

member.nick returns None.

using the 2.5something - almost stable but not exactly - pycord version

Edit: Please ping me or use the reply function when you answer

lapis dock
#

?tag pomelo

limber wagonBOT
#

Before Pomelo-

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo-

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
lapis dock
#

@grizzled loom You would want member.global_name or member.display_name

#

I see you already tried display_name not sure why that does not work

grizzled loom
shadow junco
lapis dock
#

just wait until autocomplete is called and use the text already inputed

shadow junco
#

ok

#
hw_subject = ctx.options["subject"]```
like this?
little cobalt
deft kestrel
shadow junco
deft kestrel
shadow junco
#

i only know how to add "invite button" to bot's profile

little cobalt
#

For what is rpc?

shadow junco
#

but i know how to add buttons to user's profile

shadow junco
tawny ether
#

quick question how to write unittests for discord bot?

#

how can i invoke a command like a user

lapis dock
floral ice
#

how can i use @is_user() or @has_role on slash commands?

opal hamlet
#

@commands.has_role('Role name') iirc

grizzled loom
#

Your advise was solid, my attemp too. the test bot was using an outdated pycord version. Big surprise it didn'd work as expected.

arctic plover
#

Hello!
Why does ctx.author.nick return None?

#

nvm

#

user doesn't have display_name on my server

#

why ._.

#

?tag pomelo

limber wagonBOT
#

Before Pomelo-

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo-

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
arctic plover
#

wth

lapis dock
# arctic plover wth

You need to be on master or the temp dev release in #library-updates
2.4.X does not have that feature yet.

bold creek
#

hello, does pycord support discord monetization? SKUs and entitlements?

shell radish
#

nope

floral ice
hallow copper
#

i thinks

floral ice
#

ok

hazy turret
#

Is there any way to use a decorator like has_any_role in a button class to check if the user who clicks the button has the appropriate role or do I have to check this manually once in the button?

class CloseButton(discord.ui.Button):
    def __init__(self):
        super().__init__(
            label="Close",
            custom_id="close",
            style=discord.ButtonStyle.red,
            emoji="🔒",
        )

    async def callback(self, interaction: discord.Interaction):
opal hamlet
#

does anyone have tips to make localization easier?

little cobalt
opal hamlet
#

Maybe just my format and way of doing it but its a tedious thing at times to just have to enter the file name, func names and then the var names as seperate entries in my json, and keeping track and organizing that can be quite annoying

#

Was just wondering if anyone with more experience got tips for some QOL

tawny ether
#

how do button role work after bot restart or something?

#

so there are two requirements for that timeout=None and custom_id

little cobalt
#

and add the view for listening

tawny ether
#

how does it work internally?

rugged lodgeBOT
#

Here's the persistent example.

tawny ether
#

will bot looks whether it has any view with that custom id

tawny ether
fallen cobalt
#

it it possible to use Google Speech To Text and Pycord's voice to output realtime transcriptions into a discord text channel?

tawny ether
#

i know how to do it

little cobalt
#

dont use something like ```py
view = discord.ui.View()

tawny ether
#

then when bot starts view is added with same config/parameters

tawny ether
#

so does bot checks for components with that custom_id?

#

sorry i am struggling to explain the question

lapis dock
#

Yes, if you use the same custom_id it will "find" the existing component with that ID

tawny ether
fallen cobalt
#

can someone answer my quick question about pycord’s voice?

lapis dock
tawny ether
#

oh okay so discord button in their side also have a custom id thing okay

lapis dock
tawny ether
#

thanks for answering, its crystal clear now

fallen cobalt
#

i have them working with each other just not realtime

lapis dock
#

I have no idea sorry, I have never done anything with voice.

fallen cobalt
tawny ether
#

i know that you can use, some libs to convert, but wont be that great

#

i think this is what i used

fallen cobalt
#

i know they have a streaming feature

tawny ether
#

oh i guess it is pycord side, sorry i have never worked with discord voice

fallen cobalt
#

it’s been a very long process with getting it to work

lapis dock
fallen cobalt
tawny ether
#

you can also check discord api, who knows whether it can help you

lapis dock
#

No one here is good at audio/voice :/ . And the person who is best is inactive due to school. It is overall an hard topic

fallen cobalt
#

my friend isn’t available to help either

#

and it was his idea so i’m kinda in the middle of trying to find out myself

fallen cobalt
lapis dock
#

It is possible you will need to look through the audio receiving code and make some changes yourself.

fallen cobalt
#

i’ll probably have my friend fork it and write something up for it

#

i haven’t had the best luck it’s been very aggravating to work with even though people make it look easy

#

but i did get it to work but it only updates when a user leaves / moves to a different channel not (realtime) :/

lapis dock
#

At least you are close.

fallen cobalt
# lapis dock At least you are close.

yeah i guess you can say that…. there must need to be some changes made to get it to where i want it in realtime. i’ve tried looking at other people’s code to get an idea of how they did it in realtime but there’s no luck

#

it’s hard to find people who are doing the same thing as what i’m trying to achieve

lapis dock
#

If you do find out how to to it you might consider making a short guide or something so others can follow you.

fallen cobalt
#

but that’s a good idea

#

i’ll definitely write one up for pycord, since it’s the only thing i could find that has anything to do with “voice”

tawny ether
#

when a slash command is invoked, ApplicationContext is send in callback, in that do discord send all data about guilds or users? or just id of user and guild?

cyan violet
#
@client.slash_command(guild_ids=servers, name="pillow_test")
async def pillow_test(ctx, member: discord.Member):
    if member is None:
        member = ctx.author

    img = Image.open("img/welcome.png")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("fonts/Hanson-Bold.ttf", 40)

    # Get image dimensions
    img_width, img_height = img.size

    # Get text size
    text = f"Willkommen {member.name}!"
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    # Calculate coordinates to center the text
    x = (img_width - text_width) / 2
    y = (img_height - text_height) / 2

    # Write Text on Image
    draw.text((x, y), text, (255, 255, 255), font=font, stroke_width=1, stroke_fill=(0, 234, 255))

    # Save Image
    img.save("welcome.png")

    # Send Welcome Image
    await ctx.respond(file=discord.File("welcome.png"))```
#

how can i make the text to gradient?
for example red and black or something

opal hamlet
# cyan violet how can i make the text to gradient? for example red and black or something

no clue directly, but i found this helpful LOOKING Stackoverflow thread https://stackoverflow.com/questions/63246100/how-to-draw-character-with-gradient-colors-using-pil

tawny ether
#

there is no color attribute for button?

opal hamlet
#

style iirc

#

not color

little cobalt
#

kinda

little cobalt
#

That is what discord got

tawny ether
#

😭

#

i was trying to make button_color_role

shell radish
#

select menus always exist

tawny ether
#

its also cool

red mist
#

You could also just use custom color emojis to put onto your buttons

#

or select menus ig.

tawny ether
#

can i use role_select and choose what roles should be shown there?

little cobalt
#

only with a custom select menu

tawny ether
fallen cobalt
#

does anyone here know anything about pycord voice and if it can handle realtime transcripts with google speech to text?

lofty parcel
minor crescent
#

anyone know why im having Unknown interaction errors even though im deferring every command

opal hamlet
#

is defer the first thing you do?

minor crescent
#

yep

opal hamlet
#

then i'm out of ideas without seeing sum code

minor crescent
#
@bot.slash_command(name = "find", description = "Find an item")
@option("item", description="Item to search for", autocomplete=get_items)
async def find(ctx, item: str, sorting_method: discord.Option(str, description="Method for sorting results", choices=['price', 'scan time']), accessibility: discord.Option(str, description="Whether you can access the vending machine or not (or both)", choices=['path', 'no path', 'all']), min_price = discord.Option(int, description="Minimum price for an item (optional)", default = -999), max_price = discord.Option(int, description="Maximum price for an item (optional)", default=999999999999999)):
    await ctx.defer()
    con.cmd_refresh(1)
    if check_user_int_role(ctx.user.id) >= roles["Per Search"] or check_user_int_role(ctx.user.id) == roles["Trial"] or ctx.user.id in admins:
        # MORE CODE HERE
                paginator = pages.Paginator(pages=embed_pages, custom_view=ExportView())
                await paginator.respond(ctx.interaction, ephemeral=False)
        else:
            embed = discord.Embed(title=f"Arcturus by asleepdream - Results for {item}", description=f"There were no results found for this item. Please try again later.", color=discord.Color.red())
            await ctx.respond(embed=embed.set_footer(text="Credits to Nexica for the idea and bot layout"))
    
    else:
        await ctx.respond(perms_message("use this command", "Per Search+", ctx.user.id), ephemeral=True)
#

@opal hamlet no clue what it could be 💀

#

its not on every command usage either

shell radish
#

what is con.cmd_refresh(1)?

minor crescent
#

mysql connection refresh

#

to get new data

fickle salmon
#

are you using an async mysql driver?

minor crescent
#

im just using mysql.connector

shell radish
#

I think that'll be the issue

minor crescent
shell radish
minor crescent
#

oh true

#

thats 100% the issue

#

anyone have suggestions for async

shell radish
#

i don't use mysql

minor crescent
#

sad ok

#

this gonna be pain to fix

shell radish
#

you either write good code the first time, or it grows big enough until it becomes an issue

minor crescent
#

it grew big enough to be an issue

fickle salmon
#

I suggest sqlalchemy

#

or I guess aiomysql if you don't want to rewrite your whole bot

minor crescent
#

yeah i'd prefer not to

opal hamlet
#

just to make you realize you wasted your time, now suffer /j

gentle musk
#

Hey, sorry if the question is dumb, but when I simply copy the code out of the pycord doc, it won't work.

This doc (https://guide.pycord.dev/interactions/application-commands/slash-commands)
When I copy the first code, it will say this:

Traceback (most recent call last):
File "C:\Users\nonoelmo\PycharmProjects\PolyBot\main.py", line 3, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'

Can anyone help?

Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!

opal hamlet
#

?tag py-cordnotpycord

limber wagonBOT
#

dynoError No tag py-cordnotpycord found.

opal hamlet
#

?tags

shell radish
#

you're not using pycord

limber wagonBOT
#
Tags (117)

yt-tutorials, youtube, xy, wavelink, virtualembed, usernames, usercmd, update, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, this, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, slashblog, rie, restartcmd, requests, replit-install, replit, removeall, pythonversion, pythonserver, python, practices, pp, pomelo, persistant_view, paste, partial_objects, oracle, option, oop, om, official, objects, notpycord, norepl, nojson, nohelp, nohello, no_status, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, logging, localfile, learnpython, json, intents, install_slash, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, git, getalpha, get_x, get-help, gather, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, cmd-limits, closing, client, chatgpt, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, 429

opal hamlet
#

?tag notpycord

limber wagonBOT
#

The official name of the library is py-cord. When installing the library use py-cord, pycord (without the hyphen) is a completely different package.

opal hamlet
#

this?

gentle musk
#

okay

shell radish
#

what IDE are you using?

gentle musk
#

PyCharm

shell radish
#

what is your list of python packages

gentle musk
#

idk sorry I'm new

shell radish
#

there's a button called "python packages" or "packages"

#

somewhere on the left bottom corner ish

gentle musk
#

idk whyy so much and where they come from

shell radish
gentle musk
#

I thought Pycord i smth like an extension

#

sorry i'm a complete beginner

shell radish
#

no, pycord is a different library

gentle musk
#

i think pycord

shell radish
#

so you uninstall discord.py, discord, then uninstall and reinstall py-cord

opal hamlet
#

py-cord* important to note

gentle musk
#

and then i import py-cord and not discord

opal hamlet
#

no still import discord

#

just pip install py-cord

arctic plover
#

How can i get user`s DM channel id?

#

or maybe create_dm() method returns the ID of an already existing channel, if there is one

#

?

shell radish
arctic plover
#

ty

#

didnt see this attribute here ._.

#

im blind

shell radish
#

hi blind, I'm squid

arctic plover
#

nice to meet you

arctic plover
shell radish
arctic plover
#

nah, if DM already exists

#

what happens if i use create_dm() again

shell radish
shell radish
arctic plover
fickle salmon
#

It creates a black hole and destroys discord, be very careful

arctic plover
fickle salmon
#

Just use dm_channel

arctic plover
lofty parcel
#

then create it if its none

#

its not that hard to make a small check lol

proud lynx
#

Alright, question.

arctic plover
proud lynx
#

Select.callback seems to be triggered only when the number of selected values falls within min and max values. How do I get it to be triggered the rest of the time, too?

arctic plover
lofty parcel
#

it should get triggered on min and max too

proud lynx
proud lynx
#

Here, look.

#

Hold on, give me a minute, I'll show you.

lofty parcel
#

well it wont

#

if you set a max, you cant select more than the max

proud lynx
#

Except that you can.

#

It'll just bitch about how you can only select 2.

#

But it won't actually stop you from selecting more.

lofty parcel
#

so your max is 2

proud lynx
#

So, the Submit button gets refreshed when the number of values selected falls within acceptable limits (in this case, 0 -> 2).

#

Correct.

#

But it allows me to select more than that, and when that happens, Select.callback is not triggered.

#

And therefor, Submit does not refresh.

lofty parcel
#

hm

#

@shell radish

proud lynx
#

Let me say, I don't have an opinion on whether or not Select "should" allow you to select more options than the max.

#

The two fixes, as I see it, are:

  • Call Select.callback on any modification of Select.values
  • Disallow selection of new Values after hitting the max.
#

Either way would fix this, and it doesn't even need to be a library update.

#

I'll just throw in whatever into my local copy of Pycord.

#

Whatevah.

#

Or maybe some third option! Maybe a bool that gets passed to the Callback named "valid" that tells you if the currently passed-in options are within parameters, if you can't stop the user from passing in invalid ones.

#

Who knows.

lofty parcel
#

i thought discord would just restrict you from selecting more options

proud lynx
#

Maybe.

#

Actually, let's do some investigation.

#

Maybe it does, on other Selects. Let me try on string selects.

proud lynx
#

...But only in String selects.

lofty parcel
#

no way

#

lmao

#

well thats a thing

proud lynx
#

With Channel, it will simply chide you for breaking the rules :(

#

Please don't select 3 :((

#

Now, I know String selects play under totally different rules than the other ones.

#

But is it possible to modify this behavior to bring them in line with String select in this case?

#

Could it be some oversight in the library versus a limitation with Discord?

lofty parcel
#

i would just handle the limits internally

#

or on interaction_check

arctic plover
#

Why am I getting this error? I can send messages to this user, they are even sent, but the error is still there

discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user

proud lynx
lofty parcel
#

wdym

#

interaction_check is a func in the view class

#

generally used to check authors

proud lynx
#

Is. That. So.

#

Perfect.

#

Then I'll just rewire my logic to trigger on that, instead of on callback.

proud lynx
#

So it's not that it's screening it out from reaching Select.callback, it simply isn't receiving the interaction at all, TO send it to the Select.

lofty parcel
#

remova the max

#

do the checks by yourself

proud lynx
#

I guess that's all that's left.

slender lantern
#

There's the @default_permissions(...) decorator. Is there one that lets me specify a role instead?

minor crescent
slender lantern
#

Drat

#

Thanks

lapis dock
# slender lantern Drat

The idea is that the server admin specifies a role in the integration settings so that the bot does not have to check for it.

There is commands.has_role however this is an internal check, so a user will still see the command even if they do not have the role (unlike when a server admine uses integration settings)

slender lantern
#

Yeah, I’m aware of that option and limitation. My users have slightly more complex needs than the Discord permissions system. Oh, well!

#

My solution should still work fine

#

Thanks

fallen cobalt
minor crescent
#

im having weird errors when i switched to aiomysql

Task was destroyed but it is pending!
task: <Task pending name='pycord: on_interaction' coro=<Client._run_event() done, defined at C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:370> wait_for=<Future 
pending cb=[Task.task_wakeup()]>>
Ignoring exception in command find:
Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
RuntimeError: coroutine ignored GeneratorExit

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: RuntimeError: coroutine ignored GeneratorExit
rugged lodgeBOT
minor crescent
#

my command code

tawny ether
solid turtle
#

i can't seem to accept attachments in slash commands, someone show me an example, can't find it in the pycord docs

little cobalt
solid turtle
#

oh

solid turtle
#

attached by the user

#

just file?

#

nvm i kinda got it working

arctic plover
#

I cant run my application ._.

#

When I launched it, it worked as if I had launched it somewhere else

#

So I reset the token

#

and now cant run it

#

discord.errors.LoginFailure: Improper token has been passed.

#

how to fix it

#

oh

#

u just cant run any application

#

i can run it on website

#

but cant run it local

#

ima try to reinstall pycord

#

still doesnt work

#

but i can run it in default python console

#

but not in pycharm

#

this code was working just yesterday

#

what happened meanwhile i was sleeping lol

tidal estuary
#
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.type == discord.MessageType.stage_raise_hand

I assumed this would fire on some kind of invisible system message that was created when someone raised their hand, but this is not the case. Any clue what I can do to hook the "user raises hand" event?

little cobalt
tidal estuary
arctic plover
#

does py-cord support python 3.12?

little cobalt
#

I use currently 3.11 and there are many librarys who are still not working with 3.11

little cobalt
arctic plover
#

or 3.11.5

#

cause 3.11.6`s realese date is same with 3.12

little cobalt
#

11.6 should be fine

tawny ether
#

how do i choose only some specific intents i need?

arctic plover
#

like this

tawny ether
#

thanks i was using + 🤦

arctic plover
#

if u need all default intents

tawny ether
#

for now i am only enabling those intents which i need

little cobalt
#

I would do ```py
intents = discord.Intents()
intent.message_context=True

deft kestrel
#

Guys, help. I'm trying to make a music bot, but there is one problem with FFmpeg
The point is that I use Replit for writing code, including running the bot, and I also do everything from my phone, but as I understand it, I need to download FFmpeg , what should I do?

deft kestrel
opal hamlet
#

I think you can use python-ffmpeg or shit which you can install via pip, i assume replit allows that as you can use py-cord (never used replit, so dunno)

lapis dock
tawny ether
#

oh okay

grim estuary
#

An Unknown interaction error occurred in await ctx.defer(). How is this possible?

little cobalt
#

Error at the code?

tawny ether
#

is it because he replied to that?

solid turtle
#

quick question, how can I integrate autocomplete with options? for example, in autocomplete, i have type 1, type 2 and custom as the options. if the user chooses custom, the user should be able to type in whatever they want.

#

is that even possible in pycord, i tried a lot

grim estuary
grim estuary
minor crescent
#

Task was destroyed but it is pending!
task: <Task pending name='pycord: on_interaction' coro=<Client._run_event() running at C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:378> wait_for=<Future pending cb=[Task.task_wakeup()]>>

im getting random console logged errors like this

minor crescent
#

check if you have anything that blocks

little cobalt
grim estuary
opal hamlet
#

So there are obv. The @commands.has_permission(administrator=True) and @commands.is_owner decorators for slash commands, but can i make it so that it is for server admin OR bot owner

arctic plover
#

Sorry for the misunderstanding. If you want to use the name variable inside the class, but outside of any function or method, you can do this If you want the name name it, creating at variable by creating an at to be available inside the class. Here's how to do it:

python
Copy code

class MyClass:
    def __init__(self, name):
        self.name = name

# Creating a class object and passing the name
my_object = MyClass("Name")

# Access to the name variable inside the class, inside the class, outside the function or method
aprint, but outside(my_object any.name )

In this case, the variable nameb becomesyao functribute of the class and can bee, you can define it as atri accessibble insi the classout,ri and not the class aat inidse the functiobut eik eliz methodovem.p

#

Chat gpt, what`s wrong with you lol

#

so guys

#

how can i transfer any parameters in button? when u subclassing discord.ui.View, u must write buttons via decorator, but u dont have access to self in main of class

#

for example:

class MyView(discord.ui.View):
    def __init__(self, button_label):
        self.button_label = button_label
    
    @discord.ui.button(label=??button_label??, style=discord.ButtonStyle.blurple)
    async def callback(self, button, interaction):
        await interaction.response.send_message('hello')
little cobalt
#

why do you create a new button in it

shell radish
arctic plover
#

i mean discord.ui.View

arctic plover
#

so how to do it?

shell radish
#

create a discord.ui.Button object or subclass discord.ui.Button

arctic plover
#

okay

shell radish
#

the first one

#

creating a discord.ui.Button object

tepid coyote
#

what are the reasons a slash command isnt appearing?

rough flame
#

Hi, please tell me why I cant get the global nickname of a participant when he connects to the server?
Instead of a nickname, it gives username(@username) or None. =((

little cobalt
rough flame
opal hamlet
#
self.clear_msgs.name_localizations = {locale: Localization(locale).clear_msgs.command_name for locale in locales}
        self.clear_msgs.description_localizations = {locale: Localization(locale).clear_msgs.command_desc for locale in locales}```so i am (successfully) using this to localize my command name and descriptions, but how can i localize command Options such as amount ```py
async def clear_msgs(self, ctx:discord.ApplicationContext, amount: Option(int, description='The maximum amount of messages to clear.')):```
#

should i just declare a variable for it in my __init__ instead and just using that in the Option()

little cobalt
opal hamlet
#

well never used that decorator, gotta ReadTheDocs but still, how would i acess that then? self.clear_msgs.option('amount').name_localization or smth?

solid turtle
#

i can't seem to figure it out

opal hamlet
little cobalt
opal hamlet
#

A total of 100 refreshs for all commands or 100 commands that can be synced, but more than 100 times a day

opal hamlet
#

Because well, durinf testing i kinda need a few syncs 😅

little cobalt
#

Im not 100% sure if you sync the commands that they would send a new api call for the command

opal hamlet
#

Well maybe i should just override the on_connect command sync to disable it

#

And just do it manually

#

Atleast the localization is working (thanks bing)

solid turtle
#

like if the user chooses the custom option, they should be able to type in whatever they wnt

#

want

#

i need like an example or something

lapis dock
rugged lodgeBOT
#

Here's the modal dialogs example.

solid turtle
#

🤔

solid turtle
lapis dock
#

As in another option, No. Slash command options are static. You could add an custom_text option and just ignore it unless custom was selected

solid turtle
lapis dock
#

Just add another discord.Option
Then do
if type_choice == "custom": type_choice = custom_text

solid turtle
#

wait what is type_choice

#

oh nvm mb

#

got iti

#

tysm

round heart
#

Can you decorate the same method with multiple listeners, e.g.

@commands.Cog.listener(name='on_member_update')
@commands.Cog.listener(name='on_user_update')
async def member_change(self, old_member, new_member):
  ...

or what's the best way to capture all user modifications? I can't tell whether something with the username system is causing me to miss some events, or what, but some banned names are getting through and I can't tell how.

hazy turret
#

Can I make a paginator responsive without adding a custom view and custom buttons to the paginator ?

class PaginatorView(Paginator):
    def __init__(self, bot: discord.Bot, card_info):
        self.bot = bot
        self.pages = self.create_pages(cards_info)

        super().__init__(
            pages=self.pages,
            use_default_buttons=True,
            timeout=None,
            author_check=False,
        )
arctic plover
#

how to get thing like this?

#

so if u just use await ctx.respond(attachment)

#

u get this:

shell radish
#

you can use the file or files kw-argument

arctic plover
#

and then send

#

right?

shell radish
#

I don't know the nature of your file so maybe?

arctic plover
#

i cant do it with url only? like file = discord.File(url)

devout mirage
floral ice
#

is it possible to create custom conditions for slash command to be visible?

shell radish
#

no

floral ice
shell radish
floral ice
shell radish
#

yes, it just involves oauth2

#

simple if you've done it before, tad complicated if not

floral ice
arctic plover
stray pasture
#

Do you need to use ConnectionPools with pycord ? If I use normal connection for a mysql database, I get Internal errors with sequences number of packages. From what I am seing, it can happen with multiple threads and the solutions is a connection pool. But I though with asyncio, there was only 1 thread that is switching between task ?

austere moth
#

is it possible to pass a data value like attrs below to discord.Interaction using discord.SelectOption?
I wanted to update the embed showed in a discord.ui.View using said SelectOption but the data class is local or inside discord.ui.View class

@define
class Values:
  id: str
  name: str
  ...
lofty parcel
lofty parcel
austere moth
dawn prism
#

Hello everyone !
I have a quick question, do you know any ways or library that could help to do automated tests.unit tests for pycord bot ?

I found some but they are meant for dpy :/

#

The biggest issue is that most of my commands call a database and sends embeds so i don't really know how to ensure the results are correct

opal hamlet
#

whats the command for the persistent view example again

opal hamlet
#

wasn't there a command tho, but thanks

little cobalt
#

yea but I cannot see the slash commands

opal hamlet
#

god im fucking stupid i don't even need that rn ... an embed isn't a view

little cobalt
opal hamlet
#

yeah that's why i asked heh

fiery stratus
#

make it so the only way to change the variable is through a function, then add whatever functionality you want to that function

autumn gust
#

and it sendsto the bot, and sends to a predetermined channel

fiery stratus
#

wdym seperate window

#

like still in discord or another application?

elfin quarry
#

like an InputText Modal?

fiery stratus
#

this may help you

autumn gust
#

input in 1 window, bot processes it, and sends a message to discord

fiery stratus
#

what is the "input" application?

#

is it like a command line or smthn

autumn gust
#

so

#

terminal.py -> main.py -> discord

fiery stratus
#

hmm

autumn gust
#

preferably without bot restarts yk

fiery stratus
#

terminal.py can just be a basic terminal application where it constantly asks for an input

lofty parcel
autumn gust
#
while True:
  variable = input("> ")
fiery stratus
#

you could make a function in your bot that receives a message and just sends it to a channel

#
import bot

while True:
  variable = input("> ")
  bot.sendMessage(variable, channel)
autumn gust
#

that's pseudo code, right?

fiery stratus
#

yeah

autumn gust
#

hm

#

but the thing is

#

how to make it async?

austere moth
fiery stratus
autumn gust
#

no?

fiery stratus
#

at least i dont think so

lofty parcel
fiery stratus
#
# terminal.py
import bot

while True:
  variable = input("> ")
  await bot.sendMessage(variable, channel)
# bot.py
import discord
import utils

async def sendMessage(self, message: str, channelID: int):
  channel: discord.Channel = utils.get_or_fetch(self.bot, "channel", channelID)
  channel.send(message)
#

something like this @autumn gust

lofty parcel
autumn gust
#

god I forgot about it and it made me wheeze

austere moth
fiery stratus
#
# bot.py
import discord
import utils
import asyncio

bot = discord.Bot()
channelID = 0

async def terminal():
  async def sendMessage(message: str):
    channel: discord.Channel = await utils.get_or_fetch(bot, "channel", channelID)
    await channel.send(message)

  while True:
    message = input("> ")
    await sendMessage(message)

asyncio.run(terminal)
bot.run(os.getenv("TOKEN"))
#

@autumn gust

#

try this idk

austere plank
#

Is it possible to end a users stream?

red mist
#

Im not sure if this is possible but; You could try to move them to a channel which doesn't allow users to stream (in which case their stream might be ended?) and then you move them back to the channel while them not streaming anymore.

edgy nest
#

if you move them at all the stream will end

red mist
#

Oh-

minor crescent
#

how can I allow command usage in DMs

opal hamlet
#

Does it even need to be allowed?

#

Doesn't it work by default unless you set them to guild only

arctic plover
#

Unless you use a decorator guild_only

dawn prism
#

Hi !
I would like to know if it's possible to interfer between a ctx.respond(...) and the moment its completely sent to discord in order to check the values ?
I would like to avoid any package modification and if possible to stop the sending

shadow junco
#

Hello
Can I use folders to create command groups, and the python files in it are commands
for example:
if i have three folders:

I want it to be like this
/admin ban
/admin kick
/music play
...

thank you

opal hamlet
lapis dock
#

It would not work be default with folders. You would still need to create the group and add the commands.

opal hamlet
#

used f.e. like this

lapis dock
lofty hedge
#

after i unlaod cogs, im trying to make sure you cant run any of the commands,

    async def cog_before_invoke(self, ctx):
        cog_name = ctx.cog.__class__.__name__
        print(f"Checking if {cog_name} is in {self.bot.loaded_cogs}")  # Debug print

        if any(loaded_cog.lower().endswith(cog_name.lower()) for loaded_cog in self.bot.loaded_cogs):

            return True
        else:
            await ctx.respond(f"The cog {cog_name} is currently disabled.")
            raise CogDisabledException(f"The cog {cog_name} is currently disabled.")```1
#

idk whats wrong with the formattign, but, im unsure how to achieve this, ive been trying the cog_before_invoke, but the whole issue is the only way ive managed to get it not to try to invoke the command is by using raise, but then teh issue is, it prints out to my terminal the error which i dont want it to

#
class CogDisabledException(Exception):
    pass

lofty hedge
#

im so lost on how to achieve this

rancid arrow
rancid arrow
#

Actually I think that would just continue execution because the exception is caught

#

Maybe you can try adding a on_command_error, check if it’s the disabled error, then handling it accordingly

maiden bloom
#

How can I make a message ephemeral when using interaction.followup.send()?

little cobalt
maiden bloom
#

So the first message has to be ephemeral?

lofty parcel
#

Just pass ephemeral=True

shell radish
maiden bloom
#

I was looking for that in this documentation but didn't see it. Unless I'm looking in the wrong place

#

So I can't have a non ephemeral defer with an ephemeral followup?

shell radish
#

yes

maiden bloom
#

Damn. Honestly these should all be ephemeral anyway lol

placid shard
#

do views inherit the params that the slash command has?

#

for example : if i have a slash command with a users id could i use it for a button response?

placid shard
#

just to show a pinged users name

#

is there any way i could include this in the view

shell radish
#

if you know how classes work, that should be simple

lofty parcel
#

Welcome to basic OOP

placid shard
#

i mean ive learned oop but its a param

#

so im lowkey confused

lofty parcel
#

So what?

#

Its still a variable.

#

You just pass it to the view which you previously defined with the appropriate init

shell radish
lofty parcel
#

Argument deez nuts

shell radish
#

?

red mist
#

I thought I sent a gif in here

#

How Jesus- my brain is having an error.

little cobalt
red mist
rapid jackal
#

Can my button label contain alt+0160 ? It's the windows invisible letter

deft kestrel
#

.rtfm message.channel_men

deft kestrel
#

hmm

young pelican
#

So I have a bot and it can take messages if u dm it, but if u message in a server it logs the channel and the username but not the message content and I am so confused

#
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)

this is how I extract the information and like I say it works in dms perfectly but in servers it doesn't seem to get the message.content correctly

#

it just saves user_message as , nothing

#

no matter what the message is and no matter where it is

#

the bot has administrator permissions and access to all the channels so its not something to do with roles or permissions

lofty parcel
#

?tag intents

limber wagonBOT
#

Pycord Docs - Intents
Discord API Docs - Gateway Intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
minor crescent
#

how can I allow commands in dms? i was told before they work by default but I can’t use any commands from my bot. Maybe it’s because I defined servers in the code?

young pelican
lofty parcel
young pelican
#

yep

lofty parcel
#

Show your code

young pelican
#
# Discord bot

import random
import discord

"""
Invite Link = 
Token = 
"""

intents = discord.Intents.default()

async def send_message(message, user_message, is_private):
    try:
        response = handle_response(user_message)

        if response:
            await message.author.send(response) if is_private else await message.channel.send(response)
        else:
            print("Empty message?")

    except Exception as e:
        print(e)

def run_discord_bot():
    TOKEN = ''
    client = discord.Client(intents=intents)

    @client.event
    async def on_ready():
        print(f'{client.user} is now running')

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return
        
        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        await send_message(message, user_message, is_private=False)
    

        print(f"{username} said {user_message} in {channel}")

    client.run(TOKEN)

def handle_response(message) -> str:
    p_message = message.lower()

    if p_message == 'hello':
        return 'Hey there'

    if p_message == 'roll':
        return str(random.randint(1,6))

run_discord_bot()

The token is there in the actual code, I just removed it cause yk

grizzled loom
#

default() alone won't do

young pelican
clear aurora
young pelican
#

sliders?

#

this is the error

Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
grizzled loom
#

there, those sliders

#

thats were you manage privileged intents

young pelican
# grizzled loom

How do you get to that page, im sorry for asking all these questions

grizzled loom
#

You know where you made the invitation link for your bot?

#

there is a menu on the left named "bot"

#

that's were you find the sliders

young pelican
#

I knew I saw it before ty

grizzled loom
young pelican
#

Its just for my friends server

#

so not public

grizzled loom
#

good. In this case there should be no worries about the intent settings in the long run.

young pelican
#

tysm

frail basin
#

is it just me or @commands.has_role is bugged in Cogs?

opal hamlet
#

Maybe you gotta use Cog.has_role

#

Unsure tho

#

Usually just ctrl c, v

frail basin
#

command: (in a cog)

@commands.slash_command(name="ghostping", guild=guild, description="Ghostpings the user.")
    @commands.has_role(item=admin_id)
    async def test(self, ctx: discord.ApplicationContext, user: discord.SlashCommandOptionType.user):
        await ctx.defer(ephemeral=True)
        await ctx.interaction.response.send_message(content=user.mention, delete_after=0.3)

Error:
Role '' is required to run this command.

frail basin
#

as per the docs, commands.errors.MissingRole.missing_role should return the role that is missing

little cobalt
#

you could just do e.missing_role.mention

frail basin
#

true

#

ill try that

#

but thats not the issue, it shouldnt even throw the error

little cobalt
#

than you dont need the <@&> stuff

frail basin
#

as i have that role

#

@little cobalt so turns out i was using <@&> because it doesnt return a role

#

but the id of the role

#

and it also asks for the role

#

could it be that has_role(id) just tries getting the role from cache?

#

and because it doesnt find it, returns None

little cobalt
#

?tag get_x

limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

frail basin
#

it doesnt have the role in cache

little cobalt
#

ye

frail basin
#

but @commands.has_role might try getting the role by the id from the cache

#

@commands.is_owner() works as intended

frail basin
#

seems like it was an issue on my end

vocal yoke
#

i have a function that has to get awaited. but its called inside of a @bot.command. and that causes alot of errors.


discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: asyncio.run() cannot be called from a running event loop
echo wraith
#

Hello there. Is there a way to make an ui.Select component narrower? In order to fit 2 in one row? I guess not but just wanted a confirmation.

echo wraith
vocal yoke
# echo wraith could you send a code snippet?

async def getreply(message):
    from g4f.Provider import (
        AItianhu,
        Acytoo,
        Aichat,
        Ails,
        Bard,
        Bing,
        ChatgptAi,
        H2o,
        HuggingChat,
        OpenAssistant,
        OpenaiChat,
        Raycast,
        Theb,
        Vercel,
        You,
        Yqcloud,
    )
    response = await g4f.ChatCompletion.create(
        model="gpt-3.5-turbo",
        provider=Aichat,
        messages=[{"role": "Admin", "content": f"{message}"}],
    )  # alterative model setting

    print(f"SUPPORT TEAM: {response}") 
    return(response)

@bot.command()
async def request(ctx,*,helpx):

    response = await getreply(prompft)
    await ctx.reply(response, mention_author=False)  
minor crescent
little cobalt
minor crescent
shadow junco
#

can i get a user's discord language while he use a slash command?

little cobalt
#

ctx.interaction.locale

shadow junco
#

oh

#

thank you

placid shard
#

is there anyway to put a task.loop on a button

#

when i add it the button disappears

red mist
shell radish
red mist
#

Fk off 😂

torpid cosmos
#

gatekeeping

leaden hornet
#

Hi, is there a way to update custom view in Paginator after switch the page?

clear aurora
hybrid tinsel
#

what's the issue here?
"discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 40067): A tag is required to create a forum post in this channel"

@bot.command()
async def thread(ctx):
    forumChannel = await bot.fetch_channel(CHANNEL_ID)
    await forumChannel.create_thread("test", content = "test")

how do I add a tag?

heavy sky
#

You can use applied_tags

hybrid tinsel
#

how do i get the tag ids of a forum?

heavy sky
grizzled loom
#

can someone have a look my thread #1162830037758783588 ?

hybrid tinsel
#

looking through chat history honestly really painful so i hope that putting my solution here helps some poor soul LOL

hybrid tinsel
#

how do i send a message to a thread given its id?

#
        thread_id = applicant[0].thread_id
        #send message to thread
        forumChannel = await bot.fetch_channel(FORUMCHANNEL_ID)
        thread = forumChannel.get_thread(thread_id)
        await thread.send(f"{ctx.author.name}: {ctx.content}")

gives me a AttributeError: 'NoneType' object has no attribute 'send'

#

thread_id is outputting the correct integer of the thread

#

ah nevermind i answered my own question

#

checked the type and it was a string welp

solemn finch
#

Is a autocomplete like the one YAGPDB bot uses possible with Pycord and what do I need to do to add it to my slash commands?

lofty parcel
solemn finch
#

okay, what do I need to use it, I have been banging my head with autocomplete so this revelation is great

lofty parcel
#
async def my_command(ctx, user: discord.Member):```
solemn finch
#

Okay cool, thanks for help Dark

leaden hornet
#

hello, how get pages.Paginator in custom_view? This code doesn't working

paginator = pages.Paginator(pages=pagess, disable_on_timeout=True, timeout=30,author_check=True )
paginator.custom_view = GoToPage(pag=paginator)
class GoToPage(ui.View):
    def __init__(self, pag):
        self.pag = pag
    @discord.ui.button(label='page')
    async def page_to(self, button, interaction):
        await self.pag.goto_page(10)
#

it returns AttributeError: 'GoToPage' object has no attribute 'children'

floral ice
#

after creating a button after some time it stops working even if the bot has been running the whole time

floral ice
#

thanks

#

is it just timeout=None

#

?

little cobalt
#

View class and add_view

floral ice
#

i have custom view class

#

do i just put timeout=None to super().init ?

floral ice
little cobalt
#

you have to use a view class

floral ice
#

i do

#

i have custom view class

#

i added timeout=None

little cobalt
floral ice
#

yea i added this

#

im adding add_view now

#

how do i remove it?

#

after i want it to end

#

just delete the msg?

#

or view

little cobalt
#

what?

floral ice
#

add_view Registers a View for persistent listening right?

little cobalt
#

yes

floral ice
#

how do i stop it at the end

#

i have like END button on the view

little cobalt
#

after pressing the button?

floral ice
#

im clicking the buttons multiple times

#

i need it to be able to respond after some time

little cobalt
#

like time.sleep?

#

@floral ice

floral ice
#

i made a poll system

#

the buttons need to be able to be pressed for a longer time

little cobalt
#

you could increase the timeout time of the button

#

but they are not gonna work after a restart then

floral ice
#

thats ok

little cobalt
#

timeout=the seconds

floral ice
little cobalt
#

you could create your own "handler" for the time which would disable the stuff

deft kestrel
#

How could you check if a channel exists in your discord server?

lofty parcel
sly karmaBOT
deft kestrel
#

how to set slash commands?

shell radish
deft kestrel
shell radish
#

you can check out the guide for basic information

deft kestrel
#

like that

shell radish
#

?tag guide

limber wagonBOT
deft kestrel
shell radish
deft kestrel
deft kestrel
little cobalt
#

did you set any guild id?

deft kestrel
little cobalt
#

can you press ctrl + r for a client refresh

deft kestrel
#

`import discord
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.command(description="Sends the bot's latency.") # this decorator makes a slash command
async def ping(ctx): # a slash command will be created with the name "ping"
await ctx.respond(f"Pong! Latency is {bot.latency}")

bot.run(mytoken)`

little cobalt
#

oh

#

you have commands.Bot

shell radish
#

if you are using commands.Bot, you would use @bot.slash_command() instead

little cobalt
#

change it to discord.Bot or change it to bot.slash_command

deft kestrel
little cobalt
#

can you show the pip list?