#General Help

1 messages · Page 18 of 1

analog elk
#

I want to edit a message with a view by clicking on one of the buttons. I have that part implemented, but the buttons stop working after the message is edited

ornate fog
#

its not edit

#

its edit_message

languid hollow
languid hollow
#

or doesn't interact at all?

analog elk
languid hollow
#

can you send the code pls

analog elk
#

see the issue is theres a lot of working parts but ill do my best

ornate fog
languid hollow
#
    await interaction.followup.edit_message(view=self)
TypeError: edit_message() missing 1 required positional argument: 'message_id
analog elk
#
class CountryApprovalView(discord.ui.View):
    """A view attached to country approval messages which adds an approve and deny button to the message."""
    def __init__(self, user: discord.User, timeout):
        super().__init__(timeout=timeout)
        self._user = user
        self.approver = None
        self.reason = None
        self.deleter = None
        self.edit_interaction = None
...

    @discord.ui.button(label="Edit", style=discord.ButtonStyle.blurple)
    async def third_button_callback(self, button: discord.Button, interaction: discord.Interaction):
        if self._user.id == interaction.user.id:
            self.edit_interaction = interaction
            self.stop()

        else:
            await interaction.response.send_message(f"You do not have permission to edit this claim!", ephemeral=True)

...

#
class PlayableAddModal(Modal):
  ...

    async def callback(self, interaction: discord.Interaction): # TODO: Add ability to edit claims
        embed = children_to_embed(self.children, self._entity, interaction.user)
     
        approval_view = views.CountryApprovalView(interaction.user, timeout=None)
        approval_channel_id = io.load_approve_channel(interaction.guild_id)

        approval_channel = await interaction.guild.fetch_channel(approval_channel_id)
        claim_msg = await approval_channel.send(embed=embed, view=approval_view)
        await interaction.response.send_message(f"Claim successfully added! An admin will approve you in <#{approval_channel_id}>.", ephemeral=True)

        await approval_view.wait()

        approve_button = approval_view.children[0]
        deny_button = approval_view.children[1]
        edit_button = approval_view.children[2]
        delete_button = approval_view.children[3]
        orig_msg = await interaction.original_message()

        ...

        elif approval_view.edit_interaction:
            modal = EditClaimModal(self._fields, self._entity, embed, title="Edit your claim")
            await approval_view.edit_interaction.response.send_modal(modal)
            await modal.wait()
            await claim_msg.edit(view=views.CountryApprovalView(interaction.user, timeout=None), embed=modal.embed)

#
class EditClaimModal(Modal):
    def __init__(self, fields: Dict[str,List[InputText]], entity: str, embed: discord.Embed, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._fields = fields
        self._entity = entity
        self.embed = embed

        for entity, list in self._fields.items():
            if entity != "All" and entity != self._entity:
                continue
            for input_text in list:
                for field in embed.fields:
                    if field.name.removesuffix(" Description") != input_text.label:
                        continue
                    input_text.value = field.value
                    break

                self.add_item(input_text)
                
    async def callback(self, interaction: discord.Interaction):
        self.embed = children_to_embed(self.children, self._entity, interaction.user)
        await interaction.response.send_message("Successfully edited claim!", ephemeral=True)
        self.stop()
#

here are the relevant bits of code

#

it passes the button edit interaction from the view into the modal callback

languid hollow
#

I presume self.stop() makes the button not to be used?

analog elk
#

self.stop() is what triggers await approval_view.wait() to stop waiting

#

so the code continues

#

at least, to my understanding that's what it does

#

the other buttons that work fine also have self.stop() in them

ornate fog
#

yes it does

#

but it also terminatesthe view

#

*terminates the view

analog elk
#

ah

#

i see

languid hollow
#

wait

ornate fog
#

no further interactions will be dispatched on this object

analog elk
#

mihito that makes sense

languid hollow
#

maybe I can use that for mine

#

I learnt something new, let's try that

analog elk
#

how do i continue past self.wait() without self.stop()?

#

lemme try deleting the wait

#

ok deleting the stop and wait just breaks it

#

so it is needed

#

I also tried creating a new view and editing the message with the new view of the same type as the old view

#

but that also didnt work

ornate fog
# analog elk mihito that makes sense

I also dont like the callback hell comming with views.
My approach to this issue in my bots is to make an AwaitableView that all views inherit from.

In the base view there is a asnycio.Future that is set when a callback is executed you just have to await the future in your waiting code and boom es soon its set your main code executes.

Without needing to call .stop() so you could reuse the view if you want. I dont do that but it would be possible.

analog elk
#

wym by the callback hell?

ornate fog
#

alot of callbacks

analog elk
#

doesn't every button need a callback?

analog elk
ornate fog
#

yea but i like to have my main logic in my command and not in button callbacks.
I dont want to jump with my logic from callback to callback.
the asyncio.Future approach modifies my views in a way that they only there for data grabbing and the data is returned back to my main command.
This way views are more modular and you can use the same view for other things even if the command logic is completely different.

analog elk
#

i can see where you're coming from, this code is kinda spaghetti with how much everything jumps around

#

i just couldn't think of better ways to do it

#

my original solution was to have the view classes defined in the modal code but i don't think I can do that because I need to make the country approval view persistent

ornate fog
#

hm yea

analog elk
#

because of how it works

#

it's just

#

a nightmare

#

the process of the command is:
use /claim, which sends a dropdown view
the dropdown options each send a modal
the modal then sends a message with a view to a different channel
when one of the buttons is clicked in the channel with the view, a message notifying the user is sent in the channel the claim was originally made in

languid hollow
#

any idea on how to get the Message ID on the message that the bot sent?

analog elk
#

everything is working as intended except editing the claim message and also making the approval view consistent

languid hollow
#

there is the get_message()

#

but I'm not sure how to use it

analog elk
#

iirc

#

or the interaction

#

you can get it from that

#
interaction = await ctx.respond("foo")
interaction.message.id
languid hollow
#

oh

#

awesome thxs!

analog elk
#

np

#

hours and hours of staring at the api trying to get code to work seems to be getting into my brain

languid hollow
#

honestly same

#

I have been learning pycord for about a week or 2 and the number of things are already clogging my brain blobpain

analog elk
#

i cant believe how much code i have written for my bot

#

the devil is in the details

ornate fog
#

xD

analog elk
#

making it as user friendly as possible really adds an extra level of difficulty

ornate fog
#

True

analog elk
#

especially since this is for like

#

one server

ornate fog
#

Ah nice

#

Comission ?

analog elk
#

For fun

#

and for practice

ornate fog
#

Ah

analog elk
#

it's a good project to put on my github

ornate fog
#

but we getting offtopic

analog elk
#

and i used to be active in the community

#

Tru

ornate fog
#

we will get bonked

analog elk
#

also yo wait

languid hollow
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "<Authorising timeout=None children=2>" is not snowflake.
#

I got this error now after using

await interaction.followup.edit(view=self,message_id=self)
sudden path
#

message_id=self?

languid hollow
#

yes, idk if I'm doing it correctly

#
Options = Authorising()
Options.message  = await channel.send(role.mention, embeds=[embed],view = Options)
Options.id = Options.message.id
analog elk
#

try interaction.edit_original_message()

#

if you want to edit the original message

languid hollow
#

don't I need followup?

analog elk
#

dont think so? try followup if that doesnt work

languid hollow
#

since I already used a response to send a modal

#

and you can't send modals using followups

analog elk
#

can you send the full code? and what you are trying to do specifically?

languid hollow
#

let's go, that worked

languid hollow
analog elk
#

Ah, ok

#

good to see that it worked

languid hollow
#

thanks!

languid hollow
#

or dropdown menus

analog elk
#

I do

#

i use modals, dropdown menus, and buttons

languid hollow
#

i meant as in for the button thing

analog elk
#

ohh

#

well

#

it does

#

the edit button sends a modal with the fields filled in by default to match the existing claim message

#

so it "feels" like you're editing it more

languid hollow
#

oh so I believe that you want the button to the like more of the interaction staying at only one message thing?

analog elk
#

can you please rephrase that?

craggy rapids
#

all of the task is asyncronous but i think it does

#

always got discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction while background task is running

languid hollow
#

i believe you want it to be on the same message that it is on?

analog elk
#

the same message that it is on?

languid hollow
#

e.g.
I'd change the message above the message and use the button that is there to be how the user interactions

analog elk
#

Ohhhh

#

yes

#

i want the button to edit the message that the button is on

languid hollow
#

I see hmm

languid hollow
analog elk
#

like where it says elif approval_view.edit_interaction:?

slender lintel
#

is the discord.Option "required" default to True or False

slender lintel
#

#How can I give someone rights to commands if they have rights to a voice channel?

#

Can someone help me?

analog elk
#
            for child in self.children:
                if child is not button:
                    self.remove_item(child)
#

for some reason this doesn't remove all the buttons

#

it always leaves one

#

is it because self.children becomes smaller as you loop through it, thus skipping over elements?

#

yep that was it

#

fixed it by doing self.children = [button]

desert dagger
#

any ideas why cogs slash commands randomly stop working?

  • I can verify the cogs are setup right
  • if i move commands into my main.py (removing self etc) it works fine
  • Slash commands DO show up. however i get "The application did not respond"
analog elk
#

How can I get around embed fields having a character limit of 1024?

desert dagger
#

There isnt rly a way to bypass unless u treat description as fields

analog elk
#

Thank u

#

description is perfect

warm jungle
#

does anyone know how to make a slash command only disabled in the dms but not in servers

keen hamlet
#

guys, how many maximum number of embeds can i send via a paginator
thankyou

icy sluice
#

yeah I can’t find the examples

south ermine
upbeat hill
#

any idea why it wont send this embed after hitting a button?

snow citrus
#

interaction.response.send_message(embed=embed)

warm jungle
carmine portal
#

Hello !
I want to make a choose menu but i don't found it online so i came here to ask you
if u need code or informations ping or dm me !

reef iron
#

Unions don't seem to work anymore for User/Member in release candidate 1, does anyone know why or a fix?
For example:
user: Option(typing.Union[discord.Member, discord.User], _("The user you want to unban."), required=True)
Returns:
TypeError: issubclass() arg 1 must be a class

upbeat hill
#

how would you fix this

snow citrus
#

reduce length of text

upbeat hill
crude rampart
#

how to create global slash commands (in all servers that the bot is in)

humble talon
upbeat hill
#

how do you put a link button in a class without a callback?

opaque marsh
#

anyone know how to find the inviter everytime someone join a guild?

worthy basin
#

You have to check if an inviters list of invitees includes the user

#

guild.invites returns a list of invites in the guild. Than every time a use joins find what invite count increased than find the author

crude rampart
#

Why do slash commands become invalid after being run once and requiring bot to restart

worthy basin
worthy basin
#

Also make sure you are on the latest version 2.0.0rc1

crude rampart
# worthy basin Can you show your code please
import discord
from discord.ext import commands
from discord.ext import bridge
import pymysql
import yaml

# Discord Bot Section

with open('token.txt','r',encoding='utf8') as tokenfile:
    token = tokenfile.read().strip()

bot = discord.Bot(prefix='.',intents=discord.Intents.all())

@bot.event
async def on_ready():
    pass

@bot.slash_command(guild_ids=[some_guild_id])
async def test(ctx,var1):
#    await ctx.respond(f'{ctx.interaction.channel.name}\n{ctx.interaction.message}')
    await ctx.interaction.channel.send(f'test\n{var1}')
    await ctx.delete()

bot.run(token)
crude rampart
worthy basin
#

Do you want to use prefix or bridge?

crude rampart
worthy basin
#

Try removing the discord.ext import commands import

crude rampart
worthy basin
#

So after running it once the next time you use the slash command it says "The command did not respond" or something similar

#

Do you only want slash commands or are you planning on using bridge to have both prefix and slash?

crude rampart
upbeat hill
#

is there a better way to add the buttons to the embed?

worthy basin
#

Ok Bridge is kind of buggy sometimes so I think that is a fair decision. I show you a few things you need to change in a moment

crude rampart
worthy basin
crude rampart
#

Pip showed that I have discord.py installed.
I ran sudo pip3 uninstall discord.py
Now it is telling me that module discord has no attribute bot

worthy basin
worthy basin
slender lintel
#

Hey how i can block mass DM raid?

inner iris
crude rampart
crimson gale
crude rampart
slender lintel
# inner iris wdym?

If someone start a raid and send everyone on my server a DM. How can I block that?

frigid lark
worthy basin
inner iris
#

You can't do that with a bot.
And you can't really block that afaik.
But you can take certain measures to prevent people from raiding your server.
First would be the Moderation setting of you server.
And actually I can't think of more right now xD

#

@slender lintel

worthy basin
#

Yeah you can't detect someone send DMs to server users. You could have a report command though.

vagrant mortar
#

Is there an Option to only show Threads, and not all Channels?

inner iris
slender lintel
inner iris
#

Wie du willst. Höchste ist am sichersten aber auch am stressigsten für normale Nutzer. Musst nen gutes zwischending finden.

slender lintel
#

Okay danke

inner iris
#

np

ornate fog
#

Channel slash options seem to be broken in 2.0.0b7
Is it save to upgrade to 2.0.0rc1 or does it have any breaking changes ?

slender lintel
#

Nope it works fine

earnest sail
#
    @commands.Cog.listener()
    async def on_application_command_error(self, ctx: discord.ApplicationContext, error: Exception):
        if type(error) is discord.errors.ApplicationCommandInvokeError:
            error: discord.errors.ApplicationCommandInvokeError
            if type(error.original) is PlayerNotPlaying:
                return await ctx.interaction.response.send_message('Nenhuma sala desse jogador foi encontrada!',
                                                                   ephemeral=True)
            if type(error.original) is ProfileNotPublic:
                return await ctx.interaction.response.send_message(
                    'Seu perfil não é público! os comandos não irão funcionar!',
                    ephemeral=True)
            if type(error.original) is NoLobbies:
                return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)

I want to know why this is still printing to stderr?

#

it is handling the error, but still printing to stderr

ornate fog
#

you dont overwrite the listiner that is present in discord.Bot

#

All listeners are dispatched not just one.

#

And the one in discord.Bot prints to stderr

#

override bot and everride the mehtod to return

lucid harbor
#

anyone know how to make a url button in sub-class view?
seems i cant make it with the decorator

    @discord.ui.button(label='official', url='link')
    async def btn2(self, button, interaction):
        pass
earnest sail
#

that makes sense

ornate fog
earnest sail
# ornate fog override bot and everride the mehtod to return
class CustomBot(discord.Bot):
    async def on_application_command_error(self, context: discord.ApplicationContext, exception: discord.DiscordException) -> None:
        if self.extra_events.get("on_application_command_error", None):
            return

        command = context.command
        if command and command.has_error_handler():
            return

        cog = context.cog
        if cog and cog.has_error_handler():
            return

tried this and i'm still getting the same issue

slender lintel
#

How can I make my bot react to every new msg in a channel with name

ornate fog
earnest sail
#

I did

#

still the same issue

#

I am using cogs

#

if that's something to do with it

ornate fog
#

and you initiating custom bot ?
Not an other instance ?

earnest sail
#

yes

ornate fog
ornate fog
earnest sail
#

every cog has a listener attached to on_application_command_error but none of them prints to stderr

earnest sail
ornate fog
#

nah the one you return

#

the default one

earnest sail
#

ok

#

well, the stderr output is coming from somewhere else then

#

I just don't know where

ornate fog
#

can you show full traceback ?

earnest sail
#

you know... it's actually not printing how it's supposed to print if it was on_application_command_error

ornate fog
#

the error raises in your error handler

#

thats why its still printing

earnest sail
#

what

ornate fog
#

ignoring exception IN on_application_command_error

earnest sail
#

how is that possible

#
    @commands.Cog.listener()
    async def on_application_command_error(self, ctx: discord.ApplicationContext, error: Exception):
        if type(error) is discord.errors.ApplicationCommandInvokeError:
            error: discord.errors.ApplicationCommandInvokeError
            if type(error.original) is PlayerNotPlaying:
                return await ctx.interaction.response.send_message('Nenhuma sala desse jogador foi encontrada!',
                                                                   ephemeral=True)
            if type(error.original) is ProfileNotPublic:
                return await ctx.interaction.response.send_message(
                    'Seu perfil não é público! os comandos não irão funcionar!',
                    ephemeral=True)
            if type(error.original) is NoLobbies:
                return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
#

there's my full handler

#

with the NoLobbies exception, it should run

return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
#

and it is working

ornate fog
#

File "C:\Users\Diego\PycharmProjects\KajunRewrite\kajun\lobby_steam_init_.py", line 106, in lobbies
raise NoLobbies
The problem seems to be here.
Im not sure where the problem arraises but the traceback clearly says its in your error handler

earnest sail
#

that's where it's supposed to be raised

#

I thought the on_application_command_error would catch it

#

so that's not how it works?

ornate fog
#

yea it raises and the error handler is called.
that it gets raised in on_application_command_error again

earnest sail
#

what

sudden path
#

You're using a listener cog. Cogs run with the "normal" listener present on the Discord.Bot instance. You're not overridering it.

earnest sail
#

what is the name of the method?

#

oh I see what he meant

ornate fog
#

on_application_command_error

earnest sail
#

yeah, I'm overrinding the original one on the bot

#

but I don't get how it is being raised again

#

"however it could be overridden to have a different implementation."

ornate fog
#

thats what you did

earnest sail
#

that's what I did and I'm still getting the stderr output

#

so it could be a bug on pycord itself then?

#

or the documentation is wrong

ornate fog
#
    async def on_application_command_error(self, context: ApplicationContext, exception: DiscordException) -> None:
        interface = ContextInterface(entity=context)
        self.dispatch("handle_error", interface, exception)

I do it like this and it works like charm

#

So i dont think its a pycord problem

earnest sail
#

what is that?

#

your overrinding the method on the bot?

ornate fog
#

yep

#

handle_error is a custom listener

earnest sail
#

well, what I did was return None

ornate fog
#

i return none implicit its the same

#

if you dont return anything python will return None automaticly

earnest sail
#

yeah

#

that's what I did

#

still somehow getting stderr output

slender lintel
#

What's wrong with it?

@bot.command()
async def pers(ctx):
    category = bot.get_channel(985544678755663912)
    if ctx.author.permissions_in(category).manage_channels:
        await ctx.send(f"Perms test erfolgreich")
    else:
        await ctx.send(f"Nicht erfolgreich")
ornate fog
#

can you remove all cog on_errors for testing ?

#

And look if you still get an error ?

#

or if the bot just swollows it

#

how it should be

earnest sail
#

well... if I do that i'm gonna get an error, won't I?

#

since my errors are being handled on the cogs error handlers

ornate fog
#

if you overriding the default handler you should not

earnest sail
#

I see

#

i'll try that

ornate fog
slender lintel
ornate fog
#

you overriding the default handler ? for errors ?

earnest sail
#

removed the error handler on that cog, still getting stderr output

ornate fog
#

dafuq

earnest sail
#

I'm gonna run only that cog

ornate fog
#

this also exists but i dont override it either and i dont get stderr

earnest sail
#

interesting

#

now I'm not getting stderr output

ornate fog
#

aaaaaaaaaaaaaaaaaaaaaah

#

wait

earnest sail
#

so what the hell is happening

ornate fog
#

ahhhh

earnest sail
ornate fog
#

this one is cog specifc

earnest sail
#

so by running only the cog I removed the error handler, the overridden method worked

ornate fog
#

But im no sure if this is working with app commandss

earnest sail
#

well

#

gonna try that

#

on_cog_command_error then?

ornate fog
#

i think so

#

then docs are fucked

earnest sail
#

I didn't get any stderr output

#

and my handler didn't work

ornate fog
#

show code

earnest sail
#

I guess... I'm gonna have to rewrite a lot of code

#
    @commands.Cog.listener()
    async def on_cog_command_error (self, ctx: discord.ApplicationContext, error: Exception):
        if type(error) is discord.errors.ApplicationCommandInvokeError:
            error: discord.errors.ApplicationCommandInvokeError
            if type(error.original) is PlayerNotPlaying:
                return await ctx.interaction.response.send_message('Nenhuma sala desse jogador foi encontrada!',
                                                                   ephemeral=True)
            if type(error.original) is ProfileNotPublic:
                return await ctx.interaction.response.send_message(
                    'Seu perfil não é público! os comandos não irão funcionar!',
                    ephemeral=True)
            if type(error.original) is NoLobbies:
                return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
ornate fog
#

remove listinre

#

the decorator

#

remove it

earnest sail
#

🤔

ornate fog
#

the also remove the on_ again

earnest sail
#

yeah

ornate fog
#

you need to override the method of the base cog

earnest sail
#

we did it

#

we fucking did it

ornate fog
#

👍

#

Well that was a long one

#

xD

earnest sail
#

thank you, i won't have to spend 5h rewritting stuff

ornate fog
#

👍

#

np

crystal verge
#

??????

frigid lark
#

install pycord with
pip install py-cord==2.0.0rc1

finite cliff
#
PS C:\Users\Fammy\Desktop\keni> & C:/Users/Fammy/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Fammy/Desktop/keni/bot.py
Traceback (most recent call last):
  File "c:\Users\Fammy\Desktop\keni\bot.py", line 1, in <module>
    import discord
  File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module>
    from .client import Client
  File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module>  
    from .webhook import Webhook
  File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module>
    from .async_ import *
  File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module>
    from ..channel import PartialMessageable
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)```
#

did i downloaded wrong pycord version?

crude rampart
#

Slash commands become invalid when the context message is deleted

bronze ferry
#

is prsaw still working for anyone

frigid lark
slender lintel
#

How?

    async def callback(self, interaction: discord.Interaction):
        if self.children[0].value == "BESTÄTIGEN":
            print("-")
        else:
            await interaction.response.send_message(f"{code_verify} \nSchreibe `Bestätigen` groß.", ephemeral=True)
            try:
                await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
            except discord.Forbidden:
                await interaction.response.send_message(f"I have not permissions.")
#
Ignoring exception in modal <extensions.Verify.cancel_modal object at 0x0000024FF340DDF0>:
Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 93, in callback
    await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\member.py", line 679, in kick
    await self.guild.kick(self, reason=reason)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\guild.py", line 2733, in kick
    await self._state.http.kick(user.id, self.id, reason=reason)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
    await value.callback(interaction)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 95, in callback
    await interaction.response.send_message(f"I have not permissions.")
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\interactions.py", line 588, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
crimson gale
slender lintel
crimson gale
#

yes, override on_error method

#

though what youre doing is also fine too so it isnt necessary

slender lintel
crimson gale
#

not like that

#

there is no such decorator

slender lintel
#

how then?

crimson gale
#

if youre subclassing the modal then by simply making a method named on_error

#

or by overriding that same attribute with the desired async function

#

this isnt hard to grasp

finite cliff
slender lintel
crimson gale
slender lintel
crimson gale
#

post the modal class

slender lintel
#
class cancel_modal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="🛑› Gebe diesen Code ein: Bestätigen (⏫ Groß)",
                                           placeholder="📛 Achtung: BESTÄTIGEN = Rauswurf",
                                           required=False, min_length=10, max_length=10))

    async def callback(self, interaction: discord.Interaction):
        if self.children[0].value == "BESTÄTIGEN":
            print("-")
        else:
            await interaction.response.send_message(f"{code_verify} \nSchreibe `Bestätigen` groß.", ephemeral=True)
            try:
                await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
            except discord.Forbidden:
                await interaction.response.send_message(f"I have not permissions.")
crimson gale
#

copy paste your callback function and rename it to on_error

slender lintel
crimson gale
#

in the class

#

its not that hard bro

slender lintel
#

In this class

class verify(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
crimson gale
#

in the modal class

crimson gale
#

yes, make a new async method in there named on_error

#

it takes an error and the interaction

crimson gale
#

why is it in the __init__ method?

#

it needs to be in the class

slender lintel
#

what?

crimson gale
#

dude, its not that hard

#

on_error is a method just like callback

slender lintel
#

So or what?

crimson gale
#

like that yes

#

now make the error handler

slender lintel
#

okay

crimson gale
#

why are you going through the trouble to make this error handler in the first place when your try-except block works just fine?

slender lintel
#

correct?

crimson gale
#

i guess but now you want to send the confirmation message only if the condition isnt true?

slender lintel
#

So when i start the bot then come a error..

Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\cog.py", line 711, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 159, in <module>
    class verify(commands.Cog):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 181, in verify
    async def cancel_modal_error(self, ctx, error):
TypeError: on_error() missing 2 required positional arguments: 'error' and 'interaction'

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

Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\main.py", line 14, in <module>
    bot.load_extension(f"extensions.{filename[:-3]}")
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\cog.py", line 783, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\cog.py", line 714, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'extensions.Verify' raised an error: TypeError: on_error() missing 2 required positional arguments: 'error' and 'interaction'
crimson gale
#

thats the leftover stuff

slender lintel
#

oh yeah

crimson gale
#

it also shows that you apparently can use it as a decorator

#

but theres no sensible point in doing it anyway when you can just make it in the class in the first place

slender lintel
#

Thank you, its working

#

But not..

Task exception was never retrieved
future: <Task finished name='Task-25' coro=<ModalStore.dispatch() done, defined at C:\Users\Amarz\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py:200> exception=InteractionResponded('This interaction has already been responded to before')>
Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
    await value.callback(interaction)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 103, in callback
    await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\member.py", line 679, in kick
    await self.guild.kick(self, reason=reason)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\guild.py", line 2733, in kick
    await self._state.http.kick(user.id, self.id, reason=reason)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py", line 220, in dispatch
    return await value.on_error(e, interaction)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 89, in on_error
    await interaction.response.send_message(f"I have not permissions")
  File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\interactions.py", line 588, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
crimson gale
#

an error is occurring and the error handler uses the response object to send a message

#

you need to add a check in there to use the response object or the followup webhook depending on if the callback has already responded

#

this is really basic stuff

slender lintel
#

!install

robust nebulaBOT
#

Install pycord:

pip uninstall discord.py
pip install py-cord

Install pycord beta:

pip uninstall discord.py
pip install py-cord==2.0.0b7

Install pycord alpha from git:

pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
slender lintel
#

would it be py-cord==2.0.0rc1

opal storm
#

Does py-cord have IPC in .ext

opal storm
#

Like, does it actually work?

crimson gale
slender lintel
#

yeah but for what?

crimson gale
#

the callback

#

if an error occurs

slender lintel
crimson gale
#

well an error cant possibly occur before the first response so that works

slender lintel
crimson gale
crimson gale
slender lintel
#

what?

slender lintel
brittle sundial
#
Traceback (most recent call last):
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/bot.py\", line 1068, in invoke
    await ctx.command.invoke(ctx)
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
Ignoring exception in command play:
Traceback (most recent call last):
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File \"/home/user_710339324889137184/main.py\", line 143, in play
    vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
  File \"/usr/local/lib/python3.10/site-packages/nextcord/abc.py\", line 1707, in connect
    raise TypeError(\"Type must meet VoiceProtocol abstract base class.\")
TypeError: Type must meet VoiceProtocol abstract base class.

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

Traceback (most recent call last):
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/bot.py\", line 1068, in invoke
    await ctx.command.invoke(ctx)
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Type must meet VoiceProtocol abstract base class.
#
@bot.slash_command(description="Play a song")
async def play(interaction: Interaction, channel: GuildChannel = SlashOption(channel_types=[ChannelType.voice], description="Voice Channel to Join"), search: str = SlashOption(description="Song Name")):
    search = await wavelink.YouTubeTrack.search(query=search, return_first=True)
    if not interaction.guild.voice_client:
        vc: wavelink.Player = await channel.connect(cls=wavelink.Player)
    elif not getattr(interaction.author.voice, "channel", None):
        return await interaction.send("You must join a voice channel first.")
    else:
        vc: wavelink.Player = interaction.guild.voice_client
    
    if vc.queue.is_empty and not vc.is_playing():
        await vc.play(search)
        await interaction.send(f'Playing `{search.title}`')          
    else:
        await vc.queue.put_wait(search)
        await interaction.send(f'Added `{search.title}` to the queue...')
    vc.interaction = interaction
    try:
        if vc.loop: return
    except Exception:
        setattr(vc, "loop", False)```
slender lintel
#
@commands.command()
  async def ping(ctx):
    await ctx.respond('Pong!')
``` Why dosent my !ping work? (I have a bunch of slash commands that work fine, kick ban ect but normal commands just wont work)
#

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582, 740616442034258002], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))

#

Its been happening for a while, Its super annoying

brittle sundial
#

You use @commands.command() when you're working on a cog.

slender lintel
brittle sundial
#

then you need to pass self, ctx

slender lintel
#

ffs how forgetful am i, I have that in every command but i forgot it

#

ty

slender lintel
brittle sundial
#

you need to format the code

#
  @commands.command()
  async def ping(ctx):    
    await ctx.send('Pong!')```
slender lintel
#

Thats litearly exactly how it is

#

(but i added self, ctx)

#

since cogs

past gate
#

could I just point something out?

brittle sundial
past gate
#

usr/local/lib/python3.10/site-packages/nextcord/abc.py

#

nextcord

brittle sundial
#

i was trying a bot made in nextcord to see how it works

slender lintel
#

why would u ask here then?

brittle sundial
slender lintel
slender lintel
#

just dosent work, ive tried so many things

brittle sundial
#

send ur code ss

#

also are other commands working?

slender lintel
brittle sundial
#

man send t h e ss

slender lintel
#
from discord.commands import slash_command
from discord.ext.commands import Cog
from discord.ext import commands
class Pingg(Cog):
  def __init__(self, bot):
    self.bot = bot

  @commands.command()
  async def ping(self,ctx):
    await ctx.send('Hey')

def setup(bot):
    bot.add_cog(Pingg(bot))```
brittle sundial
#

did you even load the cog

slender lintel
#

for filename in os.listdir('commandss'):
if filename.endswith('.py'):
bot.load_extension(F'commandss.{filename[:-3]}')

slender lintel
#

Anyone else know?

brazen siren
#

Hey guys, how can I hide my bot token for github repository?

slender lintel
brazen siren
#

Tyy

idle wagon
#

Hi, for the second day I can not solve the problem.
I use ORM sqlalchemy and postgres.

So I want to make as a photo, a mini shop using a database.
But there is a problem I can not do as in the photo, tried many ways not one of them is working properly.
I will be very grateful if someone has an example or a solution to the problem.(Oh exactly use pagination)

river mortar
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 380, in _run_event
    await coro(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/bot.py", line 1042, in on_connect
    await self.sync_commands()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/bot.py", line 631, in sync_commands
    global_commands, method=method, force=force, delete_existing=delete_existing
NameError: name 'delete_existing' is not defined
atomic thistle
slender lintel
snow citrus
#

use ctx.send(), not ctx.respond

slender lintel
#

That was what i tried to fix it

#
from discord.commands import slash_command
from discord.ext.commands import Cog
from discord.ext import commands
class Pingg(Cog):
  def __init__(self, bot):
    self.bot = bot

  @commands.command()
  async def ping(self,ctx):
    await ctx.send('Hey')

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

updated code

#

@snow citrus

snow citrus
#

do you have message intents?

slender lintel
#

yup

#

Slash commands work fine

opal storm
#

is the ipc server available in pycord

#

the pycord-ext-ipc does not work

slender lintel
snow citrus
#

can you not ping me pls

slender lintel
snow citrus
#

again...

slender lintel
#

That hasnt pi nged u right

snow citrus
#

yes

slender lintel
#

alrigh, Please try help me when u can

slender lintel
#

Slash commands work fine

crimson coral
slender lintel
#

oops

#

one sec

#
import os
from dotenv import load_dotenv
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582, 740616442034258002], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
load_dotenv()
for filename in os.listdir('commandss'):
     if filename.endswith('.py'):
         bot.load_extension(F'commandss.{filename[:-3]}')
@bot.event
async def on_ready():
    print('Connected to bot: {}'.format(bot.user.name))

@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.respond(error)
    else:
        raise error
@bot.event
async def on_message(message):
    if f"<@{bot.user.id}>" == message.content:
        Welcome=discord.Embed(title="Felbot",url="https://github.com/VividBlue1/Felbcord-Py/tree/discord",description="Hello! I am a personal slave bot who helps around moderating and providing fun into the felbcord! \n If you have any questions about me feel free to ask @ignfoolish#0396 - my creator \n Join Felbcord here! \n 
",color=discord.Color.blue())
        Welcome.set_author(name="FelBot", url="https://github.com/VividBlue1/Felbcord-Py/tree/discord", icon_url="https://i.ibb.co/tz7VQJw/felb.jpg")
        await message.channel.send(embed=Welcome)


bot.run(os.getenv("TOKEN"))```
crimson coral
#

you overwrote on_message

#

which is where commands are handled

#

you should add await bot.process_commands(message) to the end of that event

languid hollow
#

Does paginator have around the same length as a normal embed message or webhook?

#

in width size

crimson coral
#

uhhh the embed width is usually dependent on the embed itself

#

there isn't really an official method that normalizes it

slender lintel
# crimson coral you overwrote on_message
async def on_message(message):
    if f"<@{bot.user.id}>" == message.content:
        Welcome=discord.Embed(title="Felbot",url="https://github.com/VividBlue1/Felbcord-Py/tree/discord",description="Hello! I am a personal slave bot who helps around moderating and providing fun into the felbcord! \n If you have any questions about me feel free to ask @ignfoolish#0396 - my creator \n Join Felbcord here! \n ",color=discord.Color.blue())
        Welcome.set_author(name="FelBot", url="https://github.com/VividBlue1/Felbcord-Py/tree/discord", icon_url="https://i.ibb.co/tz7VQJw/felb.jpg")
        await message.channel.send(embed=Welcome)
        await bot.process_commands(message)```
languid hollow
#

I see, I'll experiment if stuff and see the max characters each can take

slender lintel
#

is that right

crimson coral
#

outside the if

slender lintel
crimson coral
#

... that's outside the entire function now

#

"outside the if" means the indentation should be inline with if

slender lintel
#

oh my bad

slender lintel
crimson coral
#

probably

slender lintel
#

ill try it

slender lintel
crimson coral
#

allgood

half marsh
#

Is there a way to add all possible exception to a tasks so that my task loop doesnt stop thonk

#

I mean handle the exception inside a loop

crimson coral
#

well you could just try-except, or you can set a .error function with the decorator

half marsh
#

Thanks

crimson coral
#

allgood

#

note that this will override the default error print like the regular global error handlers, so i'd recommend having an else print at the end incase you get an error you haven't accounted for

half marsh
teal shadow
#

Hi help me I need that when embed reaches the field limit it will make a new embed.


@market.command(name='products', description='View the list of products')
    @cooldown(1, 15, BucketType.user)
    async def products(self, ctx: discord.ApplicationContext): 
      embeds = []
      for x in items:
        
      paginator = pages.Paginator(pages=embeds, show_disabled=False, timeout=120)
      await paginator.respond(ctx.interaction, ephemeral=False)
crimson coral
#

isee

slender lintel
crimson coral
#

field limit is 25

slender lintel
#

whys that?

crimson coral
#

uhhh

#

can you show the final code you have for it

graceful robin
#

I have a file that is over 1000 lines long, any tips to organize it?

slender lintel
#
import os
from dotenv import load_dotenv
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582, 740616442034258002], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
load_dotenv()
for filename in os.listdir('commandss'):
     if filename.endswith('.py'):
         bot.load_extension(F'commandss.{filename[:-3]}')
@bot.event
async def on_ready():
    print('Connected to bot: {}'.format(bot.user.name))

@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.respond(error)
    else:
        raise error
@bot.event
async def on_message(message):
    if f"<@{bot.user.id}>" == message.content:
        Welcome=discord.Embed(title="Felbot",url="https://github.com/VividBlue1/Felbcord-Py/tree/discord",description="Hello! I am a personal slave bot who helps around moderating and providing fun into the felbcord! \n If you have any questions about me feel free to ask @ignfoolish#0396 - my creator \n Join Felbcord here! \n ",color=discord.Color.blue())
        Welcome.set_author(name="FelBot", url="https://github.com/VividBlue1/Felbcord-Py/tree/discord", icon_url="https://i.ibb.co/tz7VQJw/felb.jpg")
        await message.channel.send(embed=Welcome)
    await bot.process_commands(message)


bot.run(os.getenv("TOKEN"))```
slender lintel
slender lintel
crimson coral
#

wait so what's the issue

slender lintel
#

For example before it would work like this
@felbot Hi
@felbot
both would send the message now only the second one works

crimson coral
#

uhhhh

#

the first one would have never worked?

slender lintel
#

Yeah

crimson coral
#

you're checking if f"<@{bot.user.id}>" == message.content

#

which means it will work if the message ONLY contains the bot mention and nothing else

slender lintel
#

How would i allow it to have message content too?

crimson coral
#

you could do message.content.startswith(...) or ... in message.content

#

but if you do either of those, you should check if message.content exists at all

half marsh
#

Hmm i guess we can do if bot.user in message.mention

slender lintel
#

Would
if in message.content = <@{bot.user.id}> work

crimson coral
#

other way round, the other solution dot proposed could be more appropriate

#

but both of these will trigger if the bot is mentioned anywhere in the message (not just the start) or even when someone replies to the bot

slender lintel
#

Thats fine for now, If i have issues i can change it

slender lintel
crimson coral
#

message.mentions

slender lintel
#

ty

#

Thanks! Both works now

crimson coral
#

allgood

slender lintel
crimson coral
#

user.mutual_guilds

slender lintel
crimson coral
#

oh no, mutual_guilds compares the user and the bot

slender lintel
crimson coral
#

probably yeah

slender lintel
#

So
I have a ratter server and a server i want to ban all the ratters from (for obvious reasons) So i want to find all the people who are in that server and get their names/ids so i can ban them, The best way we are using is to get mutual servers but i want to see if i can automate this

crimson coral
#

well

#

is the bot in both servers?

slender lintel
#

It isnt, Its only in the server i want to ban them from.. but since that wouldnt work is it possible to see the mutuals from my alt account

crimson coral
#

nope

slender lintel
#

(Btw obviously ima leave the server before its terminated)

slender lintel
#

Would have been really helpful

crimson coral
#

the bot would have to be in the other server if you wanted to loop over the members or something

#

the best you can do is get a list of user IDs to have banned

#

(manually)

slender lintel
#

alright, Our main aim is just to find out whos in both servers

#

yeah

sullen marten
#

hey, i have a very strange problem
i define bot like this:

import discord
from discord.ext import commands

def get_prefix(bot, message):
    return commands.when_mentioned_or("-")(bot, message)

bot = commands.Bot(
    command_prefix = get_prefix,
    strip_after_prefix = True
)

but it responds only when i type "<bot_ping> help" and completely ignores "-help", there are even nothing in the terminal

by the way, bot doesn't ignore a message - get_prefix invokes
something really strange...

(using py-cord 2.0.0rc1)

slender lintel
frigid lark
sullen marten
frigid lark
#

try it with

def get_prefix(client, message):
        with open("File.json", "r") as f:
            prefix = json.load(f)

        return prefix[str(message.guild.id)]
sullen marten
past gate
#

or just like prefix.get(str(messae.guild.id), '!')

#

so you can fall back on a default prefix

sullen marten
frigid lark
#

do you have Intents?

sullen marten
#

"message content intent" turned on

frigid lark
#

what is wrong with it?

inner iris
sullen marten
slender lintel
#

Is it possible to make a command that can ban up to 500 user ids at once? (without crashing the bot xD)

slender lintel
ornate fog
inner iris
frigid lark
slender lintel
#

they do discord tokens too ect

inner iris
#

Try it. Only way is using await and ban_member or so. But I don't know if there's an api limit for that

slender lintel
#

alr

#

But how would i have it so it can ban multiple ids

inner iris
#

use a for loop...

slender lintel
#

    @slash_command(name="ban", description="Bans a member")
    async def ban(self, ctx, member: discord.Member,*,reason):
      if ctx.author.guild_permissions.moderate_members:
       await member.ban()
       await member.send(reason)
       await ctx.respond(f'{member} has been banned from felbcord', ephemeral=True)
      else:
       await ctx.respond('You do not have the correct permissions for this',ephemeral=True)``` what do i add to this
inner iris
#

You would need to be able to specify multiple users in the command but I actually don't know how you would do that. But say you got multiple members as a list you could do:

for member in member_list:
    await member.ban()
    await member.send(reason)
    ...
slender lintel
#

alr

frigid lark
slender lintel
#

(ofc in an actual bot yes but for this, why?)

frigid lark
#

I mean for a actual bot

slender lintel
#

yeah

#

@crimson coral Hey sorry for ping, I am confused how would i make a ban command to ban multiple ids at once?

#

Like 100?

#

573*

slender lintel
slender lintel
#

?

#

I need to edit my ban command to ban multiple user ids at one time

#

instead of one member at once

#
@slash_command(name="ban", description="Bans a member")
    async def ban(self, ctx, member: discord.Member,*,reason):
      if ctx.author.guild_permissions.moderate_members:
       await member.ban()
       await member.send(reason)
       await ctx.respond(f'{member} has been banned from felbcord', ephemeral=True)
      else:
       await ctx.respond('You do not have the correct permissions for this',ephemeral=True)```
#

or ban all ids in a text document

#

one or the other

past gate
#

literally spoon fed

#

lol

inner iris
#

?

#

spoon fed?

#

ah

slender lintel
past gate
#

which part? the looping over a list?

inner iris
#

Do you know what a for-loop is used for?

slender lintel
inner iris
#

I think the main problem for you is how you can get the ids of only the 573 users you want to ban...

slender lintel
inner iris
#

well then ask him and convert it to python...

slender lintel
#

he dosent know python

inner iris
#

but you do.

past gate
slender lintel
crimson gale
#

you should be able to deduce the loop structure from c# into python

inner iris
#

yes.
Most programming languages share a kind of similar syntax. You can find everywhere basics like for/foreach, if, while and so on. So it shouldn't be that difficult to try understand what he did in c# and deduce it to python. Provided that you know the python basics ofc...

paper schooner
#

how can I make "wait_for" for both message or button at the same time?

crimson coral
#

ehhh

#

you can't?

#

wait_for is only really designed for a single event

paper schooner
#

hmm okay, I'll search for another way

crimson coral
#

what exactly are you trying to do?

paper schooner
#

check whether user clicks button or sends a message

#

but wait I had the solution somewhere in my previous bot

#

oh yea, here it is

done, pending = await asyncio.wait([
                client.wait_for('message', timeout=1200, check=check_input),
                client.wait_for('reaction_add', timeout=1200, check=choose_setting)
            ], return_when=asyncio.FIRST_COMPLETED)
            try:
              stuff = done.pop().result()```just need to change reaction into button
crimson coral
#

fair enough

languid hollow
#

When adding drop down menus in the modal, would you class the drop down menus itself and then add it via the Modal Class

#

or add the drop down menu in the modal class

crimson coral
#

...drop downs in modals?

#

that's not supported

slender lintel
#

Does pycord support pop ups

frigid lark
#

what?

slender lintel
#

Only example I could find

frigid lark
slender lintel
#

Is there a doc on it

frigid lark
slender lintel
#

Ty

languid hollow
crimson coral
#

yeah....

frigid lark
crimson coral
#

modals only support text right now

languid hollow
#

So I have been fixing something that's not even implemented well that's great

crimson coral
#

discord hasn't really done anything else with them yet

languid hollow
#

idk if I saw a different language implementing them but they've implemented the drop downs in modals

frigid lark
#

^

crimson coral
#

huh

#

is there any screenshots of this? can't find anything on it

#

though i haven't been active recently so maybe i completely missed it

languid hollow
#

I'll try to find it, though chances are very low since I didn't click on the video just the the thumbnail and a bit of the title saying menus in modals

#

unless the video was clickbait well damn then

crimson coral
#

hmmm so it does

upbeat hill
#

how do you edit a ephemeral message from interaction?

upbeat hill
#

is there a way you get around the text limit in embeds

slow dome
upbeat hill
slow dome
#

Not if you already reached your limit

crimson coral
supple ravineBOT
crimson coral
#

(he says as one of the tests fails, nice)

#

...forgot to import union

#

end me, should work now

slender lintel
#

Hello, how can you make it send a message as soon as you reply to the bot?

slender lintel
slender lintel
slender lintel
#

im not exactly sure how message.reference actually works

#

but here is the docs fo rit

#

Thanks

analog elk
#

Can two buttons have the same custom ID?

slow dome
analog elk
#

scheisse

slow dome
#

?

analog elk
#

I have a command that a user can call that i want to create a custom view

#

however that means i need a custom id for each button on each message called by the command

analog elk
#

because buttons need custom ids to make a persistent view

#

the view is created after a modal is submitted

#

and my approach is to add the view to the bot at that point with the message id

#

Tbh i could make the button ID a random 100 digit integer

#

which means the chance of two buttons conflicting is 1/10,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000,​000

#

or something

slow dome
#

I don’t think integers can be tha big in Python

#

make it a string

analog elk
#

however, you can make a 100 character long string\

#

exactly

#

custom ids have to be strings anyways

slow dome
#

yes, but there is probably a char limit

analog elk
#

or even better

#

i could just make a random 100 character long string for every message

slow dome
analog elk
#

however

#

you can't pass self into a decorator

#

so i dont think i can do it without using a global

past gate
#
        if custom_id is not None and len(str(custom_id)) > 100:
            raise ValueError("custom_id must be 100 characters or fewer")```
#

indeed it is 100

slow dome
analog elk
#
 async def callback(self, interaction: discord.Interaction): # TODO: Add ability to edit claims
        # name = self.children[0]
        # lore = self.children[1]

        ## for countries:
        # head of state = self.children[2]
        # flag = self.children[3]
        # claim = self.children[4]

        ## for organizations:
        # leader = self.children[2]
        # motivation = self.children[3]
        # emblem/flag = self.children[4]

        ## for others:
        # entity = self.children[2]
        # other info = self.children[3]
        # image = self.children[4]

        embed = children_to_embed(self.children, self.entity, interaction.user)
        approval_channel_id = io.load_approve_channel(interaction.guild_id)
        approval_channel = await interaction.guild.fetch_channel(approval_channel_id)    
        claim_msg = await approval_channel.send(embed=embed)

        approval_view = views.CountryApprovalView(interaction.user, self, embed, claim_msg)

        bot.add_view(views.CountryApprovalView(), approval_view.claim_msg.id)

        await interaction.response.send_message(f"Claim successfully added! An admin will approve you in <#{approval_channel_id}>.", ephemeral=True)
        approval_view.orig_msg = await interaction.original_message()

        await approval_view.wait()
#

this is the callback of the modal that creates the view that i want to be persistent

#
class CountryApprovalView(discord.ui.View):
    """A view attached to country approval messages which adds an approve and deny button to the message."""
    def __init__(self, user: discord.User, claimmodal, embed, claim_msg):
        super().__init__(timeout=None)
        self._claimant = user
        self._claimmodal = claimmodal
        self._embed = embed
        self._claim_msg = claim_msg
        self.orig_msg = None # the original /claim message 

    @discord.ui.button(label="Approve", style=discord.ButtonStyle.green, custom_id=f"Custom ID")
    async def approve_button_callback(self, button: discord.Button, interaction: discord.Interaction):
        if interaction.user.guild_permissions.administrator:
            await interaction.response.send_message("Successfully approved claim!", ephemeral=True)

            button.label = "Approved"
            button.disabled = True
            self.children = [button]

            self._embed.color=discord.Color.green()
            await self._claim_msg.edit(f"<@{interaction.user.id}> has approved this claim!", view=self, embed=self._embed)
            await self.orig_msg.channel.send(f"<@{self._claimant.id}>, your claim \"{self._embed.title}\" has been approved by {interaction.user.name}!")
            self.stop()

            io.register_country()

        else:
            await interaction.response.send_message(f"You do not have permission to approve claims!", ephemeral=True)
  
  ... more buttons ...
#

this is the view itself

#

i am importing bot from main in modals.py (the file containing the modals) and calling bot.add_view() in the modal callback

#

and i dont know if that would work

half marsh
analog elk
#
import os, discord, config
import countrybot.io as io
from countrybot.views import CountryApprovalView
from dotenv import load_dotenv

initial_extensions = ['countrybot.cogs.date', 'countrybot.cogs.errorhandler', 'countrybot.cogs.country']
intents = discord.Intents.default()
intents.message_content = True

load_dotenv()
bot = discord.Bot()
.
.
.
#

i dont really know if it would work though

#

but i also dont know if putting self.add_view() in on_ready would work if the message with the view is created after the view is added as persistent

#

if i make a random 100 character long string of any printable ascii character, the chance of two strings colliding is (1/95)^100

#

so i think that a collision is unlikely between button ids lmao

past gate
#

ok

half marsh
#

ye with timestamp you can never get the same int

analog elk
#

well

#

relatively the same time

half marsh
analog elk
analog elk
#

when doing bot.add_view(persistentview()) are you adding the specific view that is initialized by that call to persistentview() as a persistent view? Or are you adding any view of type persistentview as a persistent view?

analog elk
#

HOWEVER

#

i have no way of saving the view

#

if i could pickle it that would be awesome but:

#

a) i dont think views are pickleable

#

b) even if they were, i cant save the view because it contains user inputted data, and unserializing user inputted data is a security risk

half marsh
analog elk
#

ignore that

#

ok nevermind

#

persistentview() creates a specific instance of a view

#

and every time a view is added to a message, it's a different instance of that view

#

so when you do bot.add_view(persistentview()), i think what it does is it adds that specific instance of the view to every message that needs to have that view

#

i think

#

and the issue is that i can't have one instance of the view attached to every message with the view

#

each message needs a different view instance

#

so they all have to be added as separate views

#

I THINK

#

i am not sure though

#

this is what i have gathered from the info i have seen

#

but my understanding could be entirely wrong

#

my idea is that maybe i can save the view instance as a json file and store that in the database my bot is using

#

however if the bot goes offline and online again, and that view instance is added to the bot from the json file, i don't know if the view will still work

half marsh
half marsh
analog elk
#

I dont know if it will work though

half marsh
#

I havent tried aswell, why no tias

analog elk
#

why no tias?

half marsh
#

Try it and see

analog elk
#

ahh

#

i am going to

#

TypeError: Object of type CountryApprovalView is not JSON serializable

#

Thought so

#

sadge

#

it straight up might not be possible to make this view persistent

half marsh
#

You dont pass the view instance

#

But any data inside that view

#

Like button id etc.

#

Then on on_ready event, you iterate the saved json, recreate the class then pass the data where it belongs

analog elk
#

But that view is being view.wait()ed by the modal callback

#

i dont know if the class can be destroyed and recreated

analog elk
#

the code here is kinda complex
-original slash command sends message with dropdown view
-each option in the dropdown view sends a modal specific to that option
-submitting the modal sends a message to another channel with the approval view
-one button edits the embed that the view is attached to, another deletes the message, another sends a modal to the user, and each button edits the approval view itself
-when the approve or deny buttons are pressed, a message is sent to the user in the channel that the original slash command was used in

#

After much pain and hours of coding everything works but the view is not persistent

#

so if that message with the view awaiting a button press is sent and the bot goes offline then online again the buttons stop working

#

so it's not essential

#

especially considering that the messages, in theory, shouldn't wait too long to be approved or denied

#

but it's a quality of life thing

#

and honestly i dont know if a persistent view can be added heer

#

here*

#

or rather

#

i don't think i am skilled enough to implement it

slender lintel
#

how can i set the default target user of an option to the author itself

desert dagger
#

b!rtfm option

open bearBOT
# desert dagger b!rtfm option

I couldn't find a documentation with the name option! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

desert dagger
#

b!rtfm pyc option

finite cliff
#
PS C:\Users\Fammy\Desktop\keni> & C:/Users/Fammy/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Fammy/Desktop/keni/bot.py
Traceback (most recent call last):
  File "c:\Users\Fammy\Desktop\keni\bot.py", line 13, in <module>
    bot = commands.Bot(command_prefix='.' , case_insensitive=True ,intents=discord.Intents.all())
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
PS C:\Users\Fammy\Desktop\keni> ```
slender lintel
#

didnt tell me anything

desert dagger
#

b!rtfm pyc choice

desert dagger
#

b!rtfm pyc option

desert dagger
#

you could code it to target user if they dont select a value and it usually shows the by default on list

finite cliff
#
Traceback (most recent call last):
  File "c:\Users\Fammy\Desktop\keni\bot.py", line 13, in <module>
    bot = commands.Bot(command_prefix='.' , case_insensitive=True ,intents=discord.Intents.all())
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
PS C:\Users\Fammy\Desktop\keni> 

Anyone help i reset my pc few days ago and now its not working

#

My code is not importing pycord

slender lintel
desert dagger
#

sure?

finite cliff
#

1 min

desert dagger
#

also do
1 -> pip uninstall py-cord
2 -> pip install py-cord==2.0.0rc1
3 - > try code again
4 - > if it fails then change "commands.Bot" to discord.Bot or discord.ext.commands.Bot()

finite cliff
desert dagger
#

seems like pycord is fine

#

just use discord.Bot() and see if that works

finite cliff
#

in vc code its white insteal of green

#

other modules are in green but discord one is in white

desert dagger
#

mhm try to reinstall ig

finite cliff
#

omki

#

also pip is not working i have to do py -m pip

C:\Users\Fammy>pip list
'pip' is not recognized as an internal or external command,
operable program or batch file.```
desert dagger
#

its normal to need to use py -m pip

#

sometimes u can and cant use pip directly

finite cliff
#

😮

#

reinstalling pycord worked

#

thanks for your help

slow dome
analog elk
crude rampart
#

is there a method to get webhook object by its ID?

languid hollow
desert dagger
#

Is it possible to create a paginator during an on_message event?

slender lintel
#

Can I use tasks to auto start my bot if it dcs

desert dagger
#

sures?

slender lintel
#

Is that what their meant for or what's it most commonly used for

desert dagger
#

With the tasks extension, you can make background tasks without worrying about the asyncio hell and mind bogglers like "what if my internet dies" and "how do I handle reconnecting" with the added benefit of a lot of useful additions that are one line of code away!

slender lintel
#

The

desert dagger
#

i havent experimented with tasks really

slender lintel
#

Alr

lusty dragon
#

does anyone know how to make buttons from a view work even if i restart the bot?

slender lintel
#

Can a button be created without a class

#

like the view class

wide sonnet
slender lintel
#

ah k

#

also

#

how do i grey out a button after one press?

wide sonnet
#

a bit complicated, but I can try to explain

#

do you have subclassed view or automatically created?

languid hollow
supple ravineBOT
slender lintel
#

How can i pass field im embed? i mean, like make space in name

hollow moth
upbeat hill
#

can you field in a embed with nothing in it

slender lintel
worthy basin
#

You need to set the name to a zero width space iirc

#

You will need to look up the unicode for it

upbeat hill
#

thanks

crude rampart
#

How to get the message ID of the message the bot sent through a webhook?

crimson coral
opal storm
#

does pycord still get .news in a channel because while looping through guild.channels it says Error: 'TextChannel' object has no attribute 'news' so I'm thinking they haven't changed that to is_news()?

crimson coral
opal storm
crimson coral
#

huh

opal storm
crimson coral
#

oh wait im wrong

upbeat hill
#

not sure how to fix this

opal storm
#

is it fixed in alpha?

crimson coral
#

not rc1, i made a pull for it but it'll be next version ##1370

supple ravineBOT
crimson coral
#

yeah

opal storm
#

sad sad dude

#

I'm making a dashboard

#

and I'm doing welcoming for it sooo yeah

#

idk how to do it efficiently so im gonna just do it the bad way

#

(cuz i am bad)

crimson coral
#

if you don't want to install the entire alpha branch, you can just go through the code changes and apply that

#

it's like 3 lines

opal storm
#

just add this right? py @property def news(self) -> bool: return self.is_news()

crimson coral
#

yeah

opal storm
#

in the textchannel class alr

crimson coral
#

i.e. def callback(self, select, interaction...)

opal storm
#

idk where that file is located though, I don't remember I knew before though

#

I have it python from windows store btw

#

oh wait dw

#

i got it

crimson coral
#

oh christ the windows store

#

well as long as you can get to it

opal storm
#

yeah got it

#

vsc on top lmao, I just ctrl clicked on the discord.channel import ez

crimson coral
#

if you're using an ide like vscode or pycharm you can control+click the module

#

yeah

opal storm
#

IPC route returned values which are not able to be sent over sockets. If you are trying to send a object, please only send the data you need. whoops, how do I send the id and the name and then use it in html?

#

I tried using dicts, though that just messed everything up.

slender lintel
#

Hey, how can my bot find suspicious users?

past gate
#

depends on your criteria

terse plinth
#
class Setup(commands.Cog):

    def __init__(self, client:commands.Bot):
        self.client = client
        self.all_user_ids = [user.id for user in client.users]
        self.ping()
    
    def ping(self):
        for guild in self.client.guilds:
            for member in guild.members:
                print(member.id)

Console Output -

$ C:/Python/python.exe "e:/Python/Evelynn Workspace/Evelynn6/main.py"
Logged in as Reii#2207

Why do i not get any output? I have all intents enabled. when i print self.all_user_ids i get []

opaque marsh
#

Does anyone know how to track the inviter if someone joins the server?

#

Using the on_member_join event?

crimson coral
opaque marsh
#

How does invite tracker bot manage it think

terse plinth
#

magic

crimson coral
terse plinth
#

i see, i am running it before on_ready. its in a cog

#

so ig i should use a cog listener

crimson coral
#

yeah just do it in a cog on_ready listener

terse plinth
#

works now. Thanks!

crimson coral
#

allgood

terse plinth
#

check these two

crimson coral
#

pretty much

opaque marsh
#

Guys you have any idea on how to create application bot?

#

Like

#

Should I play around with for loops?

#

What's yoru idea

#

*your

crimson coral
#

maybe you want modals?

opaque marsh
#

Ye

#

But

#

How do I ez ly store the data

#

Json?

crimson coral
#

json is fine on a small scale, but ideally you'd use a database

opaque marsh
#

Like MongoDB?

crimson coral
#

yeah

opaque marsh
#

I like using json it's nais

crimson coral
#

fair enough

opaque marsh
#

I have never tried db's

#

Gotta search sum tutorials

terse plinth
#

mongo is best imo

#

easy to use

#

easily scalable

#

the pymongo library is well written

crimson gale
#

works as a simple database but when you need relational models then you need to ditch mongodb for something that uses sql

terse plinth
#

ye

#

in my experience i havent needed sql so far

#

hopefully it stays that way

#

cause i hate sql

crimson gale
#

for one of my projects im just using sqlite since its the most convenient

#

sql isnt that intidimating when you learn the basic syntax

terse plinth
#

sqlite3 is just not for me since i cant open the .db file and read it like i would with a .json

#

lmao

#

ik the syntaxes quite well, had them for my recent comp sci test

crimson gale
#

do be weary when youre using json files as databases

#

theyre not designed to be such

terse plinth
#

i use mongoDB lol

slender lintel
#

How can i have seperate settings for a feature per guild? (For example i have a prefix command, how would i have that per guild)

#

and have per guild permissions ect

idle wagon
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'Embed' object is not iterable
Not sure how to solve the problem?

terse plinth
#

that stores all these settings

#

for example a json file (not recommended, user MongoDB instead)

slender lintel
#

So the database can store per server data?

terse plinth
#

yea

#

i have this exact feature on my bot

slender lintel
#

So, MongoDB works with pycord right?

idle wagon
# sudden path Full traceback?
Traceback (most recent call last):
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 122, in wrapped
    ret = await coro(arg)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 825, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\modules\pages.py", line 57, in pagetest_new
    await paginator.respond(ctx.interaction, ephemeral=False)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\ext\pages\pagination.py", line 909, in respond
    msg = await interaction.response.send_message(
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\interactions.py", line 603, in send_message
    payload["embeds"] = [e.to_dict() for e in embeds]
TypeError: 'Embed' object is not iterable

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

Traceback (most recent call last):
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 331, in invoke
    await injected(ctx)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 122, in wrapped
    ret = await coro(arg)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 1091, in _invoke
    await command.invoke(ctx)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 331, in invoke
    await injected(ctx)
  File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 128, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'Embed' object is not iterable
terse plinth
#

line 37 embeds = [add_embed]

#

parentheses required []

slender lintel
terse plinth
terse plinth
#

yt it, theres some nice tutorials

terse plinth
#

it takes a little getting used to

slender lintel
terse plinth
crimson coral
vagrant mortar
#

if only that worked.

crimson coral
#

what does it do instead?

vagrant mortar
#

gives me nothing

crimson coral
#

hmmm hold on

idle wagon
#

Why embed is not sent with embed.field?

vagrant mortar
crimson coral
#

...you're doing embed.clear_fields()

vagrant mortar
#

or... that wokeJoy

#

Yeah... that will do it too 😛

idle wagon
vagrant mortar
#

remove that line.

crimson coral
#

well

#

yeah

sleek grove
#

how can a make a per guild prefix?

vagrant mortar
#

or move it above the for i in pages_list