#General Help

1 messages ยท Page 29 of 1

slow dome
#

discord's limit of integers are between -2^32 and 2^32

#

so any number above or below is invalid

slender lintel
#

so i can't?

slow dome
#

take a string or just take a user object

slender lintel
#

if i do discord.User as type. Could it take the ID?

slow dome
#

maybe

wide cloak
#

are there interaction cooldowns?

slender lintel
#

how to send a second message after await ctx.responce

slow dome
#

b!rtfm pyc followup.send

open bearBOT
slow dome
#

b!rtfm pyc context.followup

open bearBOT
slow dome
#

b!rtfm pyc applicationcontext.followup

open bearBOT
slow dome
#

b!rtfm pyc followup

open bearBOT
burnt quiver
#

uh?

    bot = discord.Bot(intents=intents)
AttributeError: module 'discord' has no attribute 'Bot'

edit: needed to install py-cord==2.0.0rc1, default will install to v1.7.3

worn ruin
#

Hello there, in the Discord API documentation, application command option type can be one of 11 values. (https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type)
Value 8 is ROLE (= discord.Role in pycord), which works as intended.
I don't see any existing type for a list of role, which would correspond to list[discord.Role] in pycord.
Does anybody know of any workaround?

My last resort would be to code an autocomplete showing all roles and leaving the option type as a str but if it was a built-in solution I'd rather use it hehe.

Discord Developer Portal

Integrate your service with Discord โ€” whether it's a bot or a game or whatever your wildest imagination can come up with.

fair anvil
#

How do I define VoiceClient? My bot is in a voice channel but throws "NameError: name 'VoiceClient' is not defined"
when trying to execute the following code:

voice.play(discord.FFmpegOpusAudio("file.mp3"))```
What am I doing wrong?
azure quest
#

If you're using this through a command and have ctx parsed then you can get the discord.VoiceClient for that specific guild through ctx.voice_client

unkempt iron
#

Hey, what's the time out if you do use defer on a command ?

unkempt iron
keen warren
#

Cane were help me? #994010481918492732 message

static edge
#

do role members api side not instantly update? when i do ctx.guild.fetch_roles() it says the role is empty of members, but has members in it on the server UI?

#

after some testing it looks like it can only see itself as a member?

#

yeah i feel like i'm going crazy, even after giving it admin/all the scopes i could think of i still can't see any other users when doing fetch_roles()

slender lintel
#

Why do you use fetch_roles when it's already cached tho

static edge
#

in the hope that it would do something different

slender lintel
#

TT_wmpandaThinkOwO I don't get you

static edge
#

caching doesn't always work. i remember there being issues with message content as well

#

at any rate i just tried the cached version and it has the same result

#

does seeing other members through roles.members require specific permissions?

slender lintel
#

I don't believe so, it works fine for me

#

try turning on all the intents PES2_Shrug not sure if that will work

static edge
#

yeah i turned all intents on, tried different scopes... could you show me the code working for your bot?

#

and are you on rc1?

#

after further investigation output is the same between different releases. i'll make a thread in a minute unless anyone has ideas for why i can't retrieve members from roles

craggy rapids
#

Btw how to make all button on a class like disabled?, Using self.stop() only make the buttons not responding

sudden path
#

for child in self.children:
child.disabled = True

await interaction.response.edit_message(view=self)

slender lintel
#

is there a way to find where the error is easily

#

since i cannot find it

sudden path
#

Go over your commands and check the names

slender lintel
#

yo i found it

burnt quiver
#

can an ephemeral reply be edited to non-ephemeral? i have a step that has to take place after a command is ran, but I don't want it to clutter chat, nor do I want other users to be able to mess with any components on it

sterile anvil
#
  async def webhook(self,ctx,member:discord.Member,*,reason):
    await ctx.message.delete()
    webhook = await guild.text_channels[0].create_webhook(name='Programx',avatar=None,reason='Bot Webhook')
    url = member.avatar.url
    async with aiohttp.ClientSession() as ses:
        
        webhookm = Webhook.from_url(webhook.url, session=ses)
        
        await webhookm.send(reason, username=member.name)
    ```
For this code, it creates a webhook every time the command is executed at the channel that the command is executed. Is there anyway to just create the webhook once and fetch the webhook afterwards without making a new one every time the command is executed?
fair anvil
#

Why isn't on_message_delete event firing? i've reduced my code to

print('hello world')```
but when I delete a message there's no output in the console. all intents are properly enabled and on_message works, so i'm not sure what i'm doing wrong.
keen warren
#

Cane were help me? #994010481918492732 message

latent mason
#
discord.errors.ExtensionNotFound: Extension 'errors' could not be found
#

even though i made the file it doesn't work

#

anyway this is the code

#
import discord
from discord.ext import commands


class Error(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} is Ready!\n----------------------")

    @commands.Cog.listener()
    async def on_error(self, ctx: commands.Context, *, error):
        if isinstance(error, Exception):
            await ctx.send(f'{error.__name__}\n{error}')


def setup(bot=commands.Bot):
    bot.add_cog(Error(bot))
#

nvm I figured it out

wicked ferry
#

# /usr/local/bin/python3.10 /root/Bots/PublicBots/Bambus/main.py Traceback (most recent call last): File "/root/Bots/PublicBots/Bambus/main.py", line 32, in <module> bot.load_extension(f'/root/Bots/PublicBots/Bambus/cogs.{cog}') File "/usr/local/lib/python3.10/site-packages/discord/cog.py", line 783, in load_extension spec = importlib.util.find_spec(name) File "/usr/local/lib/python3.10/importlib/util.py", line 94, in find_spec parent = __import__(parent_name, fromlist=['__path__']) ModuleNotFoundError: No module named '/root/Bots/PublicBots/Bambus/cogs'

#

whats the problem?

wicked ferry
solar berry
#

Is there a way to check if an extension is already loaded?

#

nvm I read the wrong part of the docs

deep grail
#

Is the init function triggered every time cogs are loaded even if they've just been unloaded or is it only on the first time a cog is loaded?

deep grail
#

Figure out what the current working directory is and then load your cogs relative to that

#

So do print(os.getcwd())

#

And then supply any missing folders in the path for the cog when you use load_extension

forest saffron
#

how can I solve the problem that the webhook doesnt has a token associated with it

frigid elm
#

TypeError: issubclass() arg 1 must be a class

frigid elm
past gate
#

send your code

#

and the full error

verbal pecan
#

hey is it necessary for bot to have admin privilege to disable default role view for particular channel by doing this ? await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)

hoary moss
#

Hi, how do you create a webhook?

#

Am struggling to finds the docs on creating it so am coming here to see if anyone knows how ๐Ÿ‘€

#

I meant the bot creating the webhook, not the user creating the webhook

frigid elm
# past gate send your code
@commands.slash_command(name="ticket",description="Creates a tickets panel")
    async def ticket(self,ctx,channel: Option(discord.TextChannel,"In which channel",required = False),helpers: Option(discord.role,"Helpers",required=False)):
        
        
        
         
        button = Button(emoji=":tickets:",style=discord.ButtonStyle.green,label="Ticket")
        view = View()
        view.add_item(button)
        
        if channel is None:
            channel = ctx.channel

        async def btncallback(interaction):
            guild = ctx.guild
            overwrites = {
                guild.default_role: discord.PermissionOverwrite(view_channel=False),
                interaction.user: discord.PermissionOverwrite(view_channel=True)
            
            }
            global new_channel
            new_channel = await guild.create_text_channel(f"{interaction.user.name}'s ticket",overwrites=overwrites)
        button.callback = btncallback
        em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Tickets",description=":tickets: Click the button below to make a ticket!")
        await channel.send(embed=em,view=view)
        await new_channel.send("test")```
#

Exception has occurred: ExtensionFailed
Extension 'cogs.support' raised an error: TypeError: issubclass() arg 1 must be a class
File "C:\Users\amito\Desktop\tests\cogs\support.py", line 6, in <module>
class Support(commands.Cog):
File "C:\Users\amito\Desktop\tests\cogs\support.py", line 16, in Support
async def ticket(self,ctx,channel: Option(discord.TextChannel,"In which channel",required = False),helpers: Option(discord.role,"Helpers",required=False)):

frigid elm
#

oh ty

frigid elm
slender lintel
#

Like edit the role?

frigid elm
#

yh

slender lintel
#

b!rtfm pyc discord.Role.edit

open bearBOT
frigid elm
#

also i would have to put the helper role for every guild in a db right?

slender lintel
#

Prob ye

#

The role id

frigid elm
#

yh

#

alright ty

atomic thistle
#

While sending a message, if i give a list with just 1 embed in the embeds parameter instead of giving it through the embed parameter, will there be any difference?

limpid schooner
wicked ferry
#

Traceback (most recent call last): File "/root/Bots/PublicBots/Bambus/main.py", line 31, in <module> bot.load_extension(f'/root/Bots/PublicBots/Bambus/cogs/{cog}') File "/usr/local/lib/python3.10/site-packages/discord/cog.py", line 785, in load_extension raise errors.ExtensionNotFound(name) discord.errors.ExtensionNotFound: Extension '/root/Bots/PublicBots/Bambus/cogs/fun' could not be found.

deep grail
#

You have to use . Instead of /

#

Also send the output of os.getcwd

#

@wicked ferry

leaden mesa
#

how do I get my code to continue after a modal is canceled?
It just stops processing additional commands, appearing to the user like the bot has stopped until, timeout is reached
I could set the modal timeout to trigger some loop but I'd rather not if there's an alternative option

#

it does appear this is a discord limitation, but I wondered if there was a workaround

slow dome
#

The workaround is to probably open an issue (if doesn't exist) or elaborate on the existing issue on the discord api docs

slender lintel
#
     channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)```
error:
```Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\user\Desktop\Ayu Bot\main.py", line 250, in button_callback1
    channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1170, in create_text_channel
    data = await self._create_channel(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1051, in _create_channel
    "id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'```
deep grail
#

Alright thanks

steep verge
#

with @commands.is_user(...), how do pass in multiple user IDs?

wicked ferry
deep grail
# wicked ferry /root

try doing

os.chdir("/root/Bots/PublicBots/Bambus/")

Before loading your cogs with:

bot.load_extension("cogs.example_extension")
wicked ferry
#

youre a real legend

deep grail
#

Lol thanks

deep grail
wicked ferry
#

on a kvm server

#

i rented one

deep grail
#

Are you developing and hosting on that one server?

noble umbra
slender lintel
#

hmm i have the exact same code in a separate file and it works perfectly fine there..

fair anvil
stable torrent
#

can you show the code?

#

ping me when you are here

fair anvil
#

@stable torrent this is the relevant code. i have intents set as discord.Intents.all() and on_message() works which if im not mistaken requires the same intent.

print('hello world')```
this code, to my understanding, should print 'hello world' when a message is deleted, but it doesnt. ive tried deleting many messages in several channels.

Thank you so much for the help, by the way!
stable torrent
#

are you sure bot has permissions to view those channels?

fair anvil
#

yes, and it responds to on_message() events in the same channels appropriately

stable torrent
#

are you up to date?

#

try pip install git+https://github.com/Pycord-Development/pycord

fair anvil
#

just tried that, it uninstalled 'py-cord-2.0.0b5' and installed 'py-cord-2.0.0rc1', but still no luck

stable torrent
#

are you subclassing bot by any chance?

#

i'd like to see main file/bot file actually

fair anvil
#

will do! is pastebin ok?

stable torrent
#

yep

burnt quiver
#

is there a quick way to check permissions for @/everyone?

stable torrent
burnt quiver
#

yeah, as in the "role" that shows up as @/everyone in the roles list

stable torrent
#

everyone role has same id as guild, hope this helps

burnt quiver
#

gotcha, thanks

fair anvil
supple ravineBOT
stable torrent
#

you forgot to put decorator for on_message_delete

burnt quiver
stable torrent
burnt quiver
#

alright, thank you!

fair anvil
stable torrent
#

you're welcome

#

its okay

#

๐Ÿ‘๐Ÿป

frigid elm
#

im making a ticket comman nd i was wondering how would i send a message in the new made channel

past gate
#

get the channel id pass it to get_channel() and send the message

proud geode
#

How can I check if a channel exists?

worthy basin
#

get_channel if that is None use Guild.fetch_channels than check if the channel is in that list. If it is not it does not exist.

proud geode
#
if f"general-{interaction.target.name}" in interaction.guild.text_channels:```
#

would this work?

worthy basin
#

I think you have to fetch the channels if it is not in cache. Because discord does not send the channels when you look at the guild.
So you might have to add this in the else

if f"general-{interaction.target.name}" in interaction.guild.fetch_channels():
worthy basin
proud geode
#

Yea sorry for that :(

thorn verge
#

How do I add color to an embed?

frigid lark
thorn verge
#
from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
sudden path
#

Well

#

Self explanatory

spring wharf
#

What's the best way to make buttons work after restarting the bot?

sudden path
#

Persistent views.

supple ravineBOT
#

Here's the persistent example.

spring wharf
#

Thanks

spring wharf
thorn verge
thorn verge
#

How do I put a description to the slash command?

sudden path
#

description= in the decorator.

thorn verge
#

Thanks

hazy tundra
#
  File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\bot.py", line 1147, in on_connect  
    await self.sync_commands()
  File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\bot.py", line 770, in sync_commands
    await self._bot.http.bulk_upsert_command_permissions(self._bot.user.id, guild_id, guild_cmd_perms)      
  File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\http.py", line 359, in request     
    raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed```
#

Is this a bug?

sudden path
#

Update to rc1

hazy tundra
#

oh

spring wharf
#

Do I need to run the persistent view at boot up

#

or can I just make a command

#

like .activate

#

or something

sudden path
#

A command would work too ig.

spring wharf
#

ImportError: cannot import name 'SuggestionButtons' from partially initialized module 'cogs.suggest' (most likely due to a circular import) (/home/container/cogs/suggest.py)

#

Brilliant

#

How am I supposed to do it then

#

I've just added it to the @bot.event
on_connect

sudden path
#

You add persistent views on on_ready

spring wharf
#
@bot.event
async def on_ready():
    bot.add_view(SuggestionButtons())
    bot.persistent_views_added = True```
#

Should this work?

#

I've imported the SuggestionButtons class from suggest.py

#

Same error

sudden path
#

Well, you should be able to find a way to prevent circular import.

prisma pasture
#

is there anything like ctx.defer() but for buttons?

#

my button interaction takes longer than 3 seconds

slender lintel
#

b!rtfm pyc defer

slender lintel
#

b!rtfm pyc interaction.response.defer

open bearBOT
slender lintel
#

Hm

slender lintel
#

b!rtfm pyc interactionresponse.defer

slender lintel
#

oh there we go

#

@prisma pasture there you go

slow dome
#

and you get interactionresponse from interaction.response

supple ravineBOT
#

Couldn't find documentation for discord.commands.ApplicationContext.defer.

prisma pasture
slender lintel
#

b!rtfm pyc followup

open bearBOT
prisma pasture
slender lintel
#

Currently on the car and safari ainโ€™t loading

slow dome
thorn verge
#

How do I add buttons to my message?

supple ravineBOT
#

Here's the button roles example.

thorn verge
#

thanks

sudden path
#

If I use interaction.channel.id when the button is in a thread, will I get the thread ID or will it return None?

clever lava
#

guys help

#
@bot.slash_command(guild_ids=testbot, description="Mostra as estatรญsticas de alguem")
async def stats(ctx, player : Option(str, description="Nome do jogador")):

    baseurl = "https://mush.com.br/api/player/"
    endpoint = player

    r = requests.get(baseurl + endpoint)

    data = r.json()

    rank = data['response']['rank']['title']

    first_login = data['response']['first_login']
    last_login = data['response']['last_login']

    timestamp = first_login[:10]

    await ctx.respond(f"<t:{timestamp}:d>")
#

this command manipulates an API here

#

here it is

#

first_login and last_login

#

they are timestamps

#

but it have more than 10 numbers

#

so the timestamp is wrong

#

i want to remove de aditional numbers

#

the last 3

#

i cant do .strip bcuz its an int value

sudden path
#

divide by 1000?

#

Or convert it to a string a strip it? Whatever you prefer

clever lava
#

oh

#

yes

#

ty

#
    await ctx.command.invoke(ctx)
  File "C:\Users\Davi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 357, in invoke
    await injected(ctx)
  File "C:\Users\Davi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 134, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

wtf

#

unknow interaction??

#

how

sudden path
#

Most likely you took too long to respond ig.

clever lava
#

my terminal is soo laggy ngl

#

idk what happened

cunning dragon
past gate
#

Also think about deferring the response if it takes too long

spring pawn
#

Hey, I have a command that produces a graph and sends it in response to a slash_command. Using ctx.respond(file = discord.File(graphPath))sends an error, whereas ctx.send(file = discord.File(graphPath))sends the file but also a message saying "The Application did not respond". What command should i use to respond and send a file?

#

should I just do like an invisible ctx.respond first and then send file via ctx.send_followup?

slender lintel
vapid forge
#

Lol we just figured out that this was due to importing the wrong thing

spring pawn
#

ctx.response.defer() does work, but then the message "bot is thinking" persists for a while. I kinda prefer a ctx.respond message and then followup with file

spring wharf
#

Any dropdown menu examples?

supple ravineBOT
#

Here's the dropdown example.

low sparrow
#

Hi.
How to make mypy happy about channel: Option(TextChannel)?

lusty dragon
#

How do i set embedded activities?

#

i rlly cant find anything that helps me do it

wicked ferry
#
class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(discord.ui.InputText(label=":name_badge: USERNAME + HASHTAG", placeholder="e.g: Wumpus#0000"))
        self.add_item(discord.ui.InputText(label=":underage: ALTER", placeholder="e.g: 187"))
        self.add_item(discord.ui.InputText(label=":high_brightness: WARUM BEWIRBST DU DICH?", placeholder="e.g: Bin einf cool ka", style=discord.InputTextStyle.long))
        self.add_item(discord.ui.InputText(label=":computer: HAST DU ERFAHRUNG?", placeholder="e.g: Ja hab Mee7 gecodet!", style=discord.InputTextStyle.long))
        self.add_item(discord.ui.InputText(label=":thinking: WARUM GENAU DU?", placeholder="e.g: Ich kann 90s in Fortnite!", style=discord.InputTextStyle.long))


    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Bewerbung!", colour = (discord.Colour.random()))
        embed.add_field(name=":name_badge: USERNAME + HASHTAG", value=self.children[0].value, inline=False)
        embed.add_field(name=":underage: ALTER", value=self.children[1].value, inline=False)
        embed.add_field(name=":high_brightness: WARUM BEWIRBST DU DICH?", value=self.children[2].value, inline=False)
        embed.add_field(name=":computer: HAST DU ERFAHRUNG?", value=self.children[3].value, inline=False)
        embed.add_field(name=":thinking: WARUM GENAU DU?", value=self.children[4].value, inline=False)
        channel187 = bot.get_channel(989603932995199026)
        await interaction.response.send_message(f"{interaction.user.mention} Bewerbung wurde ans Team gesendet!")
        await channel187.send(embeds=[embed])


@bot.slash_command(description = "test modal uwu ")
async def test(ctx):
    modal = MyModal()
    await ctx.interaction.response.send_modal(modal)```
Error:

```py
Traceback (most recent call last):
  File "C:\Users\Noe\PycharmProjects\Bambus bot\venv\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Noe\PycharmProjects\Bambus bot\venv\lib\site-packages\discord\commands\core.py", line 357, in invoke
    await injected(ctx)
  File "C:\Users\Noe\PycharmProjects\Bambus bot\venv\lib\site-packages\discord\commands\core.py", line 134, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Modal.__init__() missing 1 required keyword-only argument: 'title'```
#

how to fix

proud geode
#

discord.Color.color()

proud geode
#

you mean this?

#

if u want both Text and Voice

#

u use Union[discord.TextChannel, discord.VoiceChannel]

supple ravineBOT
#

Here's the persistent example.

wicked ferry
#

i did self.titel and did it in the super init

#

nothing works

proud geode
#

it is title not titel

thorn verge
low sparrow
#

Slash command btw

halcyon cairn
#

no, you need option.

slender lintel
#

Hi I fetched a message object and now I want to get the exact embed from the message and store it. How can I do this? I tried doing: embed = message.embed but it didn't work

#

Getting this error: AttributeError: 'Message' object has no attribute 'embed'

proud geode
#

it works for me with no Option

#

ยฏ_(ใƒ„)_/ยฏ

low sparrow
frigid lark
halcyon cairn
#

odd. Never did for me. then again, I haven't tried it since beta.

halcyon cairn
frigid lark
sudden path
#

b!rtfm pyc Message.embeds

open bearBOT
sudden path
#

Docs are useful.

low sparrow
# proud geode it works for me with no Option

Can you give me example code?
Tried with ```py
@bot.slash_command()
async def test(ctx, chan: discord.TextChannel):
await ctx.respond(repr(chan))

But it doesn't show channel selection and `chan` is always None
#

Nvm, it actually DOES work

#

sadcatthumbsup discord didn't refresh command arguments

#

I hate that

limpid ginkgo
#

is there any way to hide the slash commands from guilds? so it only works in dms.

slender lintel
#

how would i make a slash command group only show to a certain role, i only see checks=[commands.is_owner().predicate], in the docs

slender lintel
frigid lark
#

you can use them in dmยดs

slender lintel
#

ah alr

proud geode
#

or am I just bad at python

worthy basin
graceful robin
#

Can I use the Pycord logo?

slow dome
#

for?

graceful robin
#

in an image

#

thumbnail

slow dome
#

right, probably fine

hazy tundra
#

how do i refer to a method in a cog from a discord.ui.view class?

#

i dont have the bot object and thus cant initiate an instance

slow dome
#

what is inside what

hazy tundra
#

i have a seperate file from the main file with the cog in it

#

to use discord.ui.view i also have a seperate class there with the embed

#

how do i use a method inside the cog from the embed class

slow dome
#

why can't you create the class inside the cog

hazy tundra
#

i thought that was not good practice

slow dome
#

It's only bad practice when you use more or unreadable code to do the same thing.

scenic leaf
#

how would i remove something after a certain word in a string ?

basicly name returns
naruto-episode-1
but i want to remove the -episode-1 so i get just naruto
how would i remove that ?
i tried with .split but it idnt work
i had this animename = name.split("-episode-")[-1]

hazy tundra
#

Okay

#

thank you

scenic leaf
#

but it left the episode numbed

slow dome
hazy tundra
#

.replace()

scenic leaf
#

okey but what about the episode number that one changes

slow dome
#

and item 0 of that list would be naruto

hazy tundra
#

o

#

yeah then use split

slow dome
#

while item 1 would be the episode number

scenic leaf
#

so name.split[0]

slow dome
#

no

#

name.split("-episode-")[0] is the name
name.split("-episode-")[1] is the episode number

scenic leaf
#

okey ill try that

#

nope it still says the episode number Xd

#

an no i cant do name.split("-episode-1")[0]
Xd

#

cause the episode number changes

#

okey i fixed it Xd

#

Thanks for the help !!

hazy tundra
#

do i use inheritance?

slow dome
#

well you can just use super() to get the method you want

languid hollow
#

I'm guessing it's impossible to know if a user has clicked a link button?

#

since link buttons don't have interaction_check

hazy tundra
pine musk
#

yo! I'm trying to use https://github.com/Pycord-Development/pycord in my discord bot that uses it as a requirement. How would I have the server automatically install the developer version from the requirement.txt file if I'm hosting externally?

I just want the cd pycord then pip install -U .[voice]

#

I tried adding "git+https://github.com/Pycord-Development/pycord" but this wasn't enough for the setup script inside of the pycord directory

crimson gale
#

pip freeze > some_file.txt with the github version installed and inspect it to see the syntax for using git in requirements.txt

pine musk
#

ahh it's referencing the local file path

py-cord @ file:///C:/Users/username/PycharmProjects/test-project/pycord

low sparrow
languid hollow
crimson gale
#

yep

#

link buttons cant have any functionality attached to them

#

thus its impossible to see if someone pressed the button

pine musk
#

mb if I should start a convo post, new to this server โค๏ธ

weary palm
#

how do I go by forcing it to go to 1 row down after "Quest Completions"?

slender lintel
weary palm
#

so where do I set that

#

OH i found it

slender lintel
#

Oh ok

torpid siren
#

hey is there a way to know who changed someone's nickname in an event

#

i could make it check the logs every time but is there a better way?

copper stag
#

Is there a keyword argument for intents for py ext.commands.bot

#

There is an attribute but I don't seem to find it anywhere (the keyword argument)

worthy basin
#

You need the message content intent

errant verge
#

if i have an async function that does some stuff and returns some variables, how can i get these variables inside of my command function?

#

is there something similar to if it was a regular function i'd do a,b,c = function()

past gate
#

yeah its called await

copper stag
slender lintel
errant verge
slender lintel
#

hello,
i have a problem
im new to pycord
i worked with discord.py before
File "/Users/tommy31/Desktop/py-tickets/main.py", line 3, in <module>
from discord.commands import permissions, slash_command, CommandPermission, SlashCommandGroup, Option
ModuleNotFoundError: No module named 'discord.commands'
im getting this error

#

Code smh

#

bruh

hearty rainBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

  2. Install py-cord
    python -m pip install py-cord

Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.

Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

Updating to release candidate:
pip install py-cord==2.0.0rc1

slender lintel
#

Check if it is on release candidate

#

You might be on py-cord version 1.7.3

#

That version doesnโ€™t support interactions and is just a fork of discord.py

#

ok

#

To check what version do pip freeze in terminal

#

i have the newest version

#

the 2.0.0rc1 one

frigid lark
#

do you have something else installed?

slender lintel
slender lintel
slender lintel
#

just pycord

clever lava
#

there is a way to edit messages via interaction?

#

like we have interaction.response.send_message as well

slender lintel
#

interaction.response.edit_message()

clever lava
#

oh ty

clever lava
#

guys help

#

i'm having trouble with API requests

#
@bot.slash_command(guild_ids=testbot)
async def api(ctx):
   
    url = "https://mush.com.br/api/player/Panquekoo"

    api = requests.get(url)

    data = api.json()

    rank = data['response']['rank']['title']

    await ctx.respond(rank)
#

its an simple exemple

#

but the bot don't give any response

#

and like 20 secconds later appears a error message on console

#

Error 404 not found

#

unknow interaction

worthy basin
#

check that your URL is correct

#

It cant find that endpoint

clever lava
#

IT IS

crimson gale
#

also defer the interaction if it takes longer than 3 seconds

clever lava
#

capslock

#

srry

crimson gale
#

and use aiohttp instead of requests

#

requests is a blocking library

clever lava
#

hm

#

ok

crimson gale
#

aiohttp is a dependency of pycord so it should already be installed

clever lava
#

oh nice

upbeat hill
#

there a way to remove all roles from a member and store all the role ids in a list

upbeat hill
#

sorry

#

im testing out just getting a role list ive only got 2 roles but there is 3 in the list

upbeat hill
# slow dome we know that there is a way

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code:
10011): Unknown Role

getting this error when trying to remove roles

#

not sure how to go about fixing it

clever lava
#

can someone teach me how to use aiohttp

crimson gale
upbeat hill
#

how do you turn a coma seperated string back into a list

clever lava
#

ok

upbeat hill
# sudden path .split(",")

tried that but in getting it from a sql query and get this error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'sqlite3.Cursor' object has no attribute 'split'

sudden path
#

Your cursor should return something if you're sending a query(?

#

I don't know sql

worthy basin
upbeat hill
worthy basin
#

Use cursor.fetch in place of cursor.execute

upbeat hill
worthy basin
#

Oop, fetchall I use a different lib than you

upbeat hill
worthy basin
#

Yes, it might be nested in a list tho.

upbeat hill
#

would it be .execute then x = cursor.fetchall() ?

worthy basin
#

Ah yes sorry. Also now realizing that you only are returning one row so fetchone would be the best. :/ sorry for making it confusing

upbeat hill
#

no worries :) im learning

upbeat hill
worthy basin
#

A row object is similar to a dict. with the columns being the keys so doing.
roleList["RoleList"] will give you the value of that column. (This is so if you fetch more than one column you can get the right one.)

upbeat hill
upbeat hill
#

and ideas?

gilded widget
#

it doesnt exist anymore with the introduction of 2.0

#

try avatar.url

slow dome
#

instead of avatar, use display_avatar

#

yeah

gilded widget
#

should fix that

slow dome
#

still need the .url

gilded widget
#

.url

#

member.display_avatar.url

errant verge
supple ravineBOT
slow dome
#

icon.url

#

congrats

slender lintel
#
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (/home/runner/MetallicFrontDesign/venv/lib/python3.8/site-packages/discord/channel.py)
sudden path
slender lintel
#

i never installed it

#

but ill try that

slender lintel
#

which ones?

slow dome
slender lintel
slow dome
slender lintel
#

ill show you the ouput when i unistall them

slow dome
#

are you on replit

slender lintel
#

no

#

its a online linux vm

#

that i have

#

hm

#

i see what happended

#

i had discord in my requirements.txt

#

so it kept installing

slow dome
#

nice

#

also some of your dependencies are outdated

rugged needle
fair anvil
#

I have two bots. One I use to test code and one that I run the tested and working code on. I created a command that shows the user's activity and it fully works on my test bot, but when the code is copy and pasted to the main bot the activity stops working. The attached image shows the difference when run, despite having the exact same code. I checked to make sure and it seems like both of my bots have the same intents enabled so I'm not sure whats wrong.

gilded widget
#

an issue somewhat like that existed prior to #1365 on the repo but that PR isn't in 2.0.0rc1

#

you should probably update to the git master branch

fair anvil
#

Yeah I'm currently on 2.0.0rc1

gilded widget
#

yeah, i'd start by updating to the git repo and go from there

heavy flint
#

Im trying to get the message id of a response to a slash command and am doing message = await ctx.respond(embed=embed) but message.id doesn't return the right id

fair anvil
gilded widget
fair anvil
#

yes

gilded widget
#

run this: py -3 -m pip install git+https://github.com/Pycord-Development/pycord

fair anvil
gilded widget
#

tbh no, haven't heard of anything like that. could be failure to receive data on the other pc however not sure why that would happen

#

does your pip list look identical on both machines?

fair anvil
#

the one with a 1 drawn in is the machine that doesn't seem to work

heavy flint
#

i don't see any way to fetch interaction

#

unless im tripping

#

okay so according to my research

#

u literally can't do this

#

cuz my end goal is to edit the slash command response

gilded widget
gilded widget
#

message = await ctx.respond(embed=embed) will let message be an Interaction object, assuming its the first response

#

however, message.id will give you the Interaction object's ID, not the message

#

best bet to get the message:

interaction = await ctx.respond(embed=embed)
msg = await interaction.original_message()
latent mason
#

how do I use bridge commands

#

it is cluttering to understand it

#

can someone give an example or smth?

unique glacier
dusk gale
#

If I use @tasks.loop to run a background task every x minutes, do I still need to tell the program to asyncio.sleep until it's supposed to run again? It feels like I'm doing things double currently.

worthy basin
#

No, tasks.loop automatically waits

dusk gale
#

Perfect, thanks!

smoky path
#

Is it possible make a listener for auditlog?

upbeat hill
#

how do you loop through a list of intigers and give the position
output:
added roles False out of30
code:

worthy basin
dusk gale
spring pawn
#

Any idea why await ctx.respond and await ctx.response.defer() both might produce "Error 404 Unknown Interaction" but ctx.send() still works?

worthy basin
worthy basin
upbeat hill
dusk gale
worthy basin
dusk gale
clever lava
#

guys help

#

i cant learn how to use aiohttp api requests

#

anyone recommend a yt tutorial?

#

one that is decent

spring pawn
worthy basin
#

yup, always make ctx.response.defer() the first thing in your command if it is going to take more than 3 seconds.

slow dome
#

ctx.defer() exists

#

but I suppose they do the same thing and ctx.defer is really just a shorthand for ctx.interaction.response.defer

wild thunder
#

this is my slash command's code, i am trying to use the async def on_timeout coroutine but it doesnt seem to work, am i indenting in the wrong place?

slow dome
wild thunder
slow dome
#
            view = View(timeout=10)
            view.on_timeout = on_timeout
            yes_button.callback = yes_callback
            no_button.callback = no_callback
            view.add_item(yes_button)
            view.add_item(no_button)
wild thunder
#

oh

slow dome
upbeat hill
#

is there a way to change the bot responce when defering from bot is thinking to something else?

upbeat hill
#

thx

slow dome
#

np

wild thunder
# slow dome you also need to override the on_timeout that's built in
async def on_timeout(interaction):
                yes_button.disabled = True
                no_button.disabled = True
                await interaction.response.edit_message(view=view)
                await interaction.response.send_message("e")
                    

                
            view = View(timeout=10)
            view.on_timeout = on_timeout
            yes_button.callback = yes_callback
            no_button.callback = no_callback
            view.add_item(yes_button)
            view.add_item(no_button)
#

just did that but it didnt work

slow dome
#

define didn't work

wild thunder
# slow dome define didn't work

so the timeout is working and what i mean is after the 10 seconds, the buttons dont respond leading to an interaction failed error, which is expected and mentioned on the guide as well that if the on_timeout coroutine isnt present then after the specified time the buttons will simple stop working. so the timeout is working just fine, but whatever actions i want the bot to take after the timeout which is specified on the on_timeout coroutine isnt happening

slow dome
#

because there is no actual interaction

wild thunder
#

like this code here in the guide

class MyView(discord.ui.View):
    async def on_timeout(self):
        for child in self.children:
            child.disabled = True
        await self.message.edit(content="You took too long! Disabled all the components.", view=self)

    @discord.ui.button()
    async def button_callback(self, button, interaction):
        ...

@bot.command()
async def button(ctx):
    await ctx.send("Press the button!", view=MyView(timeout=30))
slow dome
slow dome
wild thunder
slow dome
#
async def on_timeout(interaction):
  for children in view.children:
    children.disabled = True
  await interaction.edit_original_message(content = "e", view=view)
wild thunder
# slow dome ```py async def on_timeout(interaction): for children in view.children: ch...

still didnt work
the ss above after the 10 secs timeout
the code:

async def on_timeout(interaction):
                for children in view.children:
                    children.disabled = True
                await interaction.edit_original_message(content = "e", view=view)
                    

                
            view = View(timeout=10)
            view.on_timeout = on_timeout
            yes_button.callback = yes_callback
            no_button.callback = no_callback
            view.add_item(yes_button)
            view.add_item(no_button)
#

am i supposed to like rename children to button? and in the view.children to my button's name?

slow dome
clever lava
#

how does it call

#

discord.Image or something

#

i need this

supple ravineBOT
#

Here's the slash options example.

clever lava
#

ty

wild thunder
# slow dome no, view.children is a list of all the buttons and select menus in your view

well it still didnt work me , i have kept this is as the code and the timeout stuff still doesnt work

async def on_timeout():
                for children in view.children:
                    children.disabled = True
                await interaction.edit_original_message(content = "e", view=view)
                    

                
            view = View(timeout=10)
            view.on_timeout = on_timeout
            yes_button.callback = yes_callback
            no_button.callback = no_callback
            view.add_item(yes_button)
            view.add_item(no_button)
slow dome
wild thunder
slow dome
wild thunder
#

if i just use a class unexpectedly for just the timeout feature wont it mess with the rest of the code in the command

slow dome
#

Do the button callbacks even work

wild thunder
#

only timeouts are giving an issue

slow dome
wild thunder
slow dome
#

you don't need to?

wild thunder
#

how?
i have no idea how i can fit in the subclass in my view

slow dome
#
yes_button.callback = yes_callback
no_button.callback = no_callback

class MyView(discord.ui.view):
  def __init__(self):
    super().__init__(timeout=10)
    self.add_item(yes_button)
    self.add_item(no_button)

  async def on_timeout():
    for children in self.children:
        children.disabled = True
    await interaction.edit_original_message(content = "e", view=self)
#

literally only your view needs to change

keen shore
#

is there a way

#

to get a message count of a channel?

keen shore
#

oi thanks

clever lava
#
@bot.slash_command(guild_ids=testbot)
async def api(ctx):

    async def main():
        async with aiohttp.ClientSession() as session:
            async with session.get(f'https://mush.com.br/api/player/{player}') as response:
                print("Status:", response.status)

                data = await response.json()

                rank = data['response']['rank']['title']
                type = data['response']['account']['type']
                first_login = data['response']['first_login']

                timestamp = str(first_login)

                await ctx.respond(f"rank: **{rank}**\n type: **{type}**\nfirst_login: **<t:{timestamp[:10]}:d>**")
                

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
#

guys help

#

this is my code

#

i tried to make an api request using aiohttp and asyncio

#

inside an command

#

but it does not work

slow dome
#

please don't tell me you never learned asyncio

clever lava
#

no

#

sorry to tell this to you

#

but im new to python and im just asking for some help

slow dome
#
async with aiohttp.ClientSession() as session:
            async with session.get(f'https://mush.com.br/api/player/{player}') as response:
                print("Status:", response.status)

                data = await response.json()

                rank = data['response']['rank']['title']
                type = data['response']['account']['type']
                first_login = data['response']['first_login']

                timestamp = str(first_login)

                await ctx.respond(f"rank: **{rank}**\n type: **{type}**\nfirst_login: **<t:{timestamp[:10]}:d>**")
#

you only need this

#

forget about everything else

#

just that

clever lava
#

i did this before

#

but also did not work

slow dome
#

p.tag idw

supple ravineBOT
#
CommandNotFound

Command "tag" is not found

slow dome
#

?tag idw

hearty rainBOT
#

dynoError No tag idw found.

slow dome
#

p.tag

supple ravineBOT
#
CommandNotFound

Command "tag" is not found

slow dome
#

p.tags

supple ravineBOT
#
CommandNotFound

Command "tags" is not found

slow dome
#

that's great

clever lava
#

._.

slow dome
# slow dome p.tag idw

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

languid hollow
#

for some reason this pops up

slow dome
clever lava
#

ok sorry

wild thunder
languid hollow
frigid lark
#

discord and discord.ui

slow dome
languid hollow
#

and still the same error

slow dome
#

restart the server

languid hollow
#

nope still the same issue

slow dome
#

uninstall py-cord then install py-cord

languid hollow
#

does py-cord come with discord & discord.ui stuff?

languid hollow
#

I'm presuming I don't need to install discord and discord.ui?

frigid lark
languid hollow
#

oh

#

I always had it on my pc and it never had any error

leaden mesa
#

how do I respond to a view interaction on a slash command so the "This interaction failed" message doesn't appear?

I can't use ctx.respond since it interprets this as responding twice to the main slash command.
Using followup works for completing the desired task, but the view still registers as non-responded

slow dome
#

b!rtfm pyc interactionresponse

slow dome
#

b!rtfm pyc interaction

leaden mesa
sudden path
#

How could I format the traceback on on_command_error

slow dome
#

what traceback

sudden path
#

I mean, get the traceback

slow dome
#

exception.__traceback__

sudden path
slender lintel
#

How do you make choices in a slash command

supple ravineBOT
#

Here's the slash options example.

worthy basin
#

It shows choices in one of them

mild hatch
#

Is there a way to make a cog's on_ready run when it's reloaded?

slender lintel
mild hatch
#

This is the code:

class Logs(LemonCog):
    def __init__(self, bot):
        super().__init__(bot)
        self.log_channels = {}
        self.on_ready_fired = False

    @commands.Cog.listener()
    async def on_ready(self):
        if self.on_ready_fired:
            return
        self.on_ready_fired = True

        for name, channel in self.bot.config["logs"].items():
            log = self.bot.get_channel(channel)
            webhook = discord.utils.get(
                await log.webhooks(),
                name=f"{self.bot.user.name} logs")

            if webhook is None:
                webhook = await log.create_webhook(name=f"{self.bot.user.name} logs")

            self.log_channels[name] = webhook

When the bot is started as normal, it reads the webhook and sends the message, but when i use a /reload command that reloads a certain cog, it says the webhook is None

slender lintel
#

Im doing this correctly right?

#
@commands.Cog.listener()
    async def on_member_join(self, member):
        print("worked")
        guild = member.guild
        one = guild.get_role(995034830473527346)
        two = guild.get_role(995033551047237732)
        member.add_roles(one, two, reason="Automated Join Request")
#

spacing is bugged btw

slow dome
#

doing what right

slender lintel
#

for some reason print("worked") isnt even being called

slender lintel
slow dome
#

check intents

slender lintel
#

alr

#

i just do bot.Intents right?

#

ill check docs

crimson hinge
#

Did you have the members intents?

slender lintel
#

I should

#

i did discord.Intents.all

crimson hinge
#

Ok

#

await member.add_roles()

#

You forgot to use await.^^

#

@slender lintel

slender lintel
#

: o

worthy basin
#

If there are erros in the console you should post the entire error when asking

slender lintel
#

there wasnt any weirdly

worthy basin
#

oh, strange

slender lintel
#

yea

#

it was just blank

#

and wasnt working

#

got it working now

#

i forgot await lol

#

it shoulve said enable tramollic(i forgot the name)...

#

new error : o

#
403 Forbidden (error code: 50013): Missing Permissions
sudden path
#

Kinda self explanatory

sudden path
slender lintel
#

wdym

crimson hinge
#

Was the bot invited with applications.commands perms? ^^

slender lintel
#

Yes, i believe so

sudden path
#

Is the bot above the role it needs to give

#

And above the user's highest role you're trying to give the role to

slender lintel
#

the code basically adds a role to a new user

#

oh

#

im stupid ๐Ÿ’€

#

i need to sleep

crimson hinge
#

๐Ÿ˜ณ

#

All good everyone makes mistakes.

slender lintel
#

I do it so much lmao

torpid siren
#

What is the best way between @discord.ext.commands.slash_command() and @discord.application_command() ?
Or is there an other even better way?

past gate
#

wdym?

torpid siren
#

Sorry I meant @discord.ext.commands.slash_command() and @discord.slash_command()

torpid siren
# past gate wdym?

I've always used @discord.ext.commands.slash_command() as the decorator for commands in my cogs, but I wanted to know if there was a better way to do so

#

Because I discovered that @discord.slash_command() was a thing

thorn verge
#

How can I install the latest version?

torpid siren
#

py -m pip install -U py-cord --pre

slow dome
#

and yes

slow dome
torpid siren
slow dome
torpid siren
slow dome
#

no, just made it llke that so i think easier to migrate?

#

because discord.ext.commands.command

#

i think

torpid siren
#

OK thx!

slow dome
#

thereโ€™s also discord.commands.slash_command

#

lol

upbeat hill
#

is there a way to make a member option in a slash command that only shows members with a specific role?

upbeat hill
thorn verge
#

How can I have a slash command bot and a prefix command?

hearty rainBOT
thorn verge
#

It does not work for me, it does not respond to the command

sudden path
thorn verge
#

The one in the example

slow dome
thorn verge
#

both

thorn verge
#

Now it works

#

How do I have a command only in prefix and not in slash?

thorn verge
#

And slash?

slow dome
thorn verge
#

Thanks

soft stone
#

What permissions do I need to create PermissionOverwrites on a category? I'm trying to have my bot create a category and then add overwrites to it, but it always fails at the second step with a 403 Forbidden: Missing Permissions error.

My bot has permissions to view channels, manage channels, and manage roles. I don't believe anything else should be required for what I'm trying to do. Giving the bot Administrator makes everything work, but turning on all guild-level permissions aside from Administrator does not work (and just giving the bot Administrator is not a solution that is on the table for me).

soft stone
#

I'm on 2.0.0rc1.

harsh rapids
#

whats the difference between send_response and respond?

#

for ApplicationContext

slow dome
# soft stone I'm on 2.0.0rc1.

check application.commands scope on the dev portal under oauth2 and invite bot with new url then update pycord to 2.0 stable

soft stone
#

I'll try that, thanks ๐Ÿ‘๐Ÿพ

thorn verge
#

ctx.respond(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

help

harsh rapids
#

we need more information

#

but

#

have you tried adding an await?

#
await ctx.respond(embed=embed)```
thorn verge
# harsh rapids thats not the entire error

RuntimeWarning: coroutine 'BridgeContext.respond' was never awaited
ctx.respond(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

harsh rapids
thorn verge
slender lintel
#
class pending_button(discord.ui.Button):
    def __init__(self, original_user,  *args, **kwargs):
        self.original_user = original_user
        super().__init__(
            *args,
            **kwargs
        )


    async def callback(self, interaction : discord.Interaction):
        guild = interaction.guild
        user = interaction.user
        role = guild.get_role(995143525882658877)

        if role not in user.roles:
            interaction.response.send_message(content="You do not have permission", ephemeral=True)
        else:
            view = discord.ui.View
            view.add_item(item=discord.ui.Button(disabled=True, label="Status: Approved", style = discord.ButtonStyle.success))
            interaction.edit_original_message(view=view)
            DM_channel = self.original_user.create_dm()
            await DM_channel.send("Your investigation has been accepted.")
            interaction.response.send_message(content="Successfully changed status.", ephemeral=True)
TypeError: add_item() missing 1 required positional argument: 'self'

Am i tweeking rn

#

I dont see it

#

Im tired arent i

#

view.add_item is telling me i need self

#

oh i forgot () at the end of discord.ui.View

mystic wraith
#

Dumb general question. I see that str's on the web version of Discord don't allow for new lines in Slash Commands while mobile does (odd difference, but mobile allows for an enter key while web doesn't). Anyone know of any loopholes to go about that for the web version? I tried adding a \n to my text but it doesn't add a new line.

jagged meadow
#

how do i use has_permissions and bot_has_permissions checks in the latest version of pycord?

upbeat hill
icy sluice
#

how do i make certain events / commands only execute in a certain guild?

inland acorn
#

how to disable autosync slash command

inland laurel
icy sluice
#

how? are there any docs on this?

inland laurel
#

@open bear rtfm pyc Interaction.guild

strange ferry
#

How do I load command categories in the cogs folder like this
cogs

  • Admin
    ใ…ค~ ban cmd
    ใ…ค~ kick etc
  • Info
    ใ…ค~ more commands
#

i currently have this but this doesnt work

#

the commented stuff is without the categories

#

please ping me if you know it

knotty sequoia
#

just realized that this is the same code that you have above

#

is it not working?

strange ferry
#

no because i need to load the folders with the commands in them in the cogs folder

inland acorn
#

how to set send_message to true just for the bot

#

in channel perms

strange ferry
knotty sequoia
strange ferry
#

you mean folder?

knotty sequoia
#

no

strange ferry
#

what

knotty sequoia
#

do you have a separate file for every command?

strange ferry
#

yes

knotty sequoia
#

lol why would you do that

#

that's like against the point of having cogs

#

instead of having separate folders for the categories i.e(admin, info, etc)

strange ferry
#

no its more orginised

knotty sequoia
#

well you do you ig

strange ferry
#

but nobody knows how to do it?

knotty sequoia
#

for each in f[2]:

#

should it not be for each in f:

#
for folder in os.walk("./cogs"):
 for file in os.listdir(f'./{folder}'):
  if file.endswith('.py'):
     bot.load_extension(f'cogs{file[:-3]}')
#

actually just try the second one

slender lintel
#

Hey guys! I have a problem with responding with an embed to a slash command. Is it even possible? The command works when responding with a string, but not when i respond with an embed, it also doesn't return any error. Code:

stockembed = discord.Embed(title="Stock", description=f"{stock} stock left.", color=0x00ff00)
await ctx.respond(embed=stockembed)
slender lintel
sudden path
#

What's the bot output

slender lintel
#

im sorry for wasting your time, it just fixed itself after 4 restarts cat_approve

hazy tundra
#

are there still reasons to use rc1 over stable?

frigid elm
#
@commands.command(name="afk",description="afk")
    async def afk(self,ctx,reason = None):
        
        
        
        
        if reason == None:
            reason = "Reason not provided"
        
        data =  await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),str(ctx.guild.id))
        
        if data:
                if data[0] == reason:
                    e = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description="You are already afk with that reason")
                    await ctx.reply(embed=e)
                await self.bot.pg_con.execute("UPDATE afk SET reason= $1 WHERE user= $2 AND guild= $3",reason, str(ctx.author.id), str(ctx.guild.id))
        else:
                await self.bot.pg_con.execute("INSERT INTO afk (user,guild,reason) VALUES ($1,$2,$3)",str(ctx.author.id),str(ctx.guild.id,reason))
                embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
                await ctx.reply(embed=embed)``` it says asyncpg.exceptions.DataError: invalid input for query argument $1: 984856281946943598 (expected str, got int) in line
#

i tried making them strings

#

but now it says

#

int is required

graceful trout
#

How long do buttons stay active? I noticed after some time they become unclickable

inland lance
#

Hey ! How can I edit a slash_command response message after a send_message ?

crimson coral
crimson coral
#

uhhh let's see

#

well

#

it kinda says it already, it's expecting you to use string IDs

#

oh

frigid elm
#

but if i use str() it asks for ints

crimson coral
crimson coral
#

that looks like the same error tho

#

expected str, got int

frigid elm
#

this is when i remove all str functions

#

lemme put them wait

frigid elm
# crimson coral that looks like the same error tho
@commands.command(name="afk",description="afk")
    async def afk(self,ctx,reason = None):
        
        
        
        
        if reason == None:
            reason = "Reason not provided"
        
        data =  await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),str(ctx.guild.id))
        
        if data:
                if data[0] == reason:
                    e = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description="You are already afk with that reason")
                    await ctx.reply(embed=e)
                await self.bot.pg_con.execute("UPDATE afk SET reason= $1 WHERE user= $2 AND guild= $3",reason,str(ctx.author.id), str(ctx.guild.id))
        else:
                await self.bot.pg_con.execute("INSERT INTO afk (user,guild,reason) VALUES ($1,$2,$3)",str(ctx.author.id),str(ctx.guild.id),reason)
                embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
                await ctx.reply(embed=embed)

        
        


      
        
        
        
            

       

        
       
            
    #################################################################### 
    @commands.Cog.listener()
    async def on_message(self,message):
        
        if message.author.bot:
            return
        
        data = await self.bot.pg_con.fetchrow("SELECT reason FROM afk WHERE user = $1 AND guild = $2",str(message.author.id),str(message.guild.id))
        
        if data:
                embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{message.author.mention} ; Welcome back from your AFK!")
                await message.reply(embed=embed)
                await self.bot.pg_con.fetchrow("SELECT FROM afk WHERE user= $1 AND guild= $2",str(message.author.id), str(message.guild.id))
        if message.mentions:
                for mention in message.mention:
                    data2 = await self.bot.pg_con.fetchrow("SELECT reason FROM afk WHERE user= $1 AND guild= $2",str(message.author.id), str(message.guild.id))
                    
                    if data2 and mention != message.author.id:
                        embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{mention.mention} is currently AFK for reason: `{data2[0]}`")
                        await message.reply(embed=embed)

        
        await self.bot.process_commands(message)
         ``` this is the full code
#

and the error is

#

oh wait

#

am i supposed to make only the user id a string

crimson coral
#

that error's on arg $2

#

while the first was on arg $1

#

so you're using both string and int ids simultaneously

frigid elm
#

so what do i do i dont get it

crimson coral
#

well

frigid elm
#

i use str() only on one arg?

crimson coral
#

you just have to match your datatypes correctly

frigid elm
#

in pgadmin they are bigints

#

the columns

crimson coral
#
data =  await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),str(ctx.guild.id))```
so seemingly from the errors, authors are strings while guilds are ints
#

hm

frigid elm
crimson coral
#

idk why but the bot disagrees

frigid elm
#

๐Ÿ’€

crimson coral
#

just try str(ctx.author.id), ctx.guild.id i guess

frigid elm
#

okay ty

thin trellis
#

How do we access text voice channels?
Just normally with bot.get_channel? I donยดt find any ChannelType related to text voice channels

#

Or are these channels just threads?

frigid elm
# crimson coral just try `str(ctx.author.id), ctx.guild.id` i guess
else:
                await self.bot.pg_con.execute("INSERT INTO afk (user,guild,reason) VALUES ($1, $2, $3) ", str(ctx.author.id), ctx.guild.id, reason)
                embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
                await ctx.reply(embed=embed)```
#

it says

#

syntax error

#

near user

#

in the INSERT INTO line

#

but i dont see any error

plush tusk
#

Hey guys, Am I the only one who has troubles with slash_commands in cogs after update? My commands just don't appearing...

plush tusk
#

this is cog

frigid elm
#

commands.slash_command

plush tusk
#

it imported from it

frigid elm
#

wait sen full ss without cropping

plush tusk
#

and alot of files

frigid elm
#

lol nvm

plush tusk
#

.-.

median aurora
#

why does no one return
if there is such a guild

#
guild = client.get_guild(990641478164430918)
print(guild)```
slender lintel
#

Check this out

#

This is actually pretty helpful

undone delta
#

my bot throw this error after that last update, what happend here?

plush tusk
slender lintel
#

I haven't had any problems

slender lintel
median aurora
#

yes

slender lintel
#

for i in client.guilds
print(i.id)

#

See what that displays

#

@median aurora try fetching the guild

#

It might not be in the cache yet

median aurora
#

I don't need this at all the fact is that I do a daily check by importing a file with a check function and the problem is that I can't get the bot to work before it is connected and I lack python knowledge

#
async def on_ready():
    if __name__ == '__main__':
        timer = Timer(3, check(client))
        timer.start()
        timer.join()```
#
    <...>
    asyncio.run(role_delete())```
#
    client = commands.Bot(command_prefix = '!', intents=disnake.Intents.all(), test_guilds=[990641478164430918])
    guild = client.get_guild(990641478164430918)
    print(guild)```
slender lintel
#

Can I see your error?

#

You can try client.fetch_guild

#
if check.is_dev(ctx.author.id):
            num = 0
            devs_list = ""
            for dev_id in database.dev_ids():
                num += 1
                dev_mention = f"<@{dev_id}>"
                devs_list += f"`{num}.` {dev_mention}\n"
            dev_em = discord.Embed(description=devs_list, color=database.theme_color)
            dev_em.set_author(name=f"Devs List", icon_url="https://cdn.discordapp.com/emojis/979609228845129738.png?size=96")
            await ctx.respond(embed=dev_em)
        else:
            errorEm = discord.Embed(description=f":error: You are not authorized to use the command.", color=database.error_color)
            await ctx.respond(embed=errorEm, ephemeral=True)
#

Error: 'function' is not iterrable

#

dev_ids()

#

I know the error is due to for inin statment

#

but how to fix it

#

it returns a list

#

of all ids

#

You need a separate variable for thay

past gate
#

no..

slender lintel
#

Oh nvm

past gate
#

show your code for the dev_ids function

slender lintel
#

Hopefully it has a return statement

past gate
#

doesn't feel like it does

slender lintel
past gate
slender lintel
#

Print configD really quick*

slender lintel
median aurora
plush tusk
slender lintel
median aurora
#

when using client.fetch_guild

slender lintel
#

Oh weird

#

And what does get_guild display

slender lintel
past gate
slender lintel
past gate
#

hm

median aurora
slender lintel
#

Weird

slender lintel
# past gate hm

if i make a var for that funcs then when i make a change in list and again call the var it shows the old list only

slender lintel
slender lintel
#

Also print the type along with it

slender lintel
#

Yea

slender lintel
#

It would display there if you were in it

median aurora
#

yes

slender lintel
#

That's odd then

#

Hm

#

is there no ctx in bridge_command anymore?

#

@slender lintel anything?

slender lintel
#

Wth

#

Make a separate variable before you iterate in it

past gate
#

the error must be caused by something else then

slender lintel
#

Then iterate through the variable

slender lintel
#

Did that fix it?

#

no i knew it

#

BuBut how to I don't

#

Basically

#
ids = db.dev_ids()
for item in ids:
 Do your stuff here
#

That's what I meant

slender lintel
#

but i will again now wait.....

#

Alright

#

same err

#

If that doesn't work either.

ids = list(db.dev_ids())
for item in ids:
 Do your stuff hereโ€Š
#

That'll convert it into a list object

#

@past gate what's your thoughts on this?

#

same

#

err

#

What's the error again

slender lintel
#

Wth

slender lintel
#

Your module must be doing something weird

slender lintel
#

I'm just confused how it takes your list object as a function

slender lintel
#

Right above the for loop can you print out that function and its type and send it here.

#

print(ids)
print(type(ids))

#

Whatever the variable was

slender lintel
#

@slender lintel

#

@past gate

past gate
#

I am now AFK

supple ravineBOT
#

Set your AFK: No reason specified.

slender lintel
#

@slender lintel

half marsh
slender lintel
#

My bad

slender lintel
#

Can you resend your current code

slender lintel
# slender lintel Can you resend your current code
#list devs
    @slash_command(guild_ids=database.owner_guild_ids, name="list-devs")
    async def list_devs(self, ctx):
        """Shows bot devs"""
        if check.is_dev(ctx.author.id):
            num = 0
            devs_list = ""
            dev_ids = list(database.dev_ids())
            for dev_id in dev_ids:
                num += 1
                dev_mention = f"<@{dev_id}>"
                devs_list += f"`{num}.` {dev_mention}\n"
            dev_em = discord.Embed(description=devs_list, color=database.theme_color)
            dev_em.set_author(name=f"Devs List", icon_url="https://cdn.discordapp.com/emojis/979609228845129738.png?size=96")
            await ctx.respond(embed=dev_em)
        else:
            errorEm = discord.Embed(description=f":error: You are not authorized to use the command.", color=database.error_color)
            await ctx.respond(embed=errorEm, ephemeral=True)


#

What in the world

past gate
#

.

frigid elm
#
@commands.command(name="afk",description="afk")
    async def afk(self,ctx,reason = None):
        if reason == None:
            reason = "Reason not provided"
         
        
        data = await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),ctx.guild.id)
        if data:
            if data[0] == reason:
                embed = discord.Embed(color=discord.Color.from_rgb(13,99,143),description="You are already afk with thtat reason!")
                await ctx.reply(embed=embed)
            await self.bot.pg_con.execute("UPDATE afk SET reason = $1 WHERE user = $2 AND guild = $3",reason,str(ctx.author.id),ctx.guild.id)
            em = discord.Embed(color=discord.Color.from_rgb(13,99,143),description=f"Updated reason to: `{reason}` ")

        else:
            await self.bot.pg_con.execute("INSERT INTO afk (user, guild, reason) VALUES ($1, $2, $3)",str(ctx.author.id),ctx.guild.id, reason)
            embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
            await ctx.reply(emebd=embed)``` it says there's a syntax error after the last else statment near or at user
#

i dont see any

slender lintel
frigid elm
#

ive been stuck on this for hours ๐Ÿ’€

slender lintel
frigid elm
slender lintel
#

Alr bet

#

One sec

orchid horizon
#

Hello, is there any possible ways you can make a parameter that is adjustable?

For example :
.pay {member} 2000
and
.pay 2000 {member}

I want to make a pay command which has 2 parameters and those parameters can switch place depending on the user input

past gate
slender lintel
#

of 2 devs

slender lintel
slender lintel
#

It shows the list. Says it's a list. But then it tells you it's a function

slender lintel
slender lintel
#

me in tuis prob from morning

slender lintel
#

10:00am

past gate
#

what if the file doesn't exist

#

the dev_ids call has to be returning None

slender lintel
past gate
#

theres no other way

frigid elm
#

anyone knows whats wrong with mine?

slender lintel
#

@past gate no joke. It prints everything fine. But says it's a function ๐Ÿ’€