#Basic Pycord Help

1 messages · Page 36 of 1

errant trout
quartz umbra
#

Yeah i understand, smth = await TextChannel.webhooks()

errant trout
#

well sure let's go with that

quartz umbra
fresh sierra
errant trout
#

my general point is by fetching guild.webhooks, you don't have to fetch channel webhooks every time

quartz umbra
quartz umbra
fresh sierra
errant trout
#

it's just better to be conservative with fetching resources

#

also note other bots may have created webhooks for any reason, so you need to validate what webhook it is

quartz umbra
errant trout
#

thus check webhook.user

#

eh fair

quartz umbra
errant trout
#

probably

quartz umbra
#

alright, thanks a lot for your help!

errant trout
#

that gets the bot's member in that guild

fresh sierra
#

you can check the id

quartz umbra
#

I guess I'll try both and debug

fresh sierra
#

then ur sure

#

good luck with ur project

quartz umbra
#

thx, its a yap bot

deft kestrel
#

user = guild.get_member(user_id_)
if user:
await channel.set_permissions(user, read_messages=True, view_channel=True)
return True

#

How can I make it so the next message which contains the user ID allows the user id to see the private channel

sage tendon
#

you can use bot.wait_for()

#

to wait for messages etc

deft kestrel
sage tendon
#

oh
well, check the docs on how to use that method

#

.rtfm TextChannel.set_permissions

sly karmaBOT
deft kestrel
#

.rtfm discord.Member

sage tendon
#

just use the doc search

deft kestrel
#

do i have to convert user id to member smtn

sage tendon
#

you already have the member object

sage tendon
deft kestrel
#

it does

#

but it isn’t grabbing..?

#

do i have to split string from the acciqured message?

#

i sent it to full int

deft kestrel
#

and i don’t know why

sage tendon
#

the get member function takes ONLY a user ID, as an int, and also needs the member to be cached, but that's usually the case

deft kestrel
#

how to cached a user

sage tendon
#

"but that's usually the case"

#

it would help if you showed more of your code

pine venture
#

Hi, with pycord, does the channel.history feature have a way to search by specific message? Because reading the docs, I dont see how

sage tendon
#

like by content? it's just a list if you do .flatten, so just search whatever you want with it

deft kestrel
#

async def AddingPromot(user_id, channel, channel_hashes_step):
                                success_color = 0x00ff00
                                error_color = 0xff0000

                                if await set_permissions(user_id, channel):
                                    user = client.get_user(int(user_id))
                                    if user:
                                        message = f"{user.mention}, you have been granted access to this channel."
                                        status = "Success"
                                        next_step = 2
                                    else:
                                        message = "User not found."
                                        status = "Error"
                                        next_step = None
                                else:
                                    message = "Unable to grant access to the specified user ID."
                                    status = "Error"
                                    next_step = None

                                embed = discord.Embed(title="Igris : Step 1", description=message, color=success_color if status == "Success" else error_color)
                                embed.set_author(name=f"Status: {status}")
                                await channel.send(embed=embed)
pine venture
sage tendon
#

yea I'll have to look at it when I'm home, or someone else in that time

sage tendon
pine venture
#

ok thx

#

Huh though it returns incorrect amounts

#
                    amount = 0
                    async for msg in treelist:
                        if "33" in msg.content:
                            amount += 1
                    await message.channel.send("33 has been said "+str(amount)+" times in this channel")```
snow crescent
#

Hello, I've searched and search here and on the web but I'm having problems applying a tag to a newly created thread

                        workshopTag = discord.ForumTag(name="workshop", emoji=discord.PartialEmoji.from_str(":name:123"), moderated=False)
                        mapTag = discord.ForumTag(name="map", emoji=discord.PartialEmoji.from_str(":name:123"), moderated=False)

                        thread = await forum_channel.create_thread(
                            name=map_name,
                            content="words go here",
                            embed=embedMsg,
                            applied_tags=list[workshopTag, mapTag],
                            reason="reason goes here"
                        )
                        created_thread = await thread.fetch_message(thread.id)

any help is appreciated

#

the error I get rn is TypeError: 'types.GenericAlias' object is not iterable

errant trout
#

(you've done typehinting syntax)

snow crescent
#

ah heck it still ain't applying tags

#

that fixed the error tho

errant trout
#

from what i can tell, you cannot create tags through the api

snow crescent
#

guh, I've been going in circles on this for hours

#

I wish the docs were better about this

errant trout
#

idk about our docs but the official docs have no mention of creating tags, they just happen to exist

#

so we likely don't have any special notes about them

snow crescent
#

I'm not trying to create a tag if that's what you're thinking

#

I just want to add 2 to a forum post

errant trout
#

it looks like you are?

snow crescent
#

I need to course correct if I am then

#

this is where I've been lead by docs and posts here

errant trout
#

if you want to apply existing tags, you get them from channel.available_tags

#

then you can use those objects in your applied_tags list

snow crescent
#

I'll try it thanks

errant trout
#

maybe we need convenience methods for this

pine venture
#
                    amount = 0
                    async for msg in treelist:
                        if "33" in msg.content:
                            amount += 1
                    await message.channel.send("33 has been said "+str(amount)+" times in this channel")``` Damn this is taking a while, is there a faster way?
errant trout
#

if you use limit=None, it will take longer the larger the channel history is

#

so you should be careful when using it

pine venture
#

Normal discord has a search by text feature, does pycord not?

errant trout
#

discord does not allow the search endpoint to be used by bots

pine venture
#

Rip

snow crescent
#

thank you 😭

errant trout
#

allgood

snow crescent
#

hell even just a code example would help

#

finally I can do other things

sage tendon
#

i mean there can't be an example for every tiny thing

sage tendon
errant trout
#

All

#

Theoretically you get ratelimited but the iterator handles it, probably

dapper hamlet
#

is there a bot.event you can use that runs like every day (need it for like a daily leaderboard kind of thing)?

dapper hamlet
dapper hamlet
dapper hamlet
errant trout
#

It can accept time, which is a list of datetime.time objects

dapper hamlet
#

Im dumb, lemme read the doc thoroughly

errant trout
dapper hamlet
#

ayt bet

balmy flicker
#

might be off-topic but... can I use pycord without the event loop? I'd to have a REPL mode CLI tool (with Jupyter Notebook). 🍻

shell radish
#

no

deft kestrel
#

how use defer?
i have await interaction.response.send_message(embed=embed, ephemeral=True)
but sometimes i got a error "interaction not found"

lapis dock
#

interaction.response.defer()

fresh sierra
#

and then you followup cos you cant use defer and reponse

#

interaction.followup.send

glossy moon
#

what would be the reason why my bot is trying to answer 2 times with one call?

sage tendon
#

you are using .send instead of .respond

glossy moon
#

thanks, thats it

deft kestrel
# lapis dock `interaction.response.defer()`
                    embed = discord.Embed(description=f"> ![IlusionEmotes74](https://cdn.discordapp.com/emojis/1222897994660184147.webp?size=128 "IlusionEmotes74") Dziękujemy za utworzenie ticketu! Twój kanał: {ticket_channel.mention}", color=0x982afe)
                    await interaction.response.defer()
                    await interaction.followup.send(embed=embed, ephemeral=True)

                except Except```
#

like this?

lapis dock
#

👍

#

If it does not work add ephemeral=True to defer. I know you need to have the message be ephemeral if the defer is but I am unsure it it is the other way around as well

stray pasture
#

The

async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)

only fetch a maximum of 100 audit logs, event when I put the limit to None

#

I am testing with:

async for entry in guild.audit_logs(limit=None, after=discord.Object(id=0),                                action=discord.AuditLogAction.member_role_update):
  ...
#

It should fetch all audit logs in batches, not just 100 (which is the limit for the iterator at a time)

#

In the doct it says: "limit (Optional[int]) – The number of entries to retrieve. If None retrieve all entries."

deft kestrel
# lapis dock 👍
        select = discord.ui.Select(placeholder="Wybierz kategorię Zakupu", options=options, custom_id="xddddd")
        self.add_item(select)

        async def select_option(interaction: discord.Interaction):

            category_id = int(interaction.data['values'][0])

            if category_id:
                option_label = None
                for option in options:
                    if option.value == str(category_id):
                        option_label = option.label
                        break

                    highest_ticket = tickets_open_collection.find_one(sort=[("ticket_id", -1)])
                    if highest_ticket:
                        ticket_id = highest_ticket["ticket_id"] + 1
                    else:
                        ticket_id = 1

                    ticket_data = {
                        "user_id": interaction.user.id,
                        "category_id": category_id,
                        "category_label": option_label,
                        "ticket_id": ticket_id
                    }
                    tickets_open_collection.insert_one(ticket_data)

                    ticket_channel_name = f"🎫・ticket-{interaction.user.name}"
                    ticket_channel = await interaction.guild.create_text_channel(ticket_channel_name, category=discord.utils.get(interaction.guild.categories, id=category_id),
                                                                        topic=str(interaction.user.id))
                    role = interaction.guild.get_role(1217917143996432495)
                    await ticket_channel.set_permissions(role, read_messages=True)
                    await ticket_channel.set_permissions(interaction.guild.default_role, read_messages=False)
                    await ticket_channel.set_permissions(interaction.user, read_messages=True)

                    embed = discord.Embed(title="Stworzono Ticket", description=
f"""
![IlusionEmotes67](https://cdn.discordapp.com/emojis/1222898102437019649.webp?size=128 "IlusionEmotes67") - Użytkownik: {interaction.user.id}
![IlusionEmotes78](https://cdn.discordapp.com/emojis/1222898036154306631.webp?size=128 "IlusionEmotes78") - Otwarto ticket: {option_label}
![IlusionEmotes30](https://cdn.discordapp.com/emojis/1222883000698802227.webp?size=128 "IlusionEmotes30") - ID Ticketa: {ticket_id}
""", color=0x982afe)
                    embed.set_thumbnail(url=interaction.user.display_avatar.url)

                    await ticket_channel.send(f"{interaction.user.mention} ∙ <@&1217917143996432495>")
                    await ticket_channel.send(embed=embed, view=CloseButton(self.bot))

                    embed = discord.Embed(description=f"> ![IlusionEmotes74](https://cdn.discordapp.com/emojis/1222897994660184147.webp?size=128 "IlusionEmotes74") Dziękujemy za utworzenie ticketu! Twój kanał: {ticket_channel.mention}", color=0x982afe)
                    await interaction.response.defer()
                    await interaction.followup.send(embed=embed, ephemeral=True)

        select.callback = select_option
#

it still does not work

#

i got "unkknown interaction" error

stray pasture
# shell radish

yeah the the expected behavior in the library is that it fetch all of them in batches of 100

#

fetch 1-100, 101-202, ... etc

#

but in the iterator, we only see them coming one at a time

#

without to have to do multiple calls

shell radish
#

seems intended

rugged lodgeBOT
#

discord/iterators.py lines 498 to 505

def _get_retrieve(self):
    l = self.limit
    if l is None or l > 100:
        r = 100
    else:
        r = l
    self.retrieve = r
    return r > 0```
stray pasture
#

and if you check the code, it is suppose to be doing in batches

shell radish
#

the only issue I can see that could be affecting the functionality is the after arg

stray pasture
#

That audit_logs have been broken for a long time, multiple py-cord versions

#

But with different problems

shell radish
#

if you are certain it's a pycord issue, then open an issue on github

stray pasture
#

already open issues 2 times

#

that got fix with PR, but still problems

#

In the last version, the audit_logs is supposed to be fixed in the change logs

#

That is why I when to try again

shell radish
#

it only talks about the after param, and not the fetching 100 part

stray pasture
#

yeah because the fetching 100 part was working before that fix

#

but the after was not

shell radish
#

then open an issue

stray pasture
#

yeah I think I will open again

shell radish
# deft kestrel .

await interaction.response.defer() should be the first line in the callback

stray pasture
#

It is the same code

deft kestrel
#
        async def select_option(interaction: discord.Interaction):
            await interaction.response.defer()
            category_id = int(interaction.data['values'][0])

            if category_id:
                option_label = None
                for option in options:
                    if option.value == str(category_id):
                        option_label = option.label
                        break

                    highest_ticket = tickets_open_collection.find_one(sort=[("ticket_id", -1)])
                    if highest_ticket:
                        ticket_id = highest_ticket["ticket_id"] + 1
                    else:
                        ticket_id = 1

                    ticket_data = {
                        "user_id": interaction.user.id,
                        "category_id": category_id,
                        "category_label": option_label,
                        "ticket_id": ticket_id
                    }
                    tickets_open_collection.insert_one(ticket_data)

                    ticket_channel_name = f"🎫・ticket-{interaction.user.name}"
                    ticket_channel = await interaction.guild.create_text_channel(ticket_channel_name, category=discord.utils.get(interaction.guild.categories, id=category_id),
                                                                        topic=str(interaction.user.id))
                    role = interaction.guild.get_role(1217917143996432495)
                    await ticket_channel.set_permissions(role, read_messages=True)
                    await ticket_channel.set_permissions(interaction.guild.default_role, read_messages=False)
                    await ticket_channel.set_permissions(interaction.user, read_messages=True)

                    embed = discord.Embed(title="Stworzono Ticket", description=
f"""
![IlusionEmotes67](https://cdn.discordapp.com/emojis/1222898102437019649.webp?size=128 "IlusionEmotes67") - Użytkownik: {interaction.user.id}
![IlusionEmotes78](https://cdn.discordapp.com/emojis/1222898036154306631.webp?size=128 "IlusionEmotes78") - Otwarto ticket: {option_label}
![IlusionEmotes30](https://cdn.discordapp.com/emojis/1222883000698802227.webp?size=128 "IlusionEmotes30") - ID Ticketa: {ticket_id}
""", color=0x982afe)
                    embed.set_thumbnail(url=interaction.user.display_avatar.url)

                    await ticket_channel.send(f"{interaction.user.mention} ∙ <@&1217917143996432495>")
                    await ticket_channel.send(embed=embed, view=CloseButton(self.bot))

                    embed = discord.Embed(description=f"> ![IlusionEmotes74](https://cdn.discordapp.com/emojis/1222897994660184147.webp?size=128 "IlusionEmotes74") Dziękujemy za utworzenie ticketu! Twój kanał: {ticket_channel.mention}", color=0x982afe)
                    await interaction.followup.send(embed=embed, ephemeral=True)

        select.callback = select_option```
#

@shell radish Sorry about the ping, but I want to go to sleep and get this done quickly

shell radish
#

if you want it to be ephemeral, add ephemeral=True to defer

deft kestrel
shell radish
#

yes

deft kestrel
#
        async def select_option(interaction: discord.Interaction):
            await interaction.response.defer(ephemeral=True)
            category_id = int(interaction.data['values'][0])

            if category_id:
                option_label = None
                for option in options:
                    if option.value == str(category_id):
                        option_label = option.label
                        break

                try:
                    highest_ticket = tickets_open_collection.find_one(sort=[("ticket_id", -1)])
                    if highest_ticket:
                        ticket_id = highest_ticket["ticket_id"] + 1
                    else:
                        ticket_id = 1

                    ticket_data = {
                        "user_id": interaction.user.id,
                        "category_id": category_id,
                        "category_label": option_label,
                        "ticket_id": ticket_id
                    }
                    tickets_open_collection.insert_one(ticket_data)

                    ticket_channel_name = f"🎫・ticket-{interaction.user.name}"
                    ticket_channel = await interaction.guild.create_text_channel(ticket_channel_name, category=discord.utils.get(interaction.guild.categories, id=category_id),
                                                                        topic=str(interaction.user.id))
                    role = interaction.guild.get_role(1217917143996432495)
                    await ticket_channel.set_permissions(role, read_messages=True)
                    await ticket_channel.set_permissions(interaction.guild.default_role, read_messages=False)
                    await ticket_channel.set_permissions(interaction.user, read_messages=True)

                    embed = discord.Embed(title="Stworzono Ticket", description=
f"""
![IlusionEmotes67](https://cdn.discordapp.com/emojis/1222898102437019649.webp?size=128 "IlusionEmotes67") - Użytkownik: {interaction.user.id}
![IlusionEmotes78](https://cdn.discordapp.com/emojis/1222898036154306631.webp?size=128 "IlusionEmotes78") - Otwarto ticket: {option_label}
![IlusionEmotes30](https://cdn.discordapp.com/emojis/1222883000698802227.webp?size=128 "IlusionEmotes30") - ID Ticketa: {ticket_id}
""", color=0x982afe)
                    embed.set_thumbnail(url=interaction.user.display_avatar.url)

                    await ticket_channel.send(f"{interaction.user.mention} ∙ <@&1217917143996432495>")
                    await ticket_channel.send(embed=embed, view=CloseButton(self.bot))

                    embed = discord.Embed(description=f"> ![IlusionEmotes74](https://cdn.discordapp.com/emojis/1222897994660184147.webp?size=128 "IlusionEmotes74") Dziękujemy za utworzenie ticketu! Twój kanał: {ticket_channel.mention}", color=0x982afe)
                    await interaction.response.send_message(embed=embed)

                except Exception as e:
                    print(f"Error creating ticket: {e}")
        select.callback = select_option```
#

Error creating ticket: This interaction has already been responded to before

now it works but doesn't send messages

#

Could you do it for me quickly? haha let's save ourselves time

shell radish
#

await interaction.response.send_message(embed=embed) should be await interaction.followup.send(embed=embed)

deft kestrel
#

aa okey

#

Thanks @shell radish you are the best ❤️

shell radish
#

you're welcome

dapper hamlet
#

the button works fine, but like why does it still give this:

lapis dock
#

you are not responding to the interaction

#

can you show your button callback

dapper hamlet
lapis dock
#

edit message is a response

#

in some cases

dapper hamlet
# lapis dock can you show your button callback

            @discord.ui.button(label='Daily', style=discord.ButtonStyle.green)
            async def menu1(self, button: discord.ui.Button, interaction: discord.Interaction):
                if interaction.user.id == ctx.author.id:
                    stats = dpf.stats_list_x1(ctx.author.id)
                    embed = dpf.embed_creation_x1(self.bot, ctx.author, stats)
                    view = Menu_x1(self.bot)
                    await interaction.message.edit(embed=embed, view=view)```
#

this was my code

#

the view was essentially to change the button to a separate button

#

with different functionality

#

and it was working completely fine

#

yet loading until

#

"this interaction failed"

#

didnt impact anything but still annoying to view

lapis dock
#

you should be able to use interaction.response.edit_message and that will count as a response instead of interaction.message.edit

#

@dapper hamlet see this, it saves you from needing to send a message ^

dapper hamlet
#

ok thankyou <3

#

thats very helpful 😭 and makes me hate coding !!

#

@lapis dock

also, in the functionality of tasks, is it possible for them to not run everytime the bot is reset and instead run after the time period or is that too much to ask for

lapis dock
#

I gtg sorry

dapper hamlet
dapper hamlet
#

but the way I was doing it rn just to test was having it run every 24 hours

#

however when you restart the bot, it runs automatically ruining the whole point eh

deft kestrel
#

Any idea how to the message content of newest sent message inside a channel constantly and apply it to a value

errant trout
#

or do you need to update something every time a new message is sent?

deft kestrel
#

imports:

#main
from resources import *
import resources as rs
from tickets import *
from logics import *
import time 
import pandas as pd 
import asyncio
import pickle
import string
import hmac
import hashlib
from discord.ext import tasks
#Resoucrces
from coinbase_commerce.client import Client as Client3
from coinbase.wallet.client import Client as Client2
import discord
from discord.ext import bridge, commands
import json
import os
import datetime
import requests
import asyncio
from bitcoinlib.wallets import *
from bitcoinlib.mnemonic import Mnemonic
@bot.bridge_command(guild_id=config["guild_id"], name="addbalance", description="(Admin Only) Adds Balance to a User")
async def addbalance(ctx: bridge.BridgeContext, user: discord.Option(discord.User, description="Member"), amount: discord.Option(float, description="Amount")):
    role = discord.utils.get(ctx.guild.roles, id=int(config["addbalance_role"]))
    if role not in ctx.author.roles:
        return await ctx.respond(embed=await error_embed("Error", "You do not have permission to use this command."))
    await add_balance(user.id, amount)
    await ctx.respond(embed=await create_embed("Success", f"User {user.mention} has been given ${amount}"))

I get warning on the user: discord.Option(discord.User, description="Member") part saying "Call expression not allowed in type expression"

When I try to run the bot I receive the error:

  File "c:\Users\Administrator\Desktop\Bitzer\Cogs\main.py", line 2, in <module>
    from resources import *
  File "c:\Users\Administrator\Desktop\Bitzer\Cogs\resources.py", line 5, in <module>
    from discord.ext import bridge, commands
  File "C:\Python312\Lib\site-packages\discord\ext\bridge\__init__.py", line 26, in <module>
    from .bot import *
  File "C:\Python312\Lib\site-packages\discord\ext\bridge\bot.py", line 31, in <module>
    from discord.commands import ApplicationContext
  File "C:\Python312\Lib\site-packages\discord\commands\__init__.py", line 26, in <module>
    from .context import *
  File "C:\Python312\Lib\site-packages\discord\commands\context.py", line 69, in <module>
    class ApplicationContext(discord.abc.Messageable):
  File "C:\Python312\Lib\site-packages\discord\commands\context.py", line 271, in ApplicationContext
    @discord.utils.copy_doc(Interaction.respond)
                            ^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Interaction' has no attribute 'respond'. Did you mean: 'response'?```

I'm running Python 3.12.3 and py-cord==2.5.0
would appreciate if anyone has an idea, thanks
glossy moon
#

is anyone hosting their bot on AWS and have any pointers on how to get that to work?

sage tendon
#

AWS really is overkill for a discord bot

dapper hamlet
#

for tasks, how do you set it to loop at a specific time of the day

sage tendon
#

with a datetime.time object

dapper hamlet
#

I didnt know you could

#

set an exact time of the day through that?

#

and if you do, it automatically follows your time zone

#

?

dapper hamlet
#

@tasks.loop()

#

what would I need to enter inside

fresh sierra
#

for example

dapper hamlet
fresh sierra
#

So you can just put the hour u want

dapper hamlet
#

ayt bet thankyou v much

#

do I have to import the datetime module for this?

#

ofc okok

#

@tasks.loop(time=datetime.time(15+5, 16, 0, tzinfo=datetime.timezone.utc))
async def daily_db_reset():
    print('.')

#

this wasnt working when I set it a minute ahead and waited 😭

#

Im gmt+5 so

#

theoretically this should have ran at 3:16 my time yea?

fresh sierra
dapper hamlet
#

😭 it didnt

fresh sierra
#

did you start the loop correctly ?

dapper hamlet
#

yeah

#

or do I have to add more functionality?

fresh sierra
#

not gtm

dapper hamlet
#

thats why I added

#

15+5

#

oh

#

or

#

is utc and gmt diff?

#

wtf

#

it should be the same regardless right?

fresh sierra
#

yes so

dapper hamlet
#

mhm, so whats the issue exactly 💀 Im confused asf

fresh sierra
#

are you sure you are utc + 5 ?

#

and not utc - 5

dapper hamlet
#

pretty sure yep

fresh sierra
#

utc + 5 = me

so utc = me - 5

dapper hamlet
#

💀 oh

fresh sierra
#

@tasks.loop(time=datetime.time(15-5, 16, 0, tzinfo=datetime.timezone.utc))

dapper hamlet
#

thankyou for teaching me basic maths

#

ly

fresh sierra
#

🤣

glossy moon
errant trout
#

.tag hosting

sly karmaBOT
errant trout
#

those are just some recommendations, but there are way more out there

#

if you have the aws trial then tbh go for it, it's pretty nice, but you wanna be prepared to migrate to another service at the end because the cost isn't really worth it for a bot

glossy moon
#

thanks for the info. I was looking at AWS lamba functions because you only get charged for when the bot is pinged and my bot is highly specialized and doesnt get used often. It more there as a resource if anyone wants it. So it would literally be a couple dollars a year

#

i was hosting on heroku, but it went from free to like $7-12 a month

errant trout
#

"only when the bot is pinged" isn't exactly applicable because the gateway always has to be listening

#

even if your bot seems to be doing nothing, it's still processing every event

glossy moon
#

correct, but to my understanding, unless im reading the docs incorrectly, you are only paying for when a specific command you have set up is being called

errant trout
#

i think that comes with the assumption that, when the command isn't being called, the system is completely idle and doing nothing

glossy moon
#

looks like it would be similar to digital ocean functions

errant trout
#

idk, i don't know much about other aws stuff beyond ec2 so perhaps you're far beyond me and this would work out nicely, but just based on how discord bots recieve events i'm unsure

glossy moon
errant trout
#

though considering the pricing you outlined, there'd be little harm in testing it out

errant trout
glossy moon
#

I guess I'll have to look into it. Might end up just self hosting if its not going to be used often

#

thank you for the help @errant trout

errant trout
#

allgood

#

if you do selfhost, with new windows terminal you can pretty easily one-click launch your bot which i do for testing prs

glossy moon
#

good to know

hazy turret
#

Is it possible to determine the language setting of a user and use this information to display the text in an embed individually for the user in their language?

edgy nest
hazy turret
sage tendon
#

no

#

you can only guess based on the language

#

though, embed timestamps will always be localised to the user's timezone
if that's your plan

hazy turret
#

Okay, I used the timestamps 🙂

cobalt comet
#
@bridge.bridge_command()
async def ping(self, ctx: bridge.BridgeContext):
    await ctx.respond(f'Pong! :ping_pong: {self.bot.latency} ms')```
#

how do i add the description for the slash command here?

little cobalt
sage tendon
#

i suppose doing this.. ```py
messages = await ctx.channel.history(limit=50).flatten()
messages.reverse()

to feed my bot the message history for its AI command is ideal, is it?
#

Or is the ratelimit // time impact negligible?

shell radish
#

i mean it is just one request

sage tendon
#

Yea im not sure how it works behind the scenes

#

i'm also thinking of giving the AI 100 messages but im not sure how much impact thatll have, since i'm basically traversing the entire history and converting it into a list of dicts
also not sure about the time impact of the AI geneartion but oh well thaast my issue lmao

cobalt comet
#

is there any example on how to do command flags?
eg:
!greet hello (sends hello by replying)
!greet hello --silent (sends hello in dm)

sage tendon
#

i mean, just read the text and check it against a list of "flags"

quartz umbra
#

Hi, y'know when a webhook sends a message, is it possible for the username's color to be changed from just white, like to the colour of a ranK?

sage tendon
#

no

upper flint
sage tendon
#

you say that after i put a solution there

keen dragon
#

how do i sync a channels permission with its category?

fresh sierra
#

And put sync = true

rugged lodgeBOT
fresh sierra
#

This one

sage tendon
#
channel.edit(sync_permissions=True)
keen dragon
#

thank you

weary meteor
#

is it not possible to allow a bot to ping everyone?

#

same for an @ here

weary meteor
#

help = SlashCommandGroup("help", "Help commands... duh")

ofc the way the command groups work is like /help <thingy> but how do i make /help just as a standalone work

keen dragon
#

would editing (or sending a message if it got deleted) in the same channel every 10 secs on one bot get me ratelimited

deft kestrel
#

how many messages r u editing

fresh sierra
rugged lodgeBOT
errant trout
keen dragon
deft kestrel
rain dune
#
    @commands.Cog.listener()
    async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send("This command is currently on cooldown. Please try again later.", ephemeral=True)
        else:
            raise error

i tried cooldown error handling for a command, it is not sending the msg
is there something i am missing?

fresh sierra
rain dune
#

    @commands.slash_command(guild_ids=[864779702554984458,556197206147727391],description="BOT info.")
    @commands.cooldown(2, 10, commands.BucketType.user)
    async def info(
        self,
        ctx
    ):
#

like this

fresh sierra
#

can you check the MaxConcurrency error

#

maybe that the error it raise and not the command on cooldown

rain dune
#

naah its raising cooldown error but idk why its not sending the message

Ignoring exception in command info:
Traceback (most recent call last):
  File "/Users/shambo/Documents/GitHub/valo-shop-1/venv/lib/python3.11/site-packages/discord/bot.py", line 1130, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/Users/shambo/Documents/GitHub/valo-shop-1/venv/lib/python3.11/site-packages/discord/commands/core.py", line 373, in invoke
    await self.prepare(ctx)
  File "/Users/shambo/Documents/GitHub/valo-shop-1/venv/lib/python3.11/site-packages/discord/commands/core.py", line 304, in prepare
    self._prepare_cooldowns(ctx)
  File "/Users/shambo/Documents/GitHub/valo-shop-1/venv/lib/python3.11/site-packages/discord/commands/core.py", line 288, in _prepare_cooldowns
    raise CommandOnCooldown(bucket, retry_after, self._buckets.type)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 5.41s
fresh sierra
#

that mb

#

i didnt saw u were on slash comamnd

fresh sierra
#

not slash

#

on_application_command_error is the good event

rain dune
fresh sierra
#

with pleasure

rain dune
fresh sierra
#

like that : error.retry_after

#

it give the second

rotund quarry
#

Is possible to definite a view (button) and then call it later on a aplication command (emphermal)? Note that the class is up and aplication down

tidal vessel
rotund quarry
#

This is a example

tidal vessel
lofty parcel
#

That's like... normal python...

cobalt comet
#

how to make optional arguments in bridge commands? that acts as optional argument in both message command and slash command

fresh sierra
lofty parcel
#

required=False makes it return None

deft kestrel
#

i need help
is it possible to make a drop down but the label,description,emoji and value is from an db
i mean something like that:

        cur.execute("SELECT options,options_name,options_emoji,options_description FROM servers_info WHERE guild_id = ?", (self.guild_id))  # Fetch data from the database
        data = cur.fetchall()

        options = []
        labels = []
        for row in data:
            label = row[1]  # options_name
            labels.append(row[1])
            description = row[3]  # options_description
            emoji = row[2]  # options_emoji
            value = label.lower().replace(" ", "_")  # Lowercase label with spaces replaced by underscores

            option = discord.SelectOption(label=label, description=description, emoji=emoji, value=value)
            options.append(option)

and if i did it right (NO WAY) or its possible how i add it to the discord.ui.select?

deft kestrel
shell radish
#

there are multiple ways to do it. You can subclass or just work with objects

fresh sierra
#

then you can just do

#

no ?

shell radish
#

selects aren't views and that select doesn't have a callback

fresh sierra
#

did it too fast

#

view = discord.ui.View
view.add_item(discord.ui.Select(options=options) )

#

yeah but idk what he wanna do for callback

#

and idk if its a view

#

i will need more context to help you @deft kestrel

deft kestrel
fresh sierra
#

the discord.ui.Select

deft kestrel
#
class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

    async def setup_options(self, select):
        cur.execute("SELECT options,options_name,options_emoji,options_description FROM servers_info WHERE guild_id = ?", (self.guild_id))  # Fetch data from the database
        data = cur.fetchall()

        options = []
        labels = []
        for row in data:
            label = row[1]  # options_name
            labels.append(row[1])
            description = row[3]  # options_description
            emoji = row[2]  # options_emoji
            value = label.lower().replace(" ", "_")  # Lowercase label with spaces replaced by underscores

            option = discord.SelectOption(label=label, description=description, emoji=emoji, value=value)
            
            options.append(option)
        MyView.add_item(option)

    @discord.ui.select(
        custom_id="ticket_options",
        placeholder="Choose a Ticket option",
    )
        
    async def callback(self, select, interaction: discord.Interaction):
        await self.setup_options(select)
fresh sierra
#

do something lik ehtat

#
class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

        cur.execute("SELECT options,options_name,options_emoji,options_description FROM servers_info WHERE guild_id = ?", (self.guild_id))  # Fetch data from the database
        data = cur.fetchall()

        options = []
        labels = []
        for row in data:
            label = row[1]  # options_name
            labels.append(row[1])
            description = row[3]  # options_description
            emoji = row[2]  # options_emoji
            value = label.lower().replace(" ", "_")  # Lowercase label with spaces replaced by underscores

            option = discord.SelectOption(label=label, description=description, emoji=emoji, value=value)
            
            options.append(option)
        MyView.add_item(option)

    select = discord.ui.select(
        custom_id="ticket_options",
        placeholder="Choose a Ticket option",
    )
    select.callback = callback    
    self.add_item(select)

  async def callback(self, interaction: discord.Interaction):
      await self.setup_options(select)
fresh sierra
#

need to be 1 more on the left

#

and so it will be self.callback

#

also remove myview.additem

deft kestrel
#

delete one space?

fresh sierra
#

yes to go on the left

#

like one tab

#

the select has to be Select

deft kestrel
#

to be on the "wall"?

fresh sierra
#

its not the callback that need to be move

#

but the 3 lines above

#

that need to be 1 time more on the right

#

and so its not = callback but = self.callback

deft kestrel
#
    select.callback = self.callback    
    self.add_item(select)
```?
deft kestrel
#

"self" is not defined

fresh sierra
deft kestrel
fresh sierra
#

from the select

#

to the self.add_item

#

and also its Select and not select

#

for the discord.ui.Select

deft kestrel
#

error:

Ignoring exception in modal <cogs.ticket_commands.DescriptionModal object at 0x000001C39C88D670>:
Traceback (most recent call last):
  File "c:\Users\Assaf Cohen\OneDrive\bot\testing\.venv\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "C:\Users\Assaf Cohen\OneDrive\bot\testing\cogs\ticket_commands.py", line 268, in callback
    await ticket_channel.send(embed=embed, view=MyView(bot=self.bot, guild_id=interaction.guild.id))
  File "c:\Users\Assaf Cohen\OneDrive\bot\testing\.venv\Lib\site-packages\discord\abc.py", line 1651, in send
    data = await state.http.send_message(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Assaf Cohen\OneDrive\bot\testing\.venv\Lib\site-packages\discord\http.py", line 373, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: Must be between 1 and 25 in length.

code:
```py
embed = discord.Embed(
title=f"{TITLE} • Ticket System",
description="To Open ticket choose the option you need",
color=discord.colour.Color.blue()
)
embed.set_footer(text=FOOTER,icon_url=FOOTER_URL)
cur.execute("SELECT channel FROM servers_info WHERE guild_id = ?", (interaction.guild.id,))
channel = cur.fetchone()[0]
ticket_channel = self.bot.get_channel(channel)
if ticket_channel:
await ticket_channel.send(embed=embed, view=MyView(bot=self.bot, guild_id=interaction.guild.id))
else:
print("Couldn't find")

fresh sierra
#

you should have options=options

deft kestrel
#

how i can get the emoji name?

fresh sierra
deft kestrel
fiery fable
#

i need it for wavelink

shell radish
shell radish
fiery fable
#

but wavelink does

shell radish
#

I don't use wavelink so I can't comment on that

deft kestrel
fresh sierra
#

because for my test, wavelink and pycord are not compatible

#

(pycord2.5)

fiery fable
fresh sierra
#

maybe just not compatible

fiery fable
#

they kinda are, its just focused on dpy

fresh sierra
#

for example

#

there was a version not compatible

#

and after that a new which ws

#

there is someone that use it wait

#

this man @waxen ore

deft kestrel
# fresh sierra get the emoji

luma i have tryied back me old ticket system with the same emojis and its working so you maybe know why i am getting Invalid emoji error?

errant trout
#

Is it a custom emoji

deft kestrel
errant trout
#

So it's a regular Unicode emoji? You can just pass it as a string

deft kestrel
#
        for i in range(data[0][0]):
            label = labels[i]
            description = descriptions[i]  # options_description
            Emoji = Emojis[i]
            value = label.lower().replace(" ", "_")  # Lowercase label with spaces replaced by underscores
            option = discord.SelectOption(label=label, description=description, emoji=Emoji, value=value)
            options.append(option)

when i am doing like that its doesnt work and when i am doing like that:

    @discord.ui.select(
        custom_id="support",
        placeholder="Choose a Ticket option",
        options=[
            discord.SelectOption(
                label="Buy",  #Name of the 1 Select Menu Option
                description="You will buy things here!",  #Description of the 1 Select Menu Option
                emoji="💰",        #Emoji of the 1 Option  if you want a Custom Emoji read this  
                value="buy"   #Don't change this value otherwise the code will not work anymore!!!!
            ),
            discord.SelectOption(
                label="Support",  #Name of the 2 Select Menu Option
                description="Ask questions here!", #Description of the 2 Select Menu Option
                emoji="❓",        #Emoji of the 2 Option  if you want a Custom Emoji read this 

its working

errant trout
deft kestrel
#

wait sec

errant trout
#

Might have trailing spaces which can be removed with .strip()

rotund quarry
deft kestrel
# errant trout Then what happens if you print `Emoji` in the first example
        options = []
        for i in range(data[0][0]):
            label = labels[i]
            description = descriptions[i]  # options_description
            Emoji = Emojis[i]
            print(Emoji)
            print(Emoji)
            value = label.lower().replace(" ", "_")  # Lowercase label with spaces replaced by underscores
            option = discord.SelectOption(label=label, description=description, emoji=Emoji, value=value)
            options.append(option)

output:
💰
💰


🎉
🎉

errant trout
#

Or actually just print the whole Emojis list

sage tendon
#

what does that do, just curious

errant trout
#

Forcing it to print as list which shows it slightly better

sage tendon
#

yea i know, i was wondering how it would change the output tho

deft kestrel
#

['💰', ' ❓', ' 🎉']
💰
['💰']
['💰', ' ❓', ' 🎉']

[' ❓']
['💰', ' ❓', ' 🎉']
🎉
[' 🎉']

            print(Emojis)
            print(Emoji)
            print([Emoji])
errant trout
#

Well in the case of strings, it'll show the quotation marks

errant trout
#

Just use Emoji.strip() instead (or ideally, change how it's stored in the first place)

deft kestrel
#
Emoji = Emojis.strip(",")

?

errant trout
#

No not that

#

Obviously you need the split for the list

#

But strip removes starting and ending whitespace from the string, which is what you want here

deft kestrel
errant trout
#

I literally typed it above

#

Alternatively you could add a space to your comma split, depends on how it's input

deft kestrel
#

so the same just without the ,

errant trout
#

Not on Emojis, on Emoji

deft kestrel
#
            Emoji = Emojis[i]
            Emoji = Emoji.strip()

?
i feel dumb

errant trout
#

Yeah that works

sage tendon
#

Emojis[i].strip() for beautiful syntax

deft kestrel
#

i have another problem i can see the dropdown but it doesnt ahve callback

fresh sierra
deft kestrel
#
class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

        cur.execute("SELECT options,options_name,options_emoji,options_description FROM servers_info WHERE guild_id = ?", (self.guild_id,))  # Fetch data from the database
        data = cur.fetchall()

        Emojis = (data[0][2].split(","))  # options_emoji'  
        descriptions = (data[0][3].split(","))
        labels = data[0][1].split(",")  # options_name

        options = []
        for i in range(data[0][0]):
            label = labels[i]
            description = descriptions[i]  # options_description
            Emoji = Emojis[i].strip()
            value = label.lower().replace(" ", "_")  # Lowercase label with spaces replaced by underscores
            option = discord.SelectOption(label=label, description=description, emoji=Emoji, value=value)
            options.append(option)

        select = discord.ui.Select(
            custom_id="ticket_options",
            placeholder="Choose a Ticket option",
            options=options,
        )
        select.callback = self.callback    
        self.add_item(select)
sage tendon
#

man the famous MyView class
never ceases to amaze

deft kestrel
little cobalt
#

its so easy to do

sage tendon
#

i might be dumb but i dont even see self.callback anywhere?

deft kestrel
#

    async def callback(self, interaction: discord.Interaction):
        cur.execute("SELECT options,options_name,options_category,channel,guild_id FROM servers_info WHERE guild_id = ?", (interaction.guild.id,))  # Fetch data from the database
        data = cur.fetchall()
#

part of it

little cobalt
#

and for what is the callback?

#

and why did you add the bot to it?

lofty parcel
#

Isn't subclassing the select better at this point

sage tendon
#

subclassing the thing you want to subclass is usually what you should do

#

:3

#

yea i dont see the need for subclassing the view class eitehr

deft kestrel
#

so i need to subclass it?

lofty parcel
#

I feel you don't know OOP.

deft kestrel
#

i know in java (i know it doesnt help)

sage tendon
#

its no different in python, conceptually

deft kestrel
lofty parcel
#

OK, subclass the select instead

#

Do the same thing. Parse the options on your init, but you pass such options to the options= in the super()__init__()

#

And you just move the callback as a class method

fresh sierra
#

can you just show the whole cog @deft kestrel

#

(the myview + function callback

#

because what you did seems good

#

i think you just miss a tab, or just that take too much time so a defer

deft kestrel
fresh sierra
#

yeah that it

#

you have to add a defer

deft kestrel
#

how?

fresh sierra
#

also you have some issue in the code

#

like this line :

                        await interaction.message.edit(embed=embed, view=MyView(bot=self.bot)) #This will reset the SelectMenu in the Ticket Channel

#

ur class myview has 2 arg, bot and guild id, however u passed only bot, you need to also pass guild_id

deft kestrel
#

still does none

#

doesnt print

little cobalt
# fresh sierra

Why did you send the code as a full? how should the user learn anything of it?

sage tendon
#

bonus points for no syntax highlighting

deft kestrel
fresh sierra
#

interaction.reponse.defer

sage tendon
deft kestrel
fresh sierra
#

wait

#

just to be sure

#

you send the new view between clicking again right ?

#

and you dont use an old view on the message

deft kestrel
fresh sierra
#

after changing the code

#

it send the new ticket ?

#

you dont click on the old one right ?

deft kestrel
#

no

fresh sierra
#

that's ur issue

#

ur select menu is not persistent

fresh sierra
#

.rftm persistent

#

.rtfm persistent

deft kestrel
#

i mean after i used the dropdown its doesnt even print the 1 in the code

fresh sierra
#

and the bot has restarted since

deft kestrel
#

so how i can do it to not stop working after a restart

sage tendon
fresh sierra
#

persistent

fresh sierra
#

not sure that english

fresh sierra
#

basically uou need to add a custom_id on the select

#

but you did that point

#

and then you need on the on_ready to use bot.add_view(bot, guild_id)

deft kestrel
#

did that too

fresh sierra
#

where

deft kestrel
#
class Ticket_System(commands.Cog):

    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'Bot Loaded | ticket_system.py ✅')
        self.bot.add_view(MyView(bot=self.bot))
        self.bot.add_view(CloseButton(bot=self.bot))
        self.bot.add_view(TicketOptions(bot=self.bot))
fresh sierra
#

but that will not work

#

like

#

the myview take 2 arg

#

bot and guild

#

and here you only put bot

#

you miss the guild arg

deft kestrel
#

so i need the guild too?

#

ok

fresh sierra
#

well that what you did

deft kestrel
#

ok

fresh sierra
#

and so you can do for guild in bot.guilds : add_view(bot, guild.id)

#

since you did it for each guild (i guess)

deft kestrel
#

yh

fresh sierra
#

because old one will not work

#

(send a new message with the dropdown on it)

deft kestrel
#

ok

#

thanks

fresh sierra
deft kestrel
fresh sierra
fresh sierra
#

is there a way to "followup" a modal ?

waxen ore
#

@fiery fable yeah, wavelink and pycord works fine for me

#

but you need to install wavelink without deps afaik

red mist
#

exactly

sage tendon
#

thats legit the dumbest thing i can think of

red mist
#

Which leads to one having to uninstall discord.py (then if necessary py-cord too to then just reinstall py-cord)

red mist
#

I mean in the core wavelink works for py-cord but I think that in the future py-cord will need it's own "wavelink" because wavelink is built on discord.py and syntaxes might be diff in the future

waxen ore
#

You will get error caused by this lib anyway

errant trout
#

so eh just uninstall/reinstall after and i doubt anything will break in terms of voice unless dpy does a 3.0 release

fresh sierra
#

waiting for the 4 to be functional everywhere

fiery fable
fresh sierra
#

i was doing like that before :

#
    @commands.Cog.listener()
    async def on_ready(self):
        node = wavelink.Node(uri='', password='')
        await wavelink.Pool.connect(nodes=[node], client=self.bot)
        self.bot.add_view(Player_view(self.bot))
fiery fable
fresh sierra
fiery fable
# fresh sierra Do you have an error ?
An unexpected error occurred while connecting Node(identifier=TYglvPeXypMSPI7r, uri=http://localhost:2333, status=NodeStatus.CONNECTING, players=0) to Lavalink: "Cannot connect to host localhost:2333 ssl:default [Connect call failed ('127.0.0.1', 2333)]"
If this error persists or wavelink is unable to reconnect, please see: https://github.com/PythonistaGuild/Wavelink/issues
#

i asked on their discord server and said they arent supporting pycord

fresh sierra
#

Don’t think you should put localjost

fresh sierra
#

You should do

#

uri=ip:port

#

node = wavelink.Node(uri='http://ip:1028', password='LumabotLavalink!')

#

Like that

red mist
fiery fable
#
@commands.Cog.listener()
    async def on_ready(self):
        print("here")
        nodes = [wavelink.Node(
            client=self.bot,
            uri='127.0.0.1:2333',
            password='aaa',
        )]

        await wavelink.Pool.connect(nodes=nodes, client=self)
fresh sierra
fiery fable
#

yes

#

well i mean the lavalink and the bot are running on the same system

#

thats why localhost

red mist
#

You're trying to connect to an IP which does not support SSL

fresh sierra
#

you forgot the http://

red mist
#

fiery fable
#

thanks

fresh sierra
#

did it work now ?

rare marlin
#

The problem is that when you enter the "Tickets select" command, it should only show the options for a specific server. But right now the options are showing for all servers which is not right. can anyone help how to fix it? ```py
@ticket.command(description="Add a ticket option")
async def select(self, ctx, name: str, emoji: str):
await ctx.defer(ephemeral=True)
guild_id = ctx.guild.id
ticket_message = await db.get_message(guild_id)
if ticket_message:
try:
if await db.name_exists(guild_id, name):
await ctx.respond("This name is already in use. Please choose a different name.", ephemeral=True)
return
options = await db.get_options(guild_id)
if len(options) >= 5:
await ctx.respond(
"You have reached the maximum number of options (5). Please remove an option before adding a new one.",
ephemeral=True)
return

            message = await ctx.channel.fetch_message(ticket_message)
            await db.add_option(guild_id, name, emoji)
            options = await db.get_options(guild_id)
            t_options.append(discord.SelectOption(label=name, emoji=emoji))
            view = CreateTicketSelect(t_options)
            await message.edit(view=view)
            await ctx.respond("The option was added successfully.", ephemeral=True)
        except Exception as e:
            await ctx.respond(f"An error occurred: {e}", ephemeral=True)
        print(name)
    else:
        await ctx.respond(f"The ticket message was not found. Please {self.bot.get_cmd('ticket setup')} First!",
                          ephemeral=True, delete_after=10)```
fresh sierra
#

so without seeins the db func we cant help you

rare marlin
#
    async def add_option(self, guild_id, option_name, emoji):
        await self.execute(
            "INSERT INTO ticket_options (guild_id, option_name, emoji) VALUES (?, ?, ?)",
            (guild_id, option_name, emoji)
        )

    async def get_options(self, guild_id):
        rows = await self.all("SELECT option_name, emoji FROM ticket_options WHERE guild_id = ?", (guild_id,))
        options = [{'name': row[0], 'emoji': row[1]} for row in rows]
        print(f"Options for guild {guild_id}: {options}")
        return options


    async def remove_option(self, guild_id, option_name):
        await self.execute("DELETE FROM ticket_options WHERE guild_id = ? AND option_name = ?", (guild_id, option_name))```
#
class TicketDB(ezcord.DBHandler):
    def __init__(self):
        super().__init__("db/ticket.db")

    async def setup(self):
        try:
            await self.execute(
                """CREATE TABLE IF NOT EXISTS ticket(
                guild_id INTEGER PRIMARY KEY,
                category_id INTEGER DEFAULT 0,
                teamrole_id INTEGER DEFAULT 0,
                logs_channel_id INTEGER DEFAULT 0,
                channel_id INTEGER DEFAULT 0,
                message_id INTEGER DEFAULT 0
                )"""
            )
            await self.execute(
                """CREATE TABLE IF NOT EXISTS ticket_options(
                guild_id INTEGER,
                option_name TEXT,
                emoji TEXT,
                FOREIGN KEY(guild_id) REFERENCES ticket(guild_id)
                )"""
            )
            print("Tables 'ticket' and 'names' created successfully")
        except Exception as e:
            print(f"An error occurred while creating the tables: {e}")```
ivory beacon
#

how to set status like this ?

ivory beacon
fresh sierra
fresh sierra
#

somewhere

rare marlin
rare marlin
fresh sierra
fresh sierra
#

that ur issue

rare marlin
fresh sierra
#

i think that you dont remove it everytime

#

wait

#

can you show me the whole cog ?

#

from the class view to the command

#

no but like there still some issue

fresh sierra
#

so its definied before

#

and do not change everytime

#

so it append every open

#

you should do something like that

#

(can you send the code in ```py

#

for i can edit it to show u

rare marlin
#

what should I send you?

fresh sierra
rare marlin
#
class CreateTicketSelect(discord.ui.View):
    def __init__(self, guild_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id
        self.options = db.get_options(self.guild_id)

    @discord.ui.select(
        custom_id="bro_i_dont_know",
        placeholder="👆 | CLICK ME!",
        options=t_options,
    )```
fresh sierra
#

so basically

#

you should do like that

#
class CreateTicketSelect(discord.ui.View):
    def __init__(self, guild_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id
        self.options = db.get_options(self.guild_id)

        select = discord.ui.select(custom_id="bro_i_dont_know", placeholder="👆 | CLICK ME!", options=self.options)
        select.callback = self.ticket_select_callback
        self.add_item(select)
#

so

#

i will explain you why

#

you are trying to edit the toptions everytime in the callback

errant trout
#

not quite, you can't use self there

fresh sierra
#

which is not the best idea

#

tabulation are strange on discord

errant trout
#

inside the init, you just need to change self.options = ... to self.ticket_select_callback.options = ..., then remove options from your decorator

errant trout
#

try it

#

(luma's updated answer also works, there's a few paths you can take)

fresh sierra
#

since you defined a dict once

#

and send append every time

#

every option will just be added without never remove the other

#

so here

#
                options = await db.get_options(guild_id)
                t_options.append(discord.SelectOption(label=name, emoji=emoji))
                view = CreateTicketSelect(t_options)
                await message.edit(view=view)
#

you should remove the t_options and only use the option from the options = await db.get_options(guild_id)

#

since you already add the option before you can simply do

#
                options = await db.get_options(guild_id)
                view = CreateTicketSelect(options)
#

well not really ur class as some issue

#

ur class CreateTicketSelect takes a guild_id parameter and not a option parameter

fresh sierra
fiery fable
# fresh sierra did it work now ?

yes, the http prefix worked and to be fair my lavalink was kinda broken too. but thanks! (didnt use wavelink for years and now they changed everything...)

fresh sierra
#

good luck

olive ridge
#

Is it possible to create a select menu field within the slash command and not as a separate message you send for the user to choose?

sage tendon
#

you can use choices=

sage tendon
#

for a single predetermined choice

lean garnet
#

Hi !
How can I have the id who interacted with a button ?

sage tendon
#

no multiples tho

lean garnet
#

thanks

sage tendon
#

use the docs :) it's all there

sage tendon
cobalt comet
#

inside on_message event, how to get the name of the command that is run by the user? ignores other messages

shell radish
#

what command are we talking about

cobalt comet
#

i mean the prefix based commands, like i want to check if the user has a data in db when running a command, if not ask them to create

errant trout
#

you should use a check instead of the event

#

lemme get the docs

cobalt comet
#

yes, i just read the docs about check

#

but i have another question with that

errant trout
#

go on

cobalt comet
#

nvm that, i figured it out.

#

but for this, how do i access the member parameter for the cog_before_invoke method?

cobalt comet
# errant trout ctx.author

no, the other member who they mentioned or their id they've given as input. it works well in the coins command, but i want to make that logic common for other 3 related commands

errant trout
#

then ctx.args

#

or kwargs if you prefer a dict

#

might not be the same, i forget

cobalt comet
cobalt comet
#

why does the ctx.args array be empty inside cog_check method? but not inside cog_before_invoke

errant trout
upper flint
#

Can bot create invite links?

errant trout
#

yeah

#

guild.create_invite

upper flint
#

Appreciate it

errant trout
#

or channel, if you wanna be specific

cobalt comet
errant trout
#

ultimately depends on your goal but yeah

errant trout
upper flint
#

Yes

errant trout
#

even though it exists on the ui nelothink maybe it selects a default

cobalt comet
#

is there any way to stop the command from executing in the cog instead of cog_check ?

errant trout
#

eh

#

raise an error in before_invoke? lol

cobalt comet
#

oh lol, interesting, lemme try

valid panther
#

Do you recommend the use of @commands.check_any ?
I want to make the command accessible to the server owner and to me, in case I need help.

    @commands.check_any(commands.is_owner(), commands.has_permissions(manage_emojis=True))
    async def tes(self, ctx):
        await ctx.respond(embed=info_embed("Test..."), ephemeral=True)
errant trout
#

that works yeah

#

though uh, is_owner checks for the bot owner, not server owner

deft kestrel
#

I'm trying to get the embed contents of disboard's successful bump embed, but message.embeds returns an empty list when testing it with another bot and message.interactions.*/.interactions doesn't seem to give me that data miathinkink

silk oriole
#

Hello! I'm trying to migrate my bot from discord.py to pycord and everything seems to be going well, but for some reason discord.Option isn't cooperating and is giving me a warning

@chatgpt.command()
async def chat(ctx: discord.ApplicationContext, prompt: discord.Option(str)): # WARNING: Call expression not allowed in type expression
    pass

Am I doing something wrong? Even copy pasting the tutorial in the guide gives the same warning.

#

Nevermind, just doing prompt: str worked fine.

I do have another question though, in discord.py you would describe the options beforehand using a decorator which allowed you to give the option a description. I couldn't find that in the guide nor in the docs. How is that achieved with pycord?

shell radish
silk oriole
#

Got it, thank you!

sly karmaBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

deft kestrel
#

I'll refer back to this issue when I'm back from work

sage tendon
#

You also need embeds intent, which is part of default intents

silk oriole
#

I'm trying to setup the Lavalink stuff since that's one of the bigger reasons I wanted to migrate to pycord, and I followed the guide exactly but am getting this error when I try connecting to the Lavalink server:

An unexpected error occurred while connecting Node(identifier=OcarinaNode, uri=http://0.0.0.0:2333, status=NodeStatus.CONNECTING, players=0) to Lavalink: "Cannot connect to host 0.0.0.0:2333 ssl:default [The format of the specified network name is invalid]"
If this error persists or wavelink is unable to reconnect, please see: https://github.com/PythonistaGuild/Wavelink/issues
#

Googling the error doesn't seem to bring up any results and I'm not sure what to do at this point

#

NEVERMIND I got it

little cobalt
#

what was it?

silk oriole
#

I replaced the 0.0.0.0 with my ipv4 which I should've y'know, expected

little cobalt
#

lul

sage tendon
#

thats a weird bug

silk oriole
#

is that not intended behavior?

sage tendon
#

0.0.0.0 is very typically localhost

little cobalt
#

ye

silk oriole
#

my localhost is not that

#

at least i don't think it is

sage tendon
#

...

#

no

#

0.0.0.0 works like 127.0.0.1

silk oriole
#

oh

#

i didn't know that

#

good to know though

#

i may be a little stupid but what do i actually give the command to search for music?

#

i gave normal text and then a direct soundcloud link and neither worked

waxen ore
#

not that hard

#

tbh

silk oriole
#

i have been :)

waxen ore
silk oriole
#

i haven't worked with anything like wavelink before

silk oriole
waxen ore
#

hmmm, can you send me ur code in DM or here if u dont mind?

#

bcs this code worked for me

silk oriole
#
import typing
import wavelink
import discord

async def voice_search_and_play(ctx, search: str):
  vc = typing.cast(wavelink.Player, ctx.voice_client)

  if not vc:
    vc = await ctx.author.voice.channel.connect(cls=wavelink.Player)

  if ctx.author.voice.channel.id != vc.channel.id:
    return await ctx.respond("You must be in the same voice channel as the bot.")


  song = await wavelink.Playable.search(search)

  if not song:
    return await ctx.respond("No song found.")

  await vc.play(song)
  await ctx.respond(f"Now playing: `{song.title}`")

the above code gets called below:

# lotta other commands up here

@voice.command(name="play")
async def play(ctx: discord.ApplicationContext, search: str):
    await VOICE.voice_search_and_play(ctx, search)

# some other commands down here
sage tendon
#

are you in a vc?

silk oriole
#

yes

#

and so is my bot

#

also giving it the soundcloud link doesn't actually respond with "now playing" it just doesn't respond to the interaction

#

one moment it had my REAL ASS IP

sage tendon
#

people are still scared about IPs?

silk oriole
#

rather not take the chance

#

effectively can't learn anything about me but i don't wanna give away anything

waxen ore
#

can you change song variable to await wavelink.Playable.search(search, source=wavelink.TrackSource.YouTube) then restart your bot and check if you can search some yt video? just to test if ur lavalink working properly

silk oriole
#

oh wait for some reason i think "song" is being interpreted as a list

#

AttributeError: 'list' object has no attribute 'encoded'

waxen ore
#

but if it's search

#

it is

silk oriole
waxen ore
#

may be messed

silk oriole
#

yeah maybe

#

i'm gonna take a small break, been at this for quite a few hours though, i appreciate all of y'alls help :)

waxen ore
#

btw lavalink needs plugin to work with youtube

silk oriole
#

ya i think i have that

#

oh my fatass forgot to replace VERSION

#

naw still didn't do nothin

#

it's working with soundcloud now >:)

#
async def voice_search_and_play(ctx, search: str):
    vc = typing.cast(wavelink.Player, ctx.voice_client)

    if not vc:
        vc = await ctx.author.voice.channel.connect(cls=wavelink.Player)

    if ctx.author.voice.channel.id != vc.channel.id:
        return await ctx.respond("You must be in the same voice channel as the bot.")

# the new!
    tracks = await wavelink.Playable.search(search)

    if not tracks:
        return await ctx.respond("No song found.")

    song = tracks[0]
# end of the new

    await vc.play(song)
    await ctx.respond(f"Now playing: `{song.title}`")
little cobalt
#

that is why I started to add all the stuff like text: str or int for numbers

#

etc

silk oriole
#

OH yeah i gotta start doing that

#

thank you for reminding me

silk oriole
#

am back, does the recording function record each individual user in the VC or is it all at once?

sage tendon
#

p sure everything

silk oriole
#

hmmhmhmh okie

#

thank you

sage tendon
#

but try it

silk oriole
#

ye i'll need to once my friends wake up

#

i've had the idea of having my bot be abel to listen to vcs, go through sound files until it hears its name, then it listens for a little bit before putting the input into chatgpt, then chatgpt's output into elevenlabs for it to talk back

#

idek if pycord can play files locally 😭

sage tendon
#

damn

#

elaborate

silk oriole
#

homebrew alexa

#

i already have chatgpt and elevenlabs integrated with my bot and with each other, the final evolution is allowing it to work inside of a VC

sage tendon
#

isn't there the whisper model by openai that handles TTS

silk oriole
#

holy fuck

#

i did not know that but i just listened to the whisper example

#

that is INSANE

#

oh nevermind

#

i am stupid

#

i thougth the audio example was an AI voice

#

whisper is STT not TTS

#

thank you for letting me know though cuz i didn't actually have any STT model planned

sage tendon
#

a

#

mb

deft kestrel
#

help


        cur.execute("SELECT options,options_name,options_category,channel,guild_id FROM servers_info WHERE guild_id = ?", (interaction.guild.id,))  # Fetch data from the database
        data = cur.fetchall()

        labels = data[0][1].split(",")  # options_name     
        category = data[0][2].split(",") # options_category   
                        print(category_id)
                        category = self.bot.get_channel(category_id)
                        if (category is not None):
                            print(category)
                        else:
                            print("No category")
                        ticket_channel = await guild.create_text_channel(f"ticket-{member_name}", category=category,
                                                                        topic=f"{interaction.user.id}")

output:
1237421714346872883
No category
error:

#
Ignoring exception in view <MyView timeout=None children=1> for item <Select type=<ComponentType.string_select: 3> placeholder='Choose a Ticket option' min_values=1 max_values=1 options=[<SelectOption label='Buy' value='buy' description='You will buy things here!' emoji=<PartialEmoji animated=False name='💰' id=None> default=False>, <SelectOption label=' Support' value='_support' description=' Ask questions here!' emoji=<PartialEmoji animated=False name='❓' id=None> default=False>, <SelectOption label=' Giveaway' value='_giveaway' description=' if y
ou won in a giveaway you will open this' emoji=<PartialEmoji animated=False name='🎉' id=None> default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
  File "c:\Users\\OneDrive\bot\testing\.venv\Lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\\OneDrive\bot\testing\cogs\ticket_system.py", line 160, in select_callback
    await ticket_channel.set_permissions(guild.get_role(TEAM_ROLE), send_messages=True, read_messages=True, #Set the Permissions for the Staff Team
  File "c:\Users\\OneDrive\bot\testing\.venv\Lib\site-packages\discord\abc.py", line 944, in set_permissions
    raise InvalidArgument("target parameter must be either Member or Role")
discord.errors.InvalidArgument: target parameter must be either Member or Role
sage tendon
#

read

little cobalt
sage tendon
#

no?

rotund quarry
#

to make a view a cog i need to do something like this? class MyView(discord.ui.View, self):

deft kestrel
#

timout = None

#

what more

rugged lodgeBOT
#

Here's the persistent example.

deft kestrel
#

thanks

deft kestrel
# little cobalt dont crosspost pls and wtf?
class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

this is my view
and if i want it to be persistent i need to add the guild to here?

class Ticket_System(commands.Cog):

    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'Bot Loaded | ticket_system.py ✅')
        self.bot.add_view(MyView(bot=self.bot))
        self.bot.add_view(Buttons(bot=self.bot))
        self.bot.add_view(TicketOptions(bot=self.bot))

    #Closes the Connection to the Database when shutting down the Bot
    @commands.Cog.listener()
    async def on_bot_shutdown():
        cur.close()
        conn.close()
sage tendon
#

yea

#

but why do you pass it like a keyword

little cobalt
sage tendon
#

to have access to it when needed inside the view ig

little cobalt
#

you can access your bot via interaction.client?

little cobalt
#

yes you can...

deft kestrel
#

i need it in the __init__

little cobalt
#

for what?

sage tendon
deft kestrel
#

i know

deft kestrel
sage tendon
#

just pass the guild? lol

deft kestrel
# sage tendon just pass the guild? lol

like that:

    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

i mean to pass the guild

sage tendon
#

I literally have no idea what you need the bot for

#

and you were already doing that

deft kestrel
#

to get the guild in the __init__

sage tendon
#

just pass the actual guild, from within the command

deft kestrel
#

its not an command

#
class Ticket_System(commands.Cog):

    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'Bot Loaded | ticket_system.py ✅')
        self.bot.add_view(MyView(bot=self.bot))
        self.bot.add_view(Buttons(bot=self.bot))
        self.bot.add_view(TicketOptions(bot=self.bot))

    #Closes the Connection to the Database when shutting down the Bot
    @commands.Cog.listener()
    async def on_bot_shutdown():
        cur.close()
        conn.close()

class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

        cur.execute("SELECT options,options_name,options_emoji,options_description,guild_id FROM servers_info WHERE guild_id = ?", (self.guild_id,))  # Fetch data from the database
        data = cur.fetchall()

        guild = self.bot.get_guild(data[0][4])
        Emojis = (data[0][2].split(","))  # options_emoji'  
        descriptions = (data[0][3].split(","))
        labels = data[0][1].split(",")  # options_name

        options = []
        for i in range(data[0][0]):
            label = labels[i]
            description = descriptions[i]  # options_description
            Emoji = Emojis[i].strip()
            value = label.lower().strip()# Lowercase label with spaces replaced by underscores
            option = discord.SelectOption(label=label, description=description, emoji=Emoji, value=f"{guild.name}-{value}")
            options.append(option)

        select = discord.ui.Select(
            custom_id=f"{guild}-ticket_options",
            placeholder="Choose a Ticket option",
            options=options,
        )
        select.callback = self.select_callback    
        self.add_item(select)
#

and the callback of course

sage tendon
#

where are you making the view then if not in a command

deft kestrel
#

i have this:

    #Slash Command to show the Ticket Menu in the Ticket Channel only needs to be used once
    @subcommand(f"setup")
    @commands.slash_command(name="ticket", description = "Ticket menu")
    @discord.default_permissions(manage_roles=True)
    async def ticket(self, ctx,staff_role: discord.Role, member_role: discord.Role ,num_of_options: discord.Option(choices=["1","2","3","4","5"],description="choose how much options you want in your ticket system", required = "true")): # type: ignore
        cur.execute("SELECT guild_id FROM servers_info WHERE guild_id = ?", (ctx.guild.id,))
        data = cur.fetchone()
        num_of_options = int(num_of_options)
        if (data):
            view = DescriptionButton(bot=self.bot)
            embed = discord.Embed(
                title=f"{TITLE} • Ticket System",
                description="Enter the name of the options you want to have in your ticket system:",
                color= BOT_COLOR
            )
            await ctx.respond(embed = embed, view = view, ephemeral=True)    
            cur.execute("UPDATE servers_info SET options = ?, srole_id = ?, vrole_id = ? WHERE guild_id = ?", (int(num_of_options),staff_role.id,member_role.id, ctx.guild.id))
            conn.commit()                               
        else:
            view = DescriptionButton(bot=self.bot)
            embed = discord.Embed(
                title=f"{TITLE} • Ticket System",
                description="Enter the name of the options you want to have in your ticket system:",
                color= BOT_COLOR
            )
            await ctx.respond(embed = embed, view = view, ephemeral=True)                
            cur.execute("INSERT INTO servers_info (guild_id ,options, srole_id, vrole_id) VALUES(?,?,?,?)", (ctx.guild.id,int(num_of_options),staff_role.id,member_role.id,))
            conn.commit()        

but how i can pass it?

sage tendon
#

ok, one second

#

what guild are we talking about here

deft kestrel
# sage tendon what guild are we talking about here

after all the command is doing this after the buttons and that shit:

        embed = discord.Embed(
            title=f"{TITLE} • Ticket System",
            description="To Open ticket choose the option you need",
            color=discord.colour.Color.blue()
        )
        embed.set_footer(text=FOOTER,icon_url=FOOTER_URL)
        cur.execute("SELECT channel FROM servers_info WHERE guild_id = ?", (interaction.guild.id,))
        channel = cur.fetchone()[0]
        ticket_channel = self.bot.get_channel(channel)
        if ticket_channel:
            await ticket_channel.send(embed=embed, view=MyView(bot=self.bot, guild_id=interaction.guild.id))
        else:
deft kestrel
sage tendon
#

Like you want the guild the command was called from, right?

sage tendon
#

then just do DescriptionButton(ctx.guild)?

deft kestrel
#

but how i can pass it to the MyView?

sage tendon
#

idc what the name is lol, but, just pass it as a parameter lol

#

just only pass the guild, that should have everything you need, no?

deft kestrel
# sage tendon then just do `DescriptionButton(ctx.guild)`?

i have rthe descriptionsbutton:

class DescriptionModal(discord.ui.Modal):
    def __init__(self, bot, guild_id, num_of_options):
        self.bot = bot
        self.num_of_options = num_of_options
        super().__init__(timeout=None, title=f"{TITLE} • Tickets System")

        self.input_fields = []
        for i in range(num_of_options):
            cur.execute("SELECT options_name FROM servers_info WHERE guild_id = ?", (guild_id,))
            option_name = cur.fetchone()[0].split(',')[i]
            cur.execute("SELECT options_emoji FROM servers_info WHERE guild_id = ?", (guild_id,))
            option_emoji = cur.fetchone()[0].split(',')[i]
            num = f"{i + 1}{'st' if i == 0 else 'nd' if i == 1 else 'rd' if i == 2 else 'th'}"
            input_field = discord.ui.InputText(
                label=f"Enter the {num} option:",
                placeholder=f"The description for the {num} option name: {option_emoji} {option_name}",
                required=True
            )
            self.add_item(input_field)
            self.input_fields.append(input_field)

    async def callback(self, interaction: discord.Interaction):
        options = [field.value for field in self.input_fields]
        
        embed = discord.Embed(
            title=f"{TITLE} • Ticket System",
            description="To Open ticket choose the option you need",
            color=discord.colour.Color.blue()
        )
        embed.set_footer(text=FOOTER,icon_url=FOOTER_URL)
        cur.execute("SELECT channel FROM servers_info WHERE guild_id = ?", (interaction.guild.id,))
        channel = cur.fetchone()[0]
        ticket_channel = self.bot.get_channel(channel)
        if ticket_channel:
            await ticket_channel.send(embed=embed, view=MyView(bot=self.bot, guild_id=interaction.guild.id))
        else:
            print("Couldn't find")        
```'
#

and i have the my View:

class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, guild_id) -> None:
        self.bot = bot
        self.guild_id = guild_id
        super().__init__(timeout=None)

        cur.execute("SELECT options,options_name,options_emoji,options_description,guild_id FROM servers_info WHERE guild_id = ?", (self.guild_id,))  # Fetch data from the database
        data = cur.fetchall()

        guild = self.bot.get_guild(data[0][4])
        Emojis = (data[0][2].split(","))  # options_emoji'  
        descriptions = (data[0][3].split(","))
        labels = data[0][1].split(",")  # options_name

        options = []
        for i in range(data[0][0]):
            label = labels[i]
            description = descriptions[i]  # options_description
            Emoji = Emojis[i].strip()
            value = label.lower().strip()# Lowercase label with spaces replaced by underscores
            option = discord.SelectOption(label=label, description=description, emoji=Emoji, value=f"{guild.name}-{value}")
            options.append(option)

        select = discord.ui.Select(
            custom_id=f"{guild}-ticket_options",
            placeholder="Choose a Ticket option",
            options=options,
        )
        select.callback = self.select_callback    
        self.add_item(select)

    async def select_callback(self, interaction: discord.Interaction):
sage tendon
#

yea i mean just pass the guild object as a whole
there's no need to pass it both the bot and the guild id, just to then get the guild
Just pass the guild itself

deft kestrel
#

when i want to pass it i need to put the parameter in the init?

sage tendon
#
def __init__(self, guild) -> None:        
        self.guild = guild
        super().__init__(timeout=None)
#

There

deft kestrel
#

ok thanks

#

and in the self.bot.add_view in there too?

sage tendon
#

and if you need the id just do guild.id like normal

deft kestrel
#

ok

sage tendon
#

i mean tbh i have no clue how that bit of your code even works given you were not passing a guild id at all so it should've just crashed
But, yea, you need to change that too

deft kestrel
sage tendon
#

just pass None, should work i think, given that your previous code worked too, somehow

deft kestrel
sage tendon
#

how are you getting the message

#

or rather, when

deft kestrel
#

on_message

sage tendon
#

Yea, the defer is an empty message

#

Easiest way is prolly just to asyncio.sleep for a sec so that the embed is actually there

lapis dock
#

Might wait_for work?

sage tendon
#

wait for edit?

lapis dock
#

I'm not sure what event triggers between defer and message but possibly

#

Depending on the use case asyncio.sleep will not work as it can be difered for up to 15 min

sage tendon
#

No disboard's responses are quick enough
maybe sleep for 2 seconds max, but it never takes longer

deft kestrel
#

Hm, at that point might it not be better i just use on_message_edit, if that works?

sage tendon
#

no idea if that counts as an edit

#

try it

deft kestrel
#

I dont either, i cant really find any documentation on it so i'm just guessing at this point

lapis dock
#

Sleeping will always take that long tho, wait for can be sooner.

sage tendon
#

true

deft kestrel
#

Oh, it counts as an edit

#

But somehow i broke it

#

Nevermind, it works now. Now i just need to actually make it return the contents

#

And thats where i am clueless again

sage tendon
#

what do you need

deft kestrel
#

Ah, forgot to use [0]

#

Thanks you two

deft kestrel
#

help

    @discord.ui.button(label = "Move Ticket", style = discord.ButtonStyle.blurple, custom_id="move_ticket")
    async def move_ticket(self, button: discord.ui.Button ,interaction: discord.Interaction):
        
        dropdown = MoveTicket()
        view = discord.ui.View()

        guild = interaction.guild

        cur.execute("SELECT options_category from servers_info WHERE guild_id = ?", (guild.id,))
        data = cur.fetchone()[0]
        CATEGORIES = data.split(",")
        for category_id in CATEGORIES:

            if (not(category_id == " " or category_id == "")):
                category_id = category_id.strip()
                categories = interaction.client.get_channel(category_id)
                print(category_id, categories)
                if (categories is not None):
                    dropdown.add_option(label=str(categories.name), value=str(categories.id)),
                else:
                    print ("ERROR")

        print(dropdown)
        view.add_item(dropdown)
        await interaction.response.send_message(embed=discord.Embed(title="Choose a category:", color=discord.colour.Color.green()), view=view, ephemeral=True)

output:
1237421714346872883 None
ERROR
1237421715467014186 None
ERROR
1237421716662128681 None
ERROR
<MoveTicket type=<ComponentType.string_select: 3> placeholder='Select category to move this ticket to' min_values=1 max_values=1 options=[] channel_types=[] disabled=False>

#

error:

Exception has occurred: HTTPException
400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options: Must be between 1 and 25 in length.
  File "C:\Users\Assaf Cohen\OneDrive\bot\testing\cogs\ticket_system.py", line 422, in move_ticket
    await interaction.response.send_message(embed=discord.Embed(title="Choose a category:", color=discord.colour.Color.green()), view=view, ephemeral=True)
  File "C:\Users\Assaf Cohen\OneDrive\bot\testing\bot.py", line 255, in <module>
    bot.run(BOT_TOKEN)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options: Must be between 1 and 25 in length.
#

why the get_channel doesnt working?

sage tendon
#

Must be between 1 and 25 in length.

#

one of your select options is too long

deft kestrel
sage tendon
#

uh, yes, that is exactly what the error says

deft kestrel
#

there are no options because there get_channel doesnt working

deft kestrel
sage tendon
#

the channel might just not be cached
try await interaction.client.fetch_channel()

deft kestrel
#

love you thanks

deft kestrel
# sage tendon why?

and i still have a problem with the buttons and the dropdown that stop workning after i restart the bot

sage tendon
#

yea, thats normal

#

make a proper view instead of the weird thing youre doing rn and make that persistent

deft kestrel
sage tendon
#

you are just making a default view

#

thats the entire problem

#

make a proper view of your own

deft kestrel
sage tendon
#

then youre not doing it right still

deft kestrel
#

i can send you the code and you can maybe tell me where i am not wrong?

sage tendon
#

you can send it here but its too late for me rn

royal rapids
#

is there a database I can reference and attach to a variable that has a list of known primes, without destroying my pc by computing the list every time I run my program?

#
def sieve_of_eratosthenes(n):  # Array of primes to n
    prime_list = [True] * (n + 1)
    prime_list[0] = prime_list[1] = False
    for p in range(2, int(n ** 0.5) + 1):
        if prime_list[p]:
            for i in range(p * p, n + 1, p):
                prime_list[i] = False
    return [i for i, is_prime in enumerate(prime_list) if is_prime]


primes = sieve_of_eratosthenes(10000)
#

currently I am using this method, and while it works, it destroys my computational power.

lofty parcel
#

Quick google search.

royal rapids
#

right

errant trout
#

450mil 💀

lofty parcel
#

Even github struggles to load it

river bramble
#

Hey, having a problem... no slah commands are showing up in discord on my bot... just using the very simple "hello" example even ... nothing shows up for that command when I type "/"

import discord
import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot()

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(name="hello", description="Say hello to the bot")
async def hello(ctx: discord.ApplicationContext):
    await ctx.respond("Hey!")

bot.run(os.getenv('TOKEN')) # run the bot with the token
#

running that right now and "hello" does not show up at all.

#

but it does say it is ready and online.

#

This is my first time using pycord so I know I'm missing something basic... what am I missing?

deft kestrel
river bramble
#

ah, like refreshing the page?

#

kk

#

cause I definitely restarted the bot after making any changes... ... though in the past working with discord-py I found that I didn't need to actually refresh Discord's browser page to get it updated... but okay, trying.

#

okay, that worked! thanks!

sage tendon
#

it's just discord being discord

cerulean sable
#

Is there any way on Py-cord for me to view a user's bio (about me)? I can view a member's status, but what about a user's bio?

sage tendon
#

no

cerulean sable
#

Okay, thanks!

cerulean sable
#

Yes

#

Understood

river bramble
#

That really helped, also I didn't have py-cord[voice] as the docs said, so got through that too

#

now I have this but my actual audio files are blank

little cobalt
river bramble
#

so, I made sure I was using 2.5... latest distro and used pip install "py-cord[voice]"

#

still though, the audios are blank and I'm not sure why

sage tendon
#

can you show your code

river bramble
#

pretty much just example from docs...

#
import discord

bot = discord.Bot()
connections = {}

async def once_done(sink: discord.sinks, channel: discord.TextChannel, *args):  # Our voice client already passes these in.
    recorded_users = [  # A list of recorded users
        f"<@{user_id}>"
        for user_id, audio in sink.audio_data.items()
    ]
    print|(recorded_users)
    await sink.vc.disconnect()  # Disconnect from the voice channel.
    files = [discord.File(audio.file, f"{user_id}.{sink.encoding}") for user_id, audio in sink.audio_data.items()]  # List down the files.
    print([f.filename for f in files])
    await channel.send(f"finished recording audio for: {', '.join(recorded_users)}.", files=files)  # Send a message with the accumulated files.

@bot.command()
async def record(ctx):  # If you're using commands.Bot, this will also work.
    voice = ctx.author.voice

    if not voice:
        await ctx.respond("You aren't in a voice channel!")

    vc = await voice.channel.connect()  # Connect to the voice channel the author is in.
    connections.update({ctx.guild.id: vc})  # Updating the cache with the guild and channel.

    vc.start_recording(
        discord.sinks.MP3Sink(),  # The sink type to use.
        once_done,  # What to do once done.
        ctx.channel  # The channel to disconnect from.
    )
    await ctx.respond("Started recording!")
    
@bot.command()
async def stop_recording(ctx):
    if ctx.guild.id in connections:  # Check if the guild is in the cache.
        vc = connections[ctx.guild.id]
        vc.stop_recording()  # Stop recording, and call the callback (once_done).
        del connections[ctx.guild.id]  # Remove the guild from the cache.
        await ctx.delete()  # And delete.
    else:
        await ctx.respond("I am currently not recording here.")  # Respond with this if we aren't recording.


@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

bot.run(DISCORD_TOKEN)
little cobalt
#

why did you do ctx.delete() at a slash command?

river bramble
#

I didnt, it is in example

#

but sounds right

#

as problem

little cobalt
#

I wonder if you need intents for the voice channel

river bramble
#

ctx seems to be the thing deleted

sage tendon
#

thats part of default intents tho

little cobalt
#

but I dont see any intents at the code

sage tendon
#

my only idea would've been that the file isnt sent from the start, but with how pycord handles it, i dont think that can happen

little cobalt
#

so I wonder if its creating the issue

sage tendon
#

i think default intents are default if you dont pass any lol

#

but worth a try

river bramble
#

trying it now.

#

and will also try intents

#

sec

river bramble
#

seems to be what was doing it... now I get audio

errant trout
river bramble
sage tendon
elfin inlet
#

why can't I use a global variable as an option in choices?

errant trout
#

just don't define it as global

elfin inlet
#

for example, I have a list called botrolelist containing a bunch of roleIDs. I want to do choices=([discord.utils.get(role for role in botrolelist)]) in a parameter in my slash command, but it gives me a 'botrolelist is undefined' error for some reason. Botrolelist is a global variable (I'm only using this bot in one server)

sage tendon
#

just put it in some file and import it

#

global vars are never a good idea

elfin inlet
#

I know but I'm using botrolelist in a lot of places

#

the bot is just going to be in one server

sage tendon
#

then import it

elfin inlet
errant trout
#

if it's an issue with global vars it's hard for us to help, they're known to cause issues with improper usage which is why we typically recommend to not use them at all