#Basic Pycord Help (Quick Questions Only)

1 messages · Page 67 of 1

wicked helm
#

Have done. It now runs after everything has loaded. Still getting the Atr Error on member... the member id's are correct.. and the guild is being picked up fine (I assume as that isn't throwing an error)

silver moat
#

Do you have members intent?

wicked helm
#

And the bot has admin permissions

silver moat
wicked helm
#

I have not.. needed to do this yet for the / commands and ctx.respond.. I will look at doing that!

proud mason
#

Try audio.file.read()

#

I have personally had similar issues. Wav files saved by vc recording do not get loaded into pydub.AudioSegment or numpy arrays. Normal files do. And the saved files can even be played back

#

But when saving them as MP3 they can be loaded into pydub

#

I'm not sure why this happens

violet bear
#

ahh okay, so then I'm guessing I should use the MP3 sink and also audio.file.read() . Or could I still use audio.file.read() with the Wave Sink to fix it?

proud mason
#

Internally the mp3 sink just saves as wav and converts them using FFMpeg. And that works. Everything is just weird 💀

proud mason
#

If not try MP3 sink

violet bear
#

perfect, I will try that. Thank you!

proud mason
#

||In case you really want wav, convert the mp3 back into wav using ffmpeg||

livid wolf
#

Would the command be (to select a member)


async def member_roles(ctx, member: discord.Member()):
       ...

Or how would you get a discord member using discord.Member() in the bot command?

livid wolf
#

Lemme try that.

#

Thanks, it works

wicked helm
cerulean yacht
#

how to write tests for my bot?

livid wolf
#

Quick question, how do I send an embed?

#

Never mind, figured it out

#

.rftm embed

#

.rtfm embed

livid wolf
#

Just what I needed

grizzled sentinel
#

#883236900171816970 next time please :)

livid wolf
#

sorry

wicked helm
#

I'm going insane : ^ )

#

I've got to the point where my background task can get the member objects.. But I can't get the permissions to update their nicknames..? My bot is an admin and all intents are enabled..?

#

Aight - moving the bot up in the list of role priority fixed it. Glad I thought of that first x)

full basin
wind jay
#

how can i do bot.loop.create_task(daily()) in a cog?

full basin
#

The same way?...

chrome skiff
proud mason
chrome skiff
#

sorry

livid wolf
#

I got it figured out

chrome skiff
#
f = discord.File(fp=output_buffer, filename=f"winner-{formatted_date}.png")

em = discord.Embed(title=f"day", description=f"test desc", colour=colour().main, timestamp=datetime.now())
em.set_image(url=f"attachment://winner-{formatted_date}.png")
em.set_footer(text=f"test")
await ctx.send(file=f, embed=em)
#

when i use this my image is not in the embed

#

its out of the embed

#

can somebody help?

obtuse juncoBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
chrome skiff
young bone
#

any errors?

chrome skiff
#

no nothing

young bone
#

are you sure?

chrome skiff
#

now removed fp=

#

didnt changed anything

chrome skiff
#

you cant have a space in the filename

#

removed the space and now image is showing in the embed

young bone
#

ok

grizzled sentinel
violet bear
#
        audio_data = audio.file.getbuffer()
        num_channels = 2
        bytes_per_sample = 2
        sample_rate_in = 48000
        sample_rate_out = 16000
        with wave.open("talk.wav", "wb") as wav_file:
            wav_file.setnchannels(num_channels)
            wav_file.setsampwidth(bytes_per_sample)
            wav_file.setframerate(sample_rate_out)
            resampled_data = audioop.ratecv(audio_data, bytes_per_sample, num_channels, sample_rate_in, sample_rate_out, None)[0]
            wav_file.writeframes(resampled_data)```
devout anvil
#

what class to do this

limber urchin
#

what?

devout anvil
#

when i click on a user profile, it shows me that section under roles

silver moat
devout anvil
#

what does iirc mean

silver moat
#

if i recall correctly

#

if discord released a new thing, it would be in their api announcement channel

silver moat
ruby atlas
#

Ok how should I ask this, i have a code, his work is sending a message to WhatsApp with information, the thing is I need to get the message as soon as possible

#

import pywhatkit as pw

pw.sendwhatmsg("number", "message", 10, 30)
The last part is the one that gives me trouble, when I put 0,0 python takes it like 12pm

silver moat
ruby atlas
#

💀, ty tho

leaden relic
#

does InputText have live regex validation like how the min max length? or do i only have the choice to do validation after submission?

young bone
leaden relic
#

you know like those online forms that goes red when you type an invalid character

#

rn it only does validation for the length of the text you put in the fields

young bone
#

Text and that only ^

leaden relic
#

i see so i can only validate the content of the text after submission

young bone
#

Yes

leaden relic
#

would be nice if there's a pattern= argument for that

distant roost
#

Is there a way to add more than 2 fields to an modal because if i copy paste a field it doen’t work

proud mason
#

Oh sorry

#

Modal

#

I thought embed 💀

distant roost
#

xD

proud mason
#

Modal can have upto 5 input texts

leaden relic
#

imagine having 25 input text on a modal 🤣

distant roost
#

And how do i add more? Thank you for you response

leaden relic
#

self.add_item()

distant roost
#

Ok i try thank you

leaden relic
#

self.add_item(discord.ui.InputText(label="Name", required=True))

fervent cradle
#

Is there any module that converts a JSON discord embed raw to an Embed object?

sinful pivot
#

Is there a func like setup_hook that I can use in my subclass for commands.Bot

#

Just like there is in dpy

winter condorBOT
full widget
#

What's the best way to silently acknowledge a button/interaction?

#

I'm assuming editing a message with it's previous content or something like that?

#

or is there an easier way

proud mason
#

on the master branch you also have @client.listen(once=True)

sinful pivot
#

wym?

sinful pivot
full widget
#

you

#

He means to subclass the start method of the bot

#

if you're running a subclassed bot objct

sinful pivot
#

mhm and where do I add the @client.listen

full widget
#

you wouldn't need it in that case

sinful pivot
#

Alright

full widget
#

assuming you're just looking to run some coroutine when you run bot.start()

proud mason
full widget
#

problem with deferring is that the button stays greyed out until the defer times out

full widget
#

like I can't click the button again

#

until the defer times out

proud mason
#

not really

#

can you show what happens? and your code

full widget
#

I'm just playing around with the way that I respond to user interactions. I'm manipulating a Lobby object that has a lot of methods, ideally the display to the lobby channel is done from within those methods as they can be called by multiple sources, including the button. So I don't want to return a message at all from clicking the button, just run the Lobby method

#

oh wow i'm sleep deprived

#

forgot I disabled the button after clicking it if no one else was in the lobby, works as intended

orchid sapphire
#

I have a question. I cannot get my bot to mention users and roles in a response to an interaction in a private thread. allowed_mentions are set to all as an option for the bot and are set to all in the ctx.respond() function. However, allowed_mentions is no option in the interaction.response.edit_message function. Anyone know how to fix this?

grizzled sentinel
keen dove
#

Hello Guys, Is there a way to know which user invite a bot to his server ?
I didn't find this anywhere atm. Thanks for helping

orchid sapphire
sinful pivot
#

.start() takes in token as an arg cuz if I'm not wrong its called from .login()

#

oh wait, its ran from .run()

blissful hazel
#

If you had copy pasted the code instead of a screenshot it would have taken less space 😉

sinful pivot
proud mason
sinful pivot
#

ok

sinful pivot
#

And all of em are guild commands (because I use the debug_guilds kwarg in commands.Bot)

sinful pivot
#

huh?

proud mason
#

that shouldnt be related at all ngl

#

mind sharing full traceback

sinful pivot
#

wait 1s

#

Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

here ya go

proud mason
#

above the top line

sinful pivot
#

Mhm, you mean like the full full traceback?

proud mason
sinful pivot
#

nvm looks like im not deferring thats why

#

ima defer and lyk

fervent cradle
winter condorBOT
proud mason
#

read the docs when...

soft girder
#

Hi guys . Can anyone post a list of errors.

#

you need to write a couple of commands like this one.

proud mason
soft girder
#
@очистка.error
async def clear_error(ctx,error):
    if isinstance( error, commands.MissingRequiredArgument):
        await ctx.send(f'{ctx.author.mention},обязательно укажите аргумент.')

    if isinstance( error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.mention},у вас нету прав на использование.')

#

@proud mason thx

#

🤗

rich grail
#

does guild_only() not block the commands from being viewable in DMs?

#

i thought it used to, but i'm having commands show up using both guild_only() and commands.guild_only()

full basin
sick quest
#

for some reason, the task loop in my discord bot just, stopped working

#

it works on my development computer, but on the server i'm hosting it, it just doesn't run (the next_iteration property returns None)

#

I've tried restarting it, changing the interval, even completely recloning the repository for the bot and restarting it

#

but it works completely fine on my local computer

proud mason
proud mason
sinful pivot
#

Hi, how do I get the embed in a ephemeral msg

#

Like an embed is sent and the msg is ephemeral, how do I get that embed and modify it like changing the title etc (ik I can do it thru embed.title = "my title here" and then edit the msg)

proud mason
proud mason
sinful pivot
proud mason
#

ah

#

message.embeds has a list of embeds

sinful pivot
#

but like how tf do I get that msg

#

get_original_response?

proud mason
#

get the 1st item (if you are only having 1 embed)

sinful pivot
#

does that exist

sinful pivot
#

I know .embeds exists

proud mason
#

buttons have the interaction.message attribute

#

all message components do

sinful pivot
#

Great ill lyk if it works

proud mason
#

cool

sinful pivot
#

Oh yeah and how do I edit a msg after I've sent a response?

proud mason
#

||Although that will stop working after 15 mins||

sinful pivot
#

Also I sent a modal as the resp, and I do .wait() on that modal, it doesn't actually end up waiting and just does the code right below it

#

Oh wait, it wasnt awaited, whoops

#

Wait uh

#

How tf do I take data back from the modal class? I tried to set a variable and then access that using ```py

my_modal = ModalClass()
.... # Wait stuff here

answer = my_modal.var_name

proud mason
#

thats right

sinful pivot
#

but it returns None

proud mason
#

oh and dont forget to put self.stop() at the end of the modal callback

proud mason
sinful pivot
#
    async def creation(self, select: discord.ui.Select, interaction: discord.Interaction):
        message = interaction.message
        embed = message.embeds[0]
        if select.values[0] == "author":
            author_modal = TextModal(title="stuff here", text="text")
            await interaction.response.send_modal(author_modal)
            await author_modal.wait()
            author = author_modal.text
            print(author)

class TextModal(discord.ui.Modal):
    text: str | None = None

    def __init__(self, title: str, text: str) -> None:
        super().__init__(title=title)

        self.add_item(discord.ui.InputText(label=text, style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        text = self.children[0].value
        self.stop()```
#

I do that

proud mason
#

do self.text = ...

#

i.e. assign it to an object variable

sinful pivot
#

self hmm, though the text var isnt set as a class var but sure ima change that

#

Lemme try that rq

#

Works but the embed errors out, what should I do here as I'm trying to reuse that same modal but just change the kwargs and handle everything in the select

proud mason
#

you cant reuse the same modal object

sinful pivot
#

yes I can lol

proud mason
#

you will need to create a new one

sinful pivot
#

Define it again

#

Yeah thats what I mean, reuse the same class

proud mason
#

ah ok

sinful pivot
#

How do I make the modal not error out

proud mason
#

send a response?

sinful pivot
#

But like what type of response?

proud mason
#

send_message ig

sinful pivot
#

alr its ok ima just re make modal classes for each thing ima do with the select

proud mason
sinful pivot
#

Also is there like a input thingy for links or how do I verify if the link is an asset or smth

#

Because I basically want to get a png from a modal or some way

proud mason
#

you can check stuff using regex

sinful pivot
#

embed.author.name

#

Found it!

warm grotto
#

I have this code here```py
import discord, asyncio, random
from discord.commands import slash_command, Option
from discord.ext import commands
from myfunctions import Load, Save

songs = ["CarelessWhisper"]

class Join(commands.Cog):
def init(self, client):
self.client = client
@slash_command(description="Joins a channel")
async def join(self, ctx):
if ctx.author.voice:
channel = ctx.author.voice.channel
try:
await channel.connect()
except:
await ctx.voice_client.move_to(channel)
Data = Load()
Data[str(ctx.guild.id)] = channel.id
Save(Data)
embed = discord.Embed(
title = "Joined Channel",
description = "Successfully joined channel. You can now enjoy the best music!",
color = discord.Color.green()
)
embed.set_footer(text="Powered by VersaDev.org")
if not ctx.guild.voice_client.is_playing():
ctx.guild.voice_client.play(source=f"file:{random.choice(songs)}.mp3")
Message = await ctx.respond(embed=embed)but when it comes to py
ctx.guild.voice_client.play(source=f"file:{random.choice(songs)}.mp3"), It runs into the error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientException: Not connected to voice``` even when the bot is actually in the voice channel

#

Only py-cord is installed and not discordpy, yet it still does not play music

warm grotto
young bone
#

update to the new version #library-updates

warm grotto
#

Great, thanks!

green hinge
#

I created a paginator and wanted to have the paginator accutalize the pages at a certain interval. For this I created an update function that loads the new pages and then the view should be updated. Unfortunately this does not work the way I did it. Does anyone have an idea and can help me how to do this?

class PaginatorInfoView(Paginator):   
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.pages = await self.update_pages()
        view = await self.generate_view()
        custom_buttons =[#Code for Buttons]
        super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)
        
        asyncio.ensure_future(self.update_loop())

    async def update_pages(self):
        data = await dab.get_all_spots()
        pages = []
        spots_per_page = 6

        # Erstelle eine neue Seite
        embed = discord.Embed(title="Spotübersicht")
          .
          .
            #embed.set_footer(text=spot_text)
        pages.append(embed)

        # Entferne NULL-Elemente
        return [p for p in pages if p is not None]


    async def update_loop(self):
        while True:
            self.pages = await self.update_pages() 
            self.update() 
            print("Pages updated")
            await asyncio.sleep(30) 
    

    async def generate_view(self):
        view = SpotDetails(self.bot)
        return view```
novel yacht
#

code

@discord.user_command(name="Account Creation Date", guild_ids=[number])
    async def account_creation_date(ctx, *, member: discord.Member):
        await ctx.send(f"{member.name}'s account was created on {member.created_at}")```


error

Ignoring exception in command Account Creation Date:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 1571, in _invoke
await self.callback(self.cog, ctx, target)
TypeError: account_creation_date() takes 1 positional argument but 3 were given

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

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: account_creation_date() takes 1 positional argument but 3 were given```

help pls)

young bone
novel yacht
young bone
#

do you know basic python?

novel yacht
#

only started learning

young bone
#

#help-rules

novel yacht
#

sorry

young bone
#

without the basic´s of Python you will have many problems creating a discord bot

young bone
#

Pls learn Python first

full basin
#

And verbs conjugation

fervent cradle
#
view = CreateSuggestionView()
message = await interaction.response.send_message(content=PreviewMessage, embed=suggestion_embed, ephemeral=True, view=view)

view.message = message

send_message doesn't return message, any alternatives?

#

Like I just want this function here to have the message property

class CreateSuggestionView(ui.View):
  async def disable_all_items(self):
    for item in self.children:
      item.disabled = True
      await self.message.edit(view=self)

full basin
#

.rtfm interaction.original_response

winter condorBOT
fervent cradle
#

ah

#

i was looking for something like that

#

i'll try it out :o

full basin
#

Why are you trying to override a function?

fervent cradle
#

What it's supposed to do is disable all the buttons attached to the embed

#

Am i doing something wrong?

full basin
#

That function already exists?

#

Why are you creating it again?

fervent cradle
#

I didn't know

#

What's it called

full basin
#

.rtfm View.disable_all_items

winter condorBOT
fervent cradle
#

damn

#

that makes my life easier

#

ty :o

#

Any idea why i got this error after switching to interaction.original_response btw?

#

it thinks the message is a coroutine object..?

#

view.message = interaction.original_response()

fervent cradle
# winter condor

I'll still switch to this but i just wanna understand where i went wrong

#

oh i needed to await it pokemon_sweat

#

nvm thanks for the help

#

OH

#

THIS IS PYCORD

#

why am i here

#

im a dumbass

glossy tusk
#

Is there a way to listen to the sound the bot hears from the channel live from a different location?

harsh canyon
glossy tusk
harsh canyon
#

ive been trying to work my own janky solution for voice commands but not much luck so far

glossy tusk
harsh canyon
#

afaik yes

glossy tusk
#

Is it possible to record the entire conversation as a single piece
not like @glossy tusk 's record etc.

harsh canyon
#

i think it should be

glossy tusk
#

I have tried manually combining different recording, but it becomes very chaotic because the recording starts with the sound action.

#

thank you btw

harsh canyon
#

i think its just start_recording then stop_recording

#

.rtfm start_recording

winter condorBOT
glossy tusk
#

I know but

#

This is save audio from sink.audio_data.items()

#

Different users audio in there

harsh canyon
#

athh

#

idk then

glossy tusk
#

okey thx a lot

errant craneBOT
proud mason
#

Check that out

#

Would be cool if you can test it

glossy tusk
#

Thx ı'll work on it

magic pendant
#

Does the library support python 3.10?

glossy tusk
#

Or my brain had a hard time understanding the prepared algorithm for combining the sounds.

edit: Oh, or does it continue recording until the stop command comes after receiving the first sound from the user?
In other words, is the voice recording of a person who is included in the 50th second of a 100-second speech and comes out at the 55th second, is recorded as 50 seconds instead of 5 seconds? I don't have an environment to test this

undone mulch
#
Failed to load slashes.py from ./cogs:
Extension 'cogs.slashes' raised an error: ImportError: cannot import name 'InputText' from 'discord.ui' (/home/container/.local/lib/python3.9/site-packages/discord/ui/__init__.py)
Failed to load casino.py from ./cogs/Casino:
Extension 'cogs.Casino.casino' raised an error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)
Failed to load casino_misc.py from ./cogs/Casino:
Extension 'cogs.Casino.casino_misc' raised an error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)
Failed to load casino_games.py from ./cogs/Casino:
Extension 'cogs.Casino.casino_games' raised an error: AttributeError: module 'discord' has no attribute 'Cog'
Failed to load miner_only.py from ./cogs:
Extension 'cogs.miner_only' raised an error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)
Failed to load modals.py from ./cogs:
Extension 'cogs.modals' raised an error: ImportError: cannot import name 'InputText' from 'discord.ui' (/home/container/.local/lib/python3.9/site-packages/discord/ui/__init__.py)
/home/container/cogs/events.py:604: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  client.add_cog(events(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load events.py from ./cogs:
Extension 'cogs.events' raised an error: TypeError: object NoneType can't be used in 'await' expression```

Why would I be getting these erorrs on one hosting service and not the other? Amazon Azure VPS doesn't have these issues but then when I use Bisects VPS it does? Any reasons?
#

It's hard to know what code is correct if two different host give me code issues..

#

They're both using PyCord/on the same python version

glossy tusk
undone mulch
proud mason
#

Dpy is conflicting with pycord

undone mulch
#

oof

#

How could I force d.py to go away

proud mason
#

Uninstall dpy py-cord and any other discord related library. And reinstall py-cord

undone mulch
#

I have no access to those commands

proud mason
#

Oh hmm

undone mulch
#

It's just like ftp only

#

And console

proud mason
#

well pip uninstall works in the console right

undone mulch
#

Let me check

#

Nope

#

I have these only. But no commands can go into console

#

I just mention my packages in a requirements.txt

proud mason
undone mulch
#

Yeah hm

#

I think it is preinstalled.

proud mason
#

Then create a new python file and put

import os
os.system("pip uninstall discord.py discord py-cord")
#

After that is done, change it to install py-cord

undone mulch
#

Watch that not work 😂

#

Gonna try now.

proud mason
undone mulch
#
You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
Found existing installation: discord.py 2.2.2
Uninstalling discord.py-2.2.2:
  Would remove:
    /home/container/.local/lib/python3.9/site-packages/discord.py-2.2.2.dist-info/*
    /home/container/.local/lib/python3.9/site-packages/discord/*
  Would not remove (might be manually added):
    /home/container/.local/lib/python3.9/site-packages/discord/bot.py
    /home/container/.local/lib/python3.9/site-packages/discord/cog.py
    /home/container/.local/lib/python3.9/site-packages/discord/commands/__init__.py
    /home/container/.local/lib/python3.9/site-packages/discord/commands/context.py
    /home/container/.local/lib/python3.9/site-packages/discord/commands/core.py
    /home/container/.local/lib/python3.9/site-packages/discord/commands/errors.py
    /home/container/.local/lib/python3.9/site-packages/discord/commands/options.py
    /home/container/.local/lib/python3.9/site-packages/discord/commands/permissions.py
    /home/container/.local/lib/python3.9/site-packages/discord/ext/pages/__init__.py
    /home/container/.local/lib/python3.9/site-packages/discord/ext/pages/pagination.py
    /home/container/.local/lib/python3.9/site-packages/discord/iterators.py
    /home/container/.local/lib/python3.9/site-packages/discord/scheduled_events.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/__init__.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/core.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/errors.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/m4a.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/mka.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/mkv.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/mp3.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/mp4.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/ogg.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/pcm.py
    /home/container/.local/lib/python3.9/site-packages/discord/sinks/wave.py
    /home/container/.local/lib/python3.9/site-packages/discord/types/raw_models.py
    /home/container/.local/lib/python3.9/site-packages/discord/types/scheduled_events.py
    /home/container/.local/lib/python3.9/site-packages/discord/ui/input_text.py```
#

Said in console that it was being removed. But it says "Would not remove"

proud mason
#

What would it not remove

#

Oh wait put -y in there iirc

undone mulch
#

Wdum -y

#

I never use the os module 💀

#

I am used to using console linux but this host is diff

proud mason
proud mason
undone mulch
#

I can't use commands

proud mason
#

No put that in the os.system cmd

undone mulch
#

import os
os.system("pip uninstall -y discord.py discord py-cord")

proud mason
# undone mulch

Uhh if that doesn't work then delete the discord folder from site packages yourself

undone mulch
#

You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
Found existing installation: discord.py 2.2.2
Uninstalling discord.py-2.2.2:
Successfully uninstalled discord.py-2.2.2

proud mason
#

Ok nice

#

Ig uninstalled

undone mulch
#

It might reinstall every restart 💀

proud mason
#

Bruh wtf 💀

#

Contact your host ngl

undone mulch
#

Maybe I can keep that at the top of the code if that is the case

#
import importlib

# Replace 'module_name' with the name of the module you want to check
module_name = 'numpy'

try:
    importlib.import_module(module_name)
    print("True")
except ImportError:
    print("False")```

Let me try this
proud mason
undone mulch
#

trying stuff now let me check if it reinstalls

#
#import os
#os.system("pip uninstall discord.py discord py-cord")

import importlib

# Replace 'module_name' with the name of the module you want to check
module_name = 'discord.py'

try:
    importlib.import_module(module_name)
    print("True")
except ImportError:
    print("False")```
#

Cause this is printing false which is good..

undone mulch
#

Let me try manually deleting every time with the code

#
discord.py py-cord has been uninstalled
/home/container/syst.py:11: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```

💀
torn helm
#

hi, how can i get the name of a Member in one guild? if i use member.name it returns, for example, Snakeice#7702, my global name, non maybe "Superpippo", my name in that server. Thanks!

glossy tusk
winter condorBOT
torn helm
glossy tusk
#

@proud mason
If the user is on the channel at the beginning of the recording and then leaves the channel and reconnects after a while, the time difference in the recording disappears. Can you detect and equalize the time difference?

proud mason
glossy tusk
#

yeah

proud mason
#

I feel this happens because data.timestamp gets paused when the user leaves

#

It is like discord really doesn't like us to receive audio 💀

glossy tusk
#

Ironically the worst created part of discord

proud mason
#

Separate timestamps for all users. No way to coordinate between timestamps of different users

#

Now i really wonder whether audio should be timed based on data.timestamp or actual packet receiving time

glossy tusk
#

Join and speak 10 second and leave. 10 seconds After, join and speak 10 seconds. The recording 20 seconds. WTF

#

Where is my 10 seconds .d

proud mason
glossy tusk
#

Even if there are 10 seconds in between, the sound is combined instantly.

#

For example;
I connect and said hello. And then I left the channel and waited 5-6 seconds. Then I connected and said hello again.
But the recording is 2 seconds.

proud mason
#

Although i can think of a way thinkCat

#

What if i remove the user from the internal dict when he leaves

glossy tusk
#

oh my god, my brain is exploding when I think about this and the possible solutions and the problems that may arise due to the solutions. I think I'll give up

green hinge
#

I created a paginator and wanted to have the paginator accutalize the pages at a certain interval. For this I created an update function that loads the new pages and then the view should be updated. Unfortunately this does not work the way I did it. Does anyone have an idea and can help me how to do this?

class PaginatorInfoView(Paginator):   
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.pages = await self.update_pages()
        view = await self.generate_view()
        custom_buttons =[#Code for Buttons]
        super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)
        
        asyncio.ensure_future(self.update_loop())

    async def update_pages(self):
        data = await dab.get_all_spots()
        pages = []
        spots_per_page = 6

        # Erstelle eine neue Seite
        embed = discord.Embed(title="Spotübersicht")
          .
          .
            #embed.set_footer(text=spot_text)
        pages.append(embed)

        # Entferne NULL-Elemente
        return [p for p in pages if p is not None]


    async def update_loop(self):
        while True:
            self.pages = await self.update_pages() 
            self.update() 
            print("Pages updated")
            await asyncio.sleep(30) 
    

    async def generate_view(self):
        view = SpotDetails(self.bot)
        return view```
proud mason
#

Oh wait

#

Hmm

#

Nope

fringe socket
#

.rtfm rtfm

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

fringe socket
#

.rtfm deez

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

novel yacht
#

how remove standart command help?

#

.rtf

#

.rtfm

proud mason
novel yacht
proud mason
#

yes

novel yacht
#

if i say nothing change? what to do?

#
bot = discord.Bot(intents=discord.Intents.all(), help_command=None)```
#

how remove?(

full basin
#

discord.Bot doesn't have a default help command

#

commands.Bot does

novel yacht
#
mport discord
from discord.ext import commands

class general(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.help_command = None

    @discord.slash_command(name="help", description="Displays a list of available commands.")
    async def help(self, ctx):
        embed = discord.Embed(title="Help", description="Here's a list of my commands.", color=0x00ff00)
        await ctx.respond(embed=embed)

def setup(bot):
    bot.add_cog(general(bot))```
#

🙃

grizzled sentinel
#

Well you have a help command. You could remove that.
self.help_command = None is just setting a instance varible. It will not change anything.

grizzled sentinel
novel yacht
#
import discord
import os # default module
from dotenv import load_dotenv
from config import *
import mysql.connector
load_dotenv() # load all the variables from the env file

bot = discord.Bot(intents=discord.Intents.all())
conn = mysql.connector.connect(
    host=DB_HOST,
    port=DB_PORT,
    database=DB_NAME,
    user=DB_USER,
    password=DB_PASSWORD
)

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


#bot.load_extension('cmd.utility.welcome')
bot.load_extension('cmd.mod.report')
#bot.load_extension('cmd.mod.timeout')
bot.load_extension('cmd.utility.welcome')
bot.load_extension('cmd.utility.general')
bot.load_extension('cmd.main.check')
#bot.load_extension('cmd.utility.test')
bot.run(TOKEN)```
grizzled sentinel
#

And you do not have multiple bots running on the same token?

novel yacht
#

no

grizzled sentinel
#

You are on the latest version of pycord?

novel yacht
#

checking

proud mason
young bone
#

@novel yacht did you already learn the basic´s of Python?

novel yacht
grizzled sentinel
covert kayak
#

Hi, how can I trace the button's custom_id parameter? For example, like: if view.custom_id = "for example":, is it workable? I'm subclassing the view.

grizzled sentinel
# novel yacht genaral cog

Can you find all embeds with that green color? And see if any of them look like the second embed that is sent

grizzled sentinel
#

Also generally custom ids are random and unique

novel yacht
#

🥹 i update pycord and this fixed

#

@grizzled sentinelthanks

covert kayak
young bone
covert kayak
#

really

proud mason
#

button.custom_id when accessing in the callback

covert kayak
#

what if I want to use that outside the class

#

like in a command

grizzled sentinel
#

So like view.children[0].custom_id

proud mason
#

view should be an object btw

covert kayak
#

I mean if the user clicks the button Test, the value I will get is going to be test

#

As a way to see which button the user clicked

proud mason
#

you just use button.label too ?

covert kayak
#

Is there anything such as view.action?

grizzled sentinel
#

What do you want to do when the user clicks the button?

covert kayak
#

So I want to simply know which button the user clicked

#

And feed that information to another function outside the view class

grizzled sentinel
#

interaction.message will give the message the button is attached to. Would that be enough?

covert kayak
#

Is that to be used inside the callback function?

#

can I do this instead, using self.action

full basin
#

If you're subclassing the view why not just also add the buttons there with their callbacks?

covert kayak
#

I'm going to need to load the the user's data from the database and use buttons to interact with these data. I'm at a loss about how to access data between callback functions without using global

#

So I think I'm should just see which button the user clicked and create an external function that handle the callback

grizzled sentinel
#

So do you have a command that gets the data and sends the buttons?

covert kayak
#

Yes, all left is to find a way to know which button the user's clicked

grizzled sentinel
#

That is what the callback is for. When the button is clicked the callback function is called.

#

So you can send the message with the data in the callback or similar.

covert kayak
#

I'm trying to interact with the same data between callbacks tho

#

Like this, but when I run the code it says 'int' object has no attribute 'value'

grizzled sentinel
#

Can you show the full error

shut hedge
#

Is there a way to pull my "snowflake" then embed the photo within a command as a picture varible. Because right now I just have it hard coded in under author command. That has been interesting and reminded me I need to figure out a stop/shut command for the bot because I accidentally made mine into what is best described as a Daemon/zombie process but on windows. when I didn't have error handling. It used another completely unrelated comand though lol.

covert kayak
shut hedge
grizzled sentinel
grizzled sentinel
#

.rtfm discord.Bot.get_user

covert kayak
grizzled sentinel
#

Style=discord.ButtonStyle.primary

covert kayak
#

Yay it works!!! Thank you so much!!!

warm grotto
#

So I have been getting this error for the past couple of days, and seems to be having it constantly. The error does not seem to reference any of my code, so I'm not sure how I could fix it in on my end, but regardless, I don't recall using webhooks in my bot

#

But sometimes, I get interaction never responded, even though I have ctx.defer() in the application command

grizzled sentinel
limber urchin
#

Well the error means you're trying to do something on something that doesn't exist. Like deleting a message that has already been deleted.

strange cradle
#

if you make a role using the bot, can you define the role position? in the hierarchy?

livid wolf
#

How do I get the users roles?

@team.command(description="Send a team invite via DM")
async def invite(ctx, member: discord.Member):
  """Team Member Invite Handler"""
  requestedMember = await bot.fetch_user(member)
  userRoles = discord.Member.roles(requestedMember)
  await ctx.respond(f"{userRoles}") # Testing purposes
winter condorBOT
rapid lintel
#

Is there a way to get a user's server/display banner like with display_name and display_avatar?

cyan quail
#

banner isn't available on api

stuck canopy
#

yo its ronny

delicate harbor
#

is there a way to get all threads of a specific channel ? please ping when you reply

glad remnant
#

Hey, is there a way how to "Force Stop" select menu? My code is working just every time getting interaction failed even tho im getting selected option.

proud mason
glad remnant
#

I am. Into another function

clever hinge
#

hey there quick, really basic question, how can I reply to a slash command with nothing? I have this slash command that sends a webhook, can't figure out how to close the slash command thing without it erroring out

limber urchin
#

You can't respond with nothing to a slash command, the best thing you can do is an ephemeral message saying "Webhook sent!" or something.

clever hinge
#

alright, thanks

green hinge
#

Can someone help me how to make my paginator update every 10 minutes?
Unfortunately, my approach doesn't work that way.

class PaginatorInfoView(Paginator):   
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.pages = await self.update_pages()
        view = await self.generate_view()
        custom_buttons =[#Code for Buttons]
        super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)
        
        asyncio.ensure_future(self.update_loop())

    async def update_pages(self):
        data = await dab.get_all_spots()
        pages = []
        spots_per_page = 6

        # Erstelle eine neue Seite
        embed = discord.Embed(title="Spotübersicht")
          .
          .
            #embed.set_footer(text=spot_text)
        pages.append(embed)

        # Entferne NULL-Elemente
        return [p for p in pages if p is not None]


    async def update_loop(self):
        while True:
            self.pages = await self.update_pages() 
            self.update() 
            print("Pages updated")
            await asyncio.sleep(600) 
    

    async def generate_view(self):
        view = SpotDetails(self.bot)
        return view```
copper flower
#

Hey! I'm trying to define a slash command with SlashCommandGroup and change its name. I wrote this still I'm getting the attached Slash Command. My code is working in a Cog

 @reactionGroup.command(name='create')
    async def reaction_add(self, interaction: discord.Interaction) -> None:
        logging.info('hello world!')
        pass

I've looked into some examples but couldn't find the solution. How can I achieve /reaction create command?

green hinge
limber urchin
green hinge
green hinge
limber urchin
#

You didn't explain your problem, all you said is that it doesn't work

green hinge
limber urchin
#

You need to edit the message with the updated view

copper flower
green hinge
limber urchin
#

yes

leaden relic
#

how do you remove specific buttons in a view from another message?

i made the view = discord.ui.View.from_message(message) work but how do i remove an item using their custom id from this point?

green hinge
real frost
#

Hello, i have a question, how to fetch kick
I know that guild have guild.fetch_ban, but have no guild.fetch_kick
So, how to fetch it?

limber urchin
#

Why would you need to fetch a kick?

proud mason
proud mason
limber urchin
#

Audit logs are your best bet, unless you store a log of the kicks yourself

leaden relic
leaden relic
proud mason
proud mason
leaden relic
proud mason
leaden relic
#

ohhhh wait i just understand what you meant 🤣

#

same problem though since my button is in a separate button class so clear item is the best way for me unless i want to make a new view with only a single button

proud mason
#

.rtfm textchannel

proud mason
#

it is there

#

just checked

delicate harbor
#

TextChannel does have a property threads

#

but does it also gives threads which the bot is not part of ?

#

like, the bot has administrator permissions (its for my own server)
but if someone creates a thread then bot is not actually a part of it, you cannot see it in members tab

#

so i am asking whether with TextChannel.threads, will the bot be able to access to all those threads ?
thanks

proud mason
#

.rtfm on_thread

delicate harbor
# winter condor

ah, well i will use it now for future threads.

For older threads i have figured out a way by directly calling discord api with proper authorization, because i saw one or two endpoints of getting all threads whether public or private , archived or active. But ig there isnt any way to do so via pycord right ?

anyways much thanks

real frost
proud mason
ornate current
#
class WarnSystem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @slash_command(name="warn", description="warn command", guild_ids=[guild_id])
    async def warn(self, ctx : discord.ApplicationContext):
        await ctx.respond(content="Yo ok", ephemeral=True)```
help :C
grizzled sentinel
#

.tag idw

winter condorBOT
#

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.

ornate current
#
@bot.event
async def on_ready():

    bot.load_extension('cogs.warn_system')
    
    print("Bot is now online!")

error:
discord.errors.ExtensionFailed: Extension 'cogs.warn_system' raised an error: ClientException: Callback for warn command is missing "context" parameter.

proud mason
#

Don't load extensions on ready

#

Also show pip list

ornate current
#
aiofiles           23.1.0
aiohttp            3.8.4
aiosignal          1.2.0
aiosqlite          0.18.0
anyio              3.6.2
async-generator    1.10
Async-OAuthlib     0.0.9
async-timeout      4.0.2
attrs              22.1.0
autopep8           2.0.0
blinker            1.5
cachetools         5.3.0
certifi            2022.12.7
cffi               1.15.1
chardet            4.0.0
charset-normalizer 2.1.1
chat-exporter      2.5.3
click              8.1.3
colorama           0.4.6
dnspython          2.3.0
emoji              2.2.0
ffmpeg-python      0.2.0
Flask              2.2.3
frozenlist         1.3.1
future             0.18.2
grapheme           0.6.0
h11                0.14.0
h2                 4.1.0
hpack              4.0.0
httpcore           0.16.3
httpx              0.23.3
hypercorn          0.14.3
hyperframe         6.0.1
idna               3.4
imageio-ffmpeg     0.4.7
itsdangerous       2.1.2
Jinja2             3.1.2
MarkupSafe         2.1.2
motor              3.1.1
multidict          6.0.2
numpy              1.23.4
oauthlib           3.2.2
openai             0.26.5
outcome            1.2.0
Pillow             9.4.0
pip                22.3.1
priority           2.0.0
py-cord            2.4.0
pycodestyle        2.9.1
pycparser          2.21
PyJWT              2.6.0
pymongo            4.3.3
PySocks            1.7.1
python-dateutil    2.8.2
python-dotenv      1.0.0
pytz               2022.7.1
Quart-Discord-any  2.2.2b1
requests           2.28.2
rfc3986            1.5.0
roblox             2.0.0
setuptools         65.5.0
six                1.16.0
sniffio            1.3.0
sortedcontainers   2.4.0
toml               0.10.2
tomli              2.0.1
tqdm               4.64.1
trio               0.22.0
trio-websocket     0.9.2
typing_extensions  4.5.0
urllib3            1.26.14
websockets         10.4
Werkzeug           2.2.3
wsproto            1.2.0
yarl               1.8.1```
ornate current
proud mason
#

Like

bot = ...

...

bot.load_extension(...)

bot.run(...)
ornate current
#

alr

#

and i forgot to put self

proud mason
#

Rip lol

proud mason
ornate current
#

oh thanks works now

ornate current
#

removed it after sending that message

#

me dumb

livid wolf
limber urchin
#

The time you've been coding doesn't matter at all, it's about your skill level

young bone
livid wolf
#

So then how would I get the users roles?

limber urchin
#

Why are you fetching the user in the first place? You already have a member object

livid wolf
#

Or does this do it? (to get users roles)

@team.command(description="Send a team invite via DM")
async def invite(ctx, member: discord.Member):
  """Team Member Invite Handler"""
  userRoles = discord.Member.roles(member)
  await ctx.respond(f"{userRoles}") # testing
limber urchin
#

discord.Member.roles ?

#

that's not how it works

proud mason
#

member.roles where member is an object of the class discord.Member

limber urchin
#

You need to know OOP before using pycord

ornate current
#

what are debug_guilds? in slash commands

livid wolf
limber urchin
livid wolf
#

._.

leaden relic
#

object oriented programming

livid wolf
#

ah ok

ornate current
#

i am using guild_ids for now but what are debug_guilds?

limber urchin
#

.rtfm debug_guilds

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

limber urchin
#

.rtfm Bot.debug_guilds

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

limber urchin
#

k

leaden relic
#

it's under slash commands i guess

ornate current
meager heron
#

I've got a bot that's near to the point where I will be forced to shard. According to https://guide.pycord.dev/popular-topics/sharding/#what-is-sharding, all I need to do is change my bot class to AutoShardedBot, which sounds great!

However, I'm seeing another dev (d.js in this case) saying he had to completely rewrite his bot to account for sharding, which has me a little worried.

Are there any special caveats/pitfalls I need to beware when sharding?

full basin
#

Why take into account what someone that uses d.js said when you're using py-cord?

#

And the guide, just like you said, tells you to just change the instance

cyan quail
green hinge
#

Can someone explain to me how to get my Paginator persistens?
Unfortunately it does not work with the on_ready method. I don't get an error message, the print is also printed but the paginator still doesn't work after a bot restart.
Can someone explain me what I do wrong or how I get my Paginator persistent?

class Base(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.persistent_views_added = False
    
    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_views_added:
            self.bot.add_view(await PaginatorInfoView(self.bot))
            self.bot.add_view(SpotDetails(self.bot))
            print("Views added")
            self.persistent_views_added = True

    @commands.command(name="showspot", help="Zeigt alle Spots an")
    async def page(self, ctx):
        paginator = await PaginatorInfoView(self.bot)
        await paginator.send(ctx)
meager heron
cyan quail
#

but you wouldn't need this until you hit like, 10s of thousands of guilds or so

#

sharding alone should be fine for a few thousand

meager heron
#

Cool, thanks

#

I wasn't sure if I'd need to rewrite my database cache, for instance. It doesn't seem like I would, since it's keyed off of guilds and guilds are isolated to shards, but that's why I asked if there are any obvious pitfalls

cyan quail
#

heck, clustering is only possible at 150k guilds probably way less, but point being you shouldn't need to worry

meager heron
#

Unlikely I'll ever get that big. The community I'm serving is small

iron mesa
#

I know that discord implemented a thing where you can send timedate that is displayed in local time zone. Does pycord implement that and if so what is it named or where in docs can I find it?

winter condorBOT
#
<t:1664318247:t>
<t:1664318247:T>
<t:1664318247:d>
<t:1664318247:D>
<t:1664318247:f>
<t:1664318247:F>
<t:1664318247:R>

<t:1664318247:t>
<t:1664318247:T>
<t:1664318247:d>
<t:1664318247:D>
<t:1664318247:f>
<t:1664318247:F>
<t:1664318247:R>

API Reference: https://github.com/discord/discord-api-docs/blob/ff4d9d8ea6493405a8823492338880c47fb02996/docs/Reference.md#timestamp-styles

See discord.utils.format_dt for the discord.py implementation.
https://docs.pycord.dev/en/stable/api.html#discord.utils.format_dt

limber urchin
#

@iron mesa This

iron mesa
#

Thank you!

fervent cradle
#

Is there any method to call when a user is in the server for X days?

#

or any other ways technically

proud mason
limber urchin
#

That way you can only store the members you actually want to track. As opposed to iterating through all members of all servers.

coarse cargo
#

Hey guys, i would like to ask what is the best format for make a config file in python, i tried yaml but it doesnt really convince me

coarse cargo
#

I dont really like the syntax of it as some people that doesnt know anything about coding would probably have some problems using it

coarse cargo
#

I will try .ini ty

limber urchin
#

yaml, json/hocon and ini are probably your best options. Otherwise you'll have to move onto making some sort of graphical configuration interface like a website or another python program that asks the user for values. Depends on how "non-coder" friendly you want to make it.

green hinge
#

Can I not use a local image as a thumbnail in the embed?
The thumbnail is not set but the image is sent large above the embed 🤔

file = discord.File(f"./Fische/{fisch}.png", filename=f"{fisch}.png")
embed.set_thumbnail(url=f'attachment://{fisch}.png')
interaction.response.send_message(embed=embed, File=file)
young bone
green hinge
#

Use \:Emoji Name: in a channel and copy it to your code

still helm
proud mason
#

file=file

#

Also the local file only works for the main image iirc

green hinge
proud mason
green hinge
#

Do I need to pass the embeds and files as a list with my Paginator?

pages.append(page)```
winter condorBOT
solemn idol
coarse cargo
#

Hey there, im trying to use an emoji in a button but it throws Invalid emoji error. This is my code

button = Button(label=f"{ticketpanelconf['button_text']}", style=discord.ButtonStyle.green, emoji=f":{ticketpanelconf['button_emoji']}:")

and this is the data of button_emoji:

button_emoji: incoming_envelope

Anybody knows how to fix it? The format of the emoji looks good to me

coarse cargo
#

The format for the discord emoji isnt :emoji_name:?

young bone
coarse cargo
#

discord

#

📨 this one

#

really struggling with this thing i dont know why it doesnt work

grizzled sentinel
plain cave
#

Hey guys how would I read the contents of a message? like I basically want to do

@bot.slash_command(name = "read", description = "read message back to user")
async def info(message):
    await ctx.respond(message.content)
young bone
plain cave
#

No

young bone
#

also where is the ctx?

plain cave
#

I have a private bot testing server and want to try parsing my own address then passing it to an api and returning the date and time the ISS can be seen from my house

#

I could not get ctx to return the content of my message

young bone
#

Do you know basic python?

plain cave
#

Yes

#

I have been doing python for 3 years

#

Built a website backend in django

young bone
#

I'm asking because you have "ctx.respond" without the ctx in the function

plain cave
#

Ah good call

#

But how do I access the actual message content

young bone
#
async def info(ctx, message):
    await ctx.respond(message)
plain cave
#

It didn't work

young bone
#

Error?

plain cave
#
@bot.slash_command(name = "info", description = "for debugging")
async def info(ctx, message):
    await ctx.respond(message)
#

None

young bone
#

do you have anything else installed than py-cord?

plain cave
#

no

young bone
#

do you use discord.Bot?

plain cave
#

Is that a library or command

young bone
plain cave
#

I forget, it was a while ago

young bone
#

what is the py-cord version?

plain cave
#

2.4.1

young bone
plain cave
#

No

#

Just looked at the list via pip list and no other discord libraries installed

young bone
plain cave
#

No

#

Weird, this implies the command is somehow broken?

young bone
#

that is weird

#

do you use discord.Bot?

plain cave
#

I don't know what that is

#

Oh wait

#

Yes

#
bot = discord.Bot(intents=intents)
young bone
#

can you uninstall and reinstall py-cord?

#

does the bot has the permissions to send messages?

plain cave
#

Yes

#

it has full admin permissions on my server and all intents enabled

#

Wait, I got it to work. I had a hello command that did basically the same thing so I copied it and replaced the name, description, and response fields and now it works?

#

Like the uninstall reinstall did not work but this did

young bone
#

mhm

plain cave
#

Wild

#

I appreciate the help!

young bone
#

^^

silver moat
errant craneBOT
#

Here's the context menus example.

silver moat
plain cave
silver moat
#

.rtfm on_message

plain cave
#

can I combine this with the slash commands?

silver moat
plain cave
#
@bot.slash_command(name = "info", description = "for debugging")
async def on_message(ctx, message):
    await ctx.respond(message)
shut jasper
#

how do you restrict visibility of slash commands to a certain role?
i had the code earlier but i deleted it

silver moat
#

?tag xq

obtuse juncoBOT
#

dynoError No tag xq found.

obtuse juncoBOT
#

An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.

You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.

silver moat
#

.rtfm default_permission

winter condorBOT
plain cave
#

No

silver moat
#

What do you want to happen?

plain cave
#

I am asking if I can have the on message function nested under the slash command decorator so that I don't have to parse out manually the beginning of a command by doing something like `startswith("!flyover")

#

Basically I want to be able to type

/Flyover address

So that the message content only contains the address

silver moat
#

I'm not sure if you understand what a message is and the difference between that of a slash command argument

shut jasper
silver moat
shut jasper
#

i can prevent people from using it tho?

silver moat
#

however, you can add internal checks, but other users without the role can still see it

#

.rtfm commands.has_role

winter condorBOT
shut jasper
#

ok thanks

wary rover
#

Hello!
With this channel: discord.Option(discord.TextChannel, required=True) channels of type Announcement are not displayed. Any idea how to list only these channels?

silver moat
#

.rtfm option.channel_types

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

wary rover
#

Something like this?

channel: discord.Option(discord.ChannelType.news, required=True)
#

No I have an error. :/

#

channel: discord.Option(input_type=discord.ChannelType.news, required=True)

silver moat
shut jasper
#

can someone point me at the doc for making a dropdown?

silver moat
shut jasper
#

so is this where i put my code

#

im making a subscription plan dropdown

silver moat
shut jasper
silver moat
#

see

errant craneBOT
#

Here's the persistent example.

silver moat
#

for how to make views persist through restarts

shut jasper
#

oh ok thanks

shut jasper
#

bot = discord.Bot(intents=intents)

#

im using this instead of a class

silver moat
#

you just have to adapt it.

#
bot = ...
bot.persistent_views_added = False

@bot.event
async def on_ready():
  if not bot.persistent_views_added:
    # add the view
    # set to true
  ...
shut jasper
#

i was getting this when i tried to adapt it thts why i asked

silver moat
# shut jasper

yeah because the Pythonic way would be to inherit/extend it

shut jasper
#

is this bc i didnt do the perisitent views added?

silver moat
shut jasper
#

no custom id?

#

hm lemme try to find

silver moat
#

send code for the view you are trying to make persistent

shut jasper
#
class PlanView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.select(
        row=1,
        options=plan_options,
        placeholder="Choose a plan",
    )
    async def select_callback(self, select, interaction):
        chosen_plan = next((plan for plan in plans if plan["stripe_price_id"] == select.values[0]), None)
        if chosen_plan:
            await interaction.response.send_message(f"You've chosen the {chosen_plan['name']} plan.")
        else:
            await interaction.response.send_message("Something went wrong. Please try again.")```
#

this?

#
plan_options = [
    discord.SelectOption(label=plan["name"], value=plan["stripe_price_id"])
    for plan in plans
]```
silver moat
shut jasper
#

is it per option or for the whole thing?

silver moat
shut jasper
#

oh ok

#

can be anything?

silver moat
#

some string with a 30 (I think) character limit

shut jasper
shut jasper
#

ugh i decided to do a form instead based on member feedback so thats gonna be fun now

#

.rtfm modal

shut jasper
#

SelectMenu isnt available in modals?

#

guess not

#

well there goes that plan

young bone
ocean pumice
#

Hey, when doing options with slash command, integer-only ones don't accept server IDs like 996922553266360360. Any thoughts why?

#

Is it viable to just make them integers in the code?

limber urchin
#

Because discord doesn't support numbers that large, you need to take a string and parse it in your code

ocean pumice
#

Okey, thanks

nocturne canopy
#

is there a way to count how many messages one user sent in a server? or do i need to recursively search in every channel for the last 9 million messages and see how many match the user?

soft girder
#

Is it possible to write such a code that the button turns off at a certain time.

proud mason
#

.rtfm view.on_timeout

winter condorBOT
proud mason
#

subclass and override that

#

disable the button you want in the view, and edit the msg

proud mason
#

there is not recursion in this tbh...

#

simple plain looping

nocturne canopy
#

yeah that's what i was talking about, iterate i think is the word i was looking for

#

weird how that's not possible, since a normal user can just search messages from x and it spits out the whole history

fervent cradle
#

Hi

#

It this possible? I want to make sure before I try making it

#

a persistent view with a drop down of 3 items

#

If user chooses item it’ll show two buttons

#

If user chose a button it will run my code

#

However when you press the button I need the value of the item they chose in the dropdown

silver moat
#

yes

fervent cradle
silver moat
#

yes

proud mason
nocturne canopy
#

boowomp

silver moat
#

So libraries implemented their own version of it

proud mason
#

ayo did they?

#

||which one?||

#

👀

silver moat
#

history?

#

.rtfm channel.history

soft girder
#

what?

silver moat
#

.rtfm view.timeout

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
silver moat
proud mason
# soft girder

oh yeah just set disable_on_timeout to True and set timeout as the number of seconds after which the buttons should be disabled

coarse cargo
#

Guys i have a view in a subclass and then a slash commands that should use the view of that class, but when i try to define the view with view=PanelView() it says its undefined. Any idea?

proud mason
#

also full traceback please

#

also are you using the correct version of the file? ||and did you save the file 💀 ||

coarse cargo
coarse cargo
# proud mason also full traceback please
Ignoring exception in command ticketpanel:
Traceback (most recent call last):
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
    ret = await coro(arg)
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 766, in _invoke
    await self.callback(ctx, **kwargs)
  File "c:\Users\Federico\Desktop\TicketBot\bot.py", line 152, in ticketpanel
    await channel.send(embed=embed, view=PanelView())
NameError: name 'PanelView' is not defined

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

Traceback (most recent call last):
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
    await ctx.command.invoke(ctx)
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
    await injected(ctx)
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: NameError: name 'PanelView' is not defined
#

You want the code?

#

Idk

proud mason
#

yes was gonna say just that 😂

coarse cargo
young bone
#

also view = Menu()?

silver moat
coarse cargo
coarse cargo
#

Thanks to all of you, i fixed it.

graceful mortar
#

Hey, you can make SlashCommandGroups. If I now create a group with e.g. "test", is there a possibility to use only the /test? And then /test 1, 2 etc. as well.?

graceful mortar
#

Sure, but there is only /greetings (hello, aloha), and I would like to be able to do only /greetings if possible.

proud mason
#

it is because of the fact that subgroups are technically just option choices of the parent command

#

discord clients just render them differently

graceful mortar
#

Ah okay, all right. thx 😄

novel jay
#

bot.get_channel(123) also works for categories, right?

full basin
#

Yes

novel jay
#

thx

fervent cradle
#

If an embed raw has the "contents" value, will it also be added as a message while using from_dict or will be ignored?

silver moat
novel jay
#

The function input bot on __init__ in a commands.Cog cog is the type of commands.Bot yes?

silver moat
novel jay
#

when loading from bot.load_extension("cogs/cog")?

silver moat
#

yes

novel jay
#

interesting

#

ohhhhhh i see it now

#

god im a dumbass xD

silver moat
#

iirc it is only there for you to access the bot object

novel jay
#

yeah

solemn idol
#

I am genuinely confused,

file = discord.File(f"assets/gifs/no.gif", filename=f"no.gif")
            em = discord.Embed(title="Error!", description="Why would I do that?.", color=em_red)
            em.set_image(url="attachment://no.gif")
            await ctx.respond(file = file, embed=em)

So for some reason, I cannot add images (gifs) to my embed, otherwise it will give me the error code :
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

solemn idol
#
# Mute
    @commands.has_permissions(moderate_members = True)
    @discord.slash_command(name = "mute", description = "Mutes a member.")
    @option("user", discord.Member, description="Choose a member.",)
    @option("reason", description="Reason for the user to be muted.", default="No reason provided", required=False)
    @option("days", description="Time for the user to be muted in days (optional).", required=False, default=0)
    @option("hours", description="Time for the user to be muted in hours (optional).", required=False, default=0)
    @option("minutes", description="Time for the user to be muted in minutes (optional).", required=False, default=0)
    @option("seconds", description="Time for the user to be muted in seconds (optional).", required=False, default=0)
    async def mute(self, ctx, user: discord.Member, reason: str, days: int, hours: int, minutes: int, seconds: int):
        unix_time = int(time.time())
        try:
            duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
        except OverflowError:
            file = discord.File(f"assets/gifs/no.gif", filename=f"no.gif")
            em = discord.Embed(title="Error!", description="Why would I do that?.", color=em_red)
            em.set_image(url="attachment://no.gif")
            await ctx.respond(file = file, embed=em)
            return
        user_role = discord.utils.get(user.roles, name='Muted')
        mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
        if user.id == ctx.author.id:
            em = discord.Embed(title = "Error!", description = "You can't mute yourself, " + random.choice(insult), color = em_red)
            await ctx.respond(embed = em, ephemeral = True)
            return
...
#

its a mute command, but yeah the rest should be pretty irrelevant

#

just ping me if you have a solution ig

silver moat
solemn idol
silver moat
#

oh just using ctx.user removes this warning

shut jasper
#
plan_options = [
    discord.SelectOption(label=plan["name"], value=plan["stripe_price_id"])
    for plan in plans
]

# create a view for a dropdown for each plan in plans.yml
class PlanViewTest(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.select(
        row=1,
        options=plan_options,
        placeholder="Choose a plan",
    )
    async def select_callback(self, select, interaction):
        chosen_plan = next((plan for plan in plans if plan["stripe_price_id"] == select.values[0]), None)
        if chosen_plan:
            await interaction.response.send_message(f"You've chosen the {chosen_plan['name']} plan.")
        else:
            await interaction.response.send_message("Something went wrong. Please try again.")
#

im super confused with this, how do i make it so i can send code for each of the different options?

#

basically i need to have a changeable amount of options (plans that the user configures) so i have to use a for loop?

errant craneBOT
#

Here's the dropdown example.

shut jasper
#

i get that, but i need to have it scale for however many plans the user configures @silver moat

#

the example defines a set amount of plans

#

maybe i should say the end goal

#

a dropdown which spawns two buttons (one for one time payment and another for subscription), that button will open a modal asking for the users email, then it replies with a invoice link

#

but the invoice needs to know what plan to charge the user for

silver moat
#

imo this seems very insecure over a discord bot. Consider using a website with stripe instead.

shut jasper
#

hows it insecure?

#

i currently use a paid solution which uses a website but i want my own via a bot

#

payments are processed via a stripe invoice

#

api key is restricted in permissions

silver moat
#

well, I think it looks suspicious. Mostly because Discord Bots have been known to be involved with scams and such

shut jasper
#

i have a good reputation in the community i sell in, hundreds of reviews

#

but ye i get what you're saying

#

i dont believe its against discord tos as other popular payment bots exist

silver moat
#

well, you have the selected option(s) what else do you need?

shut jasper
#

well i need to create a two buttons after the user choses (which i can do)

#

then make a modal

#

i get that part

#

however i dont know how to then fetch what plan they chose after they submit email via modal

#

without manually setting up each option in the dropdown, which i cant do because i need to loop through all the user's plans

silver moat
#

just pass it as an argument through?

shut jasper
#

how do i do that?

#
plan_options = [
    discord.SelectOption(label=plan["name"], value=plan["stripe_price_id"])
    for plan in plans
]

# create a view for a dropdown for each plan in plans.yml
class PlanViewTest(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.select(
        row=1,
        options=plan_options,
        placeholder="Choose a plan",
    )
    async def select_callback(self, select, interaction):
        chosen_plan = next((plan for plan in plans if plan["stripe_price_id"] == select.values[0]), None)
        if chosen_plan:
            await interaction.response.send_message(f"You've chosen the {chosen_plan['name']} plan.")
        else:
            await interaction.response.send_message("Something went wrong. Please try again.")
            #make a slash command to spawn the PlanViewTest```
#

i dont see where i could put the arguement in the for loop

#

sry im not that good with python

#

this took me like 8 hours to make

silver moat
#

Do you know basic Python OOP?

shut jasper
#

probably not rlly

silver moat
shut jasper
#

i dont get it

silver moat
# shut jasper oh

Pycord is an advanced python library. You should have a solid understanding of fundamentals before starting to integrate with pycord.

vapid pumice
#

I'm having an issue when trying to host my bot that I actually ran into a few weeks ago.

I am getting:

"ImportError: cannot import name 'option' from 'discord' (/usr/local/lib/python3.10/dist-packages/discord/init.py)"

I have py-cord 2.4.0 installed, and my code is working just fine on my windows system, but it is getting hung up in my ubuntu system. I did a normal pip freeze, ported reqs, and now have encountered this issue.

Any clue what might cause this? Before, the problem was that my py-cord lib needed an update, but that's not the case here

wary rover
#

Hello!
I have a small question.

From a list of ID I get a list of channels.
I then try to do an auto completion but impossible to propose a custom channel list, any idea?

#

I am forced to give a list of channel names and retrieve the channel a second time, with the risk that the name is duplicated.

proud mason
#

also uninstall py-cord and reinstall it

#

see if that helps

proud mason
#

.rtfm optionchoice

winter condorBOT
wary rover
vapid pumice
bitter gull
#

sorry, why does the footer is not mentioned? I did set the footer's text to

"By: {ctx.author.mention}"
storm oyster
#

Footers can't mention users

#

Instead you could just do ctx.author

bitter gull
#

aw rip

#

yeah ctx.author.display_name should be fine huh...

ornate current
#

how can i make slash commands limited to certain roles

proud mason
winter condorBOT
ornate current
#

doesn't seem to work

#
    @warn_class.command(name="view", description="Shows all the warns for a specified user", guild_ids=[guild_id])
    @commands.has_role(1088420607877730314)
    @discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to view warns for", required=False)
    async def view(self, ctx : discord.ApplicationContext, member):```
#

@proud mason

#

no error

#

i want it so it only shows up for certain people

#

i could do it in js but not in py.. why?

young bone
#

Only for permissions

ornate current
#

and for permissions

#

ye tell me what should i use

young bone
#

discord.default_permissions

fervent cradle
ornate current
#

should i use bot.dispatch? is it good to use it?

limber urchin
#

Why would you?

proud mason
ornate current
#

I am trying to make an on_warn event

#

to make it organized

#

instead going on each command and doing stuff there

#

so what would you suggest?

limber urchin
#

Can't you just call the on_warn method in those places?

chrome skiff
#

has somebody a list of discord code block colors?

young bone
#

there is not a list of code block colors

chrome skiff
#

i mean like

#

is there a list like
language --> color

young bone
#

google it ;3

limber urchin
#

Those are markdown syntax colors

#

Has nothing to do with Discord, and you can't control them

#

And there isn't a "list" of colors, the colors are decided by the syntax highlighting of the language you're writing in

fervent cradle
#

hey i was wondering, is there a way to mock and an interaction, like for example button press interaction, lets say i have a button and if the user does not press it in 20 seconds the bot can press it as it was the user who pressed it

solemn idol
#
em = discord.Embed(title = 'Test Embed!', description = 'Hell yeah', color = em_green) # em_green is a variable to hex color and works fine.
em.set_author(name=self.bot.user.name, # The Bot's Name (works fine, self because this embed is in a cog.)
url='https://google.com', # Here this is my issue, the Author name above, should become clickable in the embed, but for some reason it just doesn't
icon_url=self.bot.user.display_avatar.url) # The Bot's Avatar (works fine too, self because this embed is in a cog.)

What am I doing wrong with my url='https://google.com'

I mean https://google.com is a valid Url... so I am really confused here, docs say I can include url too soo... Yeah. I have no idea what I am doing wrong.

#

Oh my god I am an idiot. I made 2 embeds and it took the first one bigbrain

#

No more help needed facepalm

proud mason
#

Unless the callback is user indifferent

fervent cradle
#

well as of the moment let's say that i know 100% who is supposed to press it

#

it's some sort of turn based "game"

#

i just want to add a time for the turn, so the player doesnt intentionally make others wait

proud mason
#

If what you want to do it do stuff when button is pressed or 20s have passed and button not pressed, then what i was thinking is

For normal button press, call another function from the button and pass interaction.

For timeout,
Set view timeout to 20s. In the on_timeout method of the view, create any object (even object()) that has the parameters you would use from Interaction and then pass that to the function you would call from normal button press

#

Since python uses duck typing, the actual class won't matter

proud mason
fervent cradle
ornate current
#

slash commands doesnt load. it loads in the first cog the main.py file loads but not the others

#
cogs = [ 
        "cogs.moderation_settings", #this cog has one command (and it works)
        "cogs.warn_system"]# this cog has 4 commands (doesnt load)


for filename in cogs:
    bot.load_extension(filename)```
winter condorBOT
# ornate current ```py cogs = [ "cogs.moderation_settings", #this cog has one command (a...

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

ornate current
#

and what do you mean by on_connect overriden

#

its not like all my commands are not loading its just that one cog

proud mason
#

Can you show thag cog?

#

Is the setup function being called?

ornate current
#

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

    modsettings_class = discord.SlashCommandGroup(name="modsettings", description="Everything related to moderation settings. Can only be set up by admins.", guild_ids=[guild_id])

    @modsettings_class.command(name="mod", description="Edit moderator roles", guild_ids=[guild_id])
    @discord.option(name="action", description="Choose actions to do moderator roles" ,autocomplete=["add", "view", "remove"])
    @discord.option(name="role", description="Role to do actions for. There is no need of this field if using the action \"view\"." ,autocomplete=modactions)
    async def mod(self, ctx, role):
      #code
def setup(bot):
    bot.add_cog(ModSettings(bot))```

cog 2
silver moat
ornate current
#

nope on _ready

#
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import time
import aiosqlite
from discord.ext import tasks
load_dotenv()
TOKEN = os.getenv("DISCORD_BOT_TOKEN")
guild_id = os.getenv("GUILD_ID")
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents, case_insensitive=True, debug_guild=guild_id)
bot.remove_command('help')
cogs = ["cogs.auto_actions", 
        "cogs.moderation_settings",
        "cogs.warn_system"]



    

@bot.event
async def on_ready():
    print("Bot is now online!")

for filename in cogs:
    bot.load_extension(filename)```
silver moat
#

I’m assuming modactions is defined

silver moat
ornate current
#
class WarnSystem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    warn_class = discord.SlashCommandGroup(name="warn", description="Everything related to... warns.", guild_ids=[guild_id])



    @warn_class.command(name="add", description="Warns a specified user", guild_ids=[guild_id])
    @discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to warn")
    @discord.option(name="reason", type=str, description="Reason to warn the user", required=False, min_length=1, max_length=300)
    async def add(self, ctx : discord.ApplicationContext, member, reason : str=None):
      pass
    @warn_class.command(name="remove", description="Removes a warn for the specified user", guild_ids=[guild_id])
    @discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to remove a warn for")
    @discord.option(name="warn id", type=discord.SlashCommandOptionType.integer, description="The warn to remove")
    @commands.has_permissions(administrator=True)
    async def remove(self, ctx : discord.ApplicationContext, member, warnid):
        pass
    @warn_class.command(name="view", description="Shows all the warns for a specified user", guild_ids=[guild_id])
    @discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to view warns for", required=False)
    async def view(self, ctx : discord.ApplicationContext, member):
        pass
    @warn_class.command(name="clear", description="Clear all the warns for a specified user", guild_ids=[guild_id])
    @discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to clear warns for", required=False)
    async def clear(self, ctx : discord.ApplicationContext, member):
        pass

def setup(bot):
    bot.add_cog(WarnSystem(bot))```
silver moat
#

because debug_guild was removed way before alpha 1

ornate current
#

using 2.4.1

#

i even removed debug_guild

#

guild ids is an integer

silver moat
ornate current
#

oh hum

silver moat
#

autocomplete takes a coroutine with an argument of AutocompleteContext

errant craneBOT
#

Here's the buttons example.

red geyser
#

bruh

errant craneBOT
#

Here's the confirm example.