#Basic Pycord Help (Quick Questions Only)

1 messages · Page 4 of 1

silver moat
#

so any errors?

lofty falcon
#

no errors

silver moat
#

so what's the output?

lofty falcon
#

from ?

#

I solved someones question

#

this

#

with this

silver moat
#

for this

lofty falcon
#

I ran it no errors

#

testing code from:
#1002289194544136323

#

124 so if someone knows how I can get await custom_id and the user id in the "main loop". I would be thankful

#

the callback into another function is not a solution 4 me

silver moat
#

ok, but you really need to name your variables/parameters better

full basin
#

I recommend you subclassing view and adding the buttons with the corresponding callbacks

lofty falcon
#

I tried that

#

doesn't do what I need

full basin
#

Why not?

lofty falcon
#

because I automatically generate everything based from lists afterwards to corresponding buttons also in a list with NPC data -> there is a minimum chain of 100 possibilities

#

it will get very messy

#

if its not in the main loop

#

I really need to await it in the main loop

pallid trench
#

you could use partials to generate button objects each with different values in the callback

lofty falcon
#
@bot.command()
async def button(ctx):
    await ctx.send(
        "Hello, World!",
        components = [
            Button(label = "WOW button!", custom_id = "button1")
        ]
    )

    interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
    await interaction.send(content = "Button clicked!")
#

discord_components

#

had something like this

#

but it doesn't work anymore

#

that's what I need, but it doesn't work for me anymore

#

I spent 3 days of losing hair

pallid trench
#

those buttons need to be wrapped in a View object and that sent with the message using view kwarg

#

you can simply provide a list of components as args when initializing a View object and theyll automatically be added to the view with no further action

lofty falcon
#

the buttons work, the response doesn't

#
interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
    await interaction.send(content = "Button clicked!")
#

this doesnt work anymore

pallid trench
#

those should be set as the button's callback attribute

#

that also eliminates the need for a custom id for each button

lofty falcon
#

is there somewhere a code example?

pallid trench
#

simply define an async function that takes one argument interaction and set that as the callback attribute for the given component

lofty falcon
#
async def create_message_with_button(msg, embed):
    view=View()
    thisbutton = Button(label="button", style=discord.ButtonStyle.secondary, custom_id='mybutton1')
    thisbutton.callback=on_interaction
async def on_interaction(interaction: discord.Interaction):
    await interaction.response.send_message(f"Button: {interaction.data['custom_id']}\npressed by: {interaction.user}")
@bot.command()
async def hello(msg):
    embed=discord.Embed(title="**Welcome!**", description="**Press this button to recieve a DM**?", color=0xfbe8d2)
    await create_message_with_button(msg, embed)
pallid trench
#

yep

lofty falcon
#

...

#

that doesn't solve my problem

#

and I had that from the start

#

I give up

pallid trench
#

are you using a third party package to pycord?

lofty falcon
#

pycord

#

I tried discord_components

#

doesn't work

pallid trench
#

because its incompatible

lofty falcon
#

I uninstalled everything for discord_components

#

else it would error out

pallid trench
#

hold up

#

did you install pycord while having discord.py still installed?

lofty falcon
#

bo

#

no, first pycord

#

then discord py 2.0

#

no errors

pallid trench
#

pycord and discord.py are not compatible with each other

#

its one or the other

lofty falcon
#

there are no errors, the code works

#

as I said, the problem is, I need to await the button click in the main loop

#

or get the custom_id and user id as a return value from a function directly to the main loop

pallid trench
#

yeah no i cant help you with that

#

i was under the impression that the issue was something else

lofty falcon
#

I tried creating custom views, subclassing, everything

#

I spent 3 days, trust me

cyan quail
#

if you installed dpy after installing pycord then you're running dpy

#

since it'll just overwrite the files

lofty falcon
#

I uninstalled discord, and blaseted pycord over it, didn't change anything

proud pagoda
#

Are you using slash commands?

rare ice
#

@lofty falcon Maybe instead of using 3 libraries you could just use Pycord and then we can help you better, since we’re not going to help you the best when you’re not using our library components.

lofty falcon
# proud pagoda wdym the main loop
async def hello(msg):
    embed=discord.Embed(title="**Welcome!**", description="**Press this button to recieve a DM**?", color=0xfbe8d2)
    await create_message_with_button(msg, embed)
    #await For button click here, or await the return value from a function with custom_id from the button and user id
cyan quail
lofty falcon
rare ice
#

K

proud pagoda
cyan quail
#

yeah... idk why you're so reluctant to just use the callback

#

that's the best way to handle it

lofty falcon
#

Ok, so when I have a list, of 100 follow ups

#

custom buttons for each

proud pagoda
#

Just use the same callback for all the buttons

cyan quail
#

^ and decide the outcome based on custom_id

#

if you really want you could use wait_for("interaction") but it isn't the best practice

lofty falcon
#

that would be pure gore

#

I am sorry, but I rather leave it at emoji reactions, which is way slower

pallid trench
#

just use guard clausing if you dont want the mess of alot of indents?

lofty falcon
#

I will do it the ugly and hard way.
Json database for every user...

#

with counters

#

yuk

pallid trench
#

i would suggest against that

#

and instead learning a sql or nosql database solution

#

if you mean using .json files that is

proud pagoda
cyan quail
#

again if you want to emulate reaction_add then you can use interaction, but im struggling to understand what you're trying to do that would make using callbacks impossible/harder than coding it all inside the command

lofty falcon
#

because I want to migrate my code

pallid trench
#

then migrate it and optimize later

lofty falcon
#

not have to code 150000 lines just to emulate the same functionality in a callback ...

cyan quail
#

im sorry but it's hard to help you if we don't actually know your end goal, outside of generic advice like using wait_for

full basin
#

Man wants to migrate but doesn't want to write new code. He just wants the old code work his way with pycord views

#

Which is literally impossible

lofty falcon
#

exactly, I wrote code that codes itself, 60 lines, but if I have to use the callbacks, it ends up in tons of code lines and pure code gore

pallid trench
#

you dont have to use it

#

you were offered a solution that doesnt involve callbacks

lofty falcon
#

which solution didn't offer callbacks ?

pallid trench
#

wait_for but you listen for interaction instead

proud pagoda
cyan quail
#

again button_click isn't a real event, which is why im suggesting interaction

#

maybe it's a dpy thing? idk but it ain't here

lofty falcon
#

hmm

proud pagoda
#

By the way, do SlashCommandGroups with guild_ids set refresh every time the bot is run?

cyan quail
#

doesn't everything refresh on run by default

proud pagoda
#

Yeah well it just stopped doing that for some reason

#

Alright finally it refreshed the commands

#

By the way are guilds fully loaded in from self.bot.guilds?

cyan quail
#

they should be yes

proud pagoda
#

So does it have the same data as if I had fetched it using fetch_guild, except maybe a bit outdated depending on when the bot was started?

cyan quail
#

fetch_guild returns way less data

proud pagoda
#

Really?

#

Huh

#

Then whats the point of fetch_guild?

cyan quail
#

you do get an approximate member count but nothing specific

proud pagoda
#

So self.bot.guilds is refreshed every time a new guild is joined or removed as well, right?

cyan quail
#

yes, the cache is always updated

proud pagoda
#

Ok thanks

cyan quail
#

allgood

lofty falcon
#

this looks.... doable

#

I will just make for each user a session with their user id, return the btn_id and listen for the interaction

cyan quail
#

well yeah that's what we've been telling you the whole time

lofty falcon
#

I read 95% callbacks

cyan quail
#

and then we told you wait_for("interaction")... this is exactly what you found

lofty falcon
#

wait_for(interaction), doesnt exist

#

I was looking for that

cyan quail
#

it does?

#

wait_for works for any "on" event

#

on_message, on_reaction_add, and so on

lofty falcon
#

wait_for(on_interaction)

cyan quail
#

no, wait_for("interaction")

#

like wait_for("message") or wait_for("reaction_add")

grizzled sentinel
#

leave out the on_
interaction is the event name
on_x means that that function is called when (or on) the event is triggered

proud pagoda
#

By the way, is guild.owner not stored by self.bot.guilds?

pallid trench
#

i believe that is something you need the members intent for

proud pagoda
#

Yeah I have it

lofty falcon
cyan quail
#

it should be, but if not you should at least have guild.owner_id?

cyan quail
proud pagoda
#

the test bots only in 3 guilds and I'm the owner of all of them

cyan quail
#

oh it won't if you fetch it

proud pagoda
#

Even when I don't, it doesn't work

cyan quail
#

that's pretty odd, it should be fine on that scale

proud pagoda
#

huh it worked this time

#

When I put a print statement for the guild.owner right before accessing the name attr

cyan quail
#

wait no, fetching should give you owner_id but not owner

#

because guild.owner just checks guild.members for owner_id but it doesn't have .members when fetched

lofty falcon
#

it works, cheers

cyan quail
#

havefun

lofty falcon
#

Now I will just optimize it

proud pagoda
cyan quail
#

ahh rip

lofty falcon
#
async def btn_pressed(msg):
    answered = False
    while (answered == False):
        try:
            myinteraction = await bot.wait_for('interaction', check=lambda i: i.user == msg.author and i.channel == msg.channel, timeout=180)
        except asyncio.TimeoutError:
            await msg.delete()
            return
        else:
            answered = True
            return myinteraction.data['custom_id']
#

if someone needs it, await for button click with custom_id as return value from the button

#

exactly what I needed

iron halo
#

idk if this is possible but how do you pass the context of a message that has a button into a function im bad at explaining

class buttons(discord.ui.View):
    def __init__(self, x):
        super().__init__()
        self.x = x
    @discord.ui.button(label="a", style=discord.ButtonStyle.grey)
    async def callback(self, button, interaction):
        await function(interaction.context, x) # <----```
#

github copilot said interaction.context but it does not exist

#

and just interaction says AttributeError: 'Interaction' object has no attribute 'author'

pallid trench
#

access interaction.user for the user that instigated the interaction

iron halo
#

function is just another command but idk how to do the ctx part

#

i cant do interaction.user bc its ctx.author in the actual function

pallid trench
#

context is not an attribute of Interaction

iron halo
#

so if i wanted it to redo the command by pressing a button how would i give ctx?

pallid trench
#

you dont

iron halo
#
class buttons(discord.ui.View):
    def __init__(self, x, context):
        super().__init__()
        self.x = x
        self.context = context
    @discord.ui.button(label="a", style=discord.ButtonStyle.grey)
    async def callback(self, button, interaction):
        await function(context, x) # <----``` i just did this idk if its bad but it works
pallid trench
iron halo
#

i said it works lmfao

pallid trench
#

misread that

lofty falcon
verbal marten
#

Anyone know why my commands are taking a while to sync even though I am using debug_guilds

gleaming falcon
#

Is there a way to avoid system messages for pins, or is the only way to manage those by watching on_message for a message.type of pins_add?

(Kinda sucks cuz I'm doing it in a Thread, and if I delete the message, it will show "No recent messages" in the thread highlights instead of the actual important bit, the message itself)

rare ice
final fractal
#

I'm using PyMongo and I got this error:

  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke
    await injected(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}```
#

code:

post = {'_id' : 0, 'user' : ctx.author, 'uses' : +1}
collection.insert_one(post)```
verbal marten
#

your connection string is probably incorrect

#

plus pymongo is blocking use motor instead

amber shale
#

how to get user description?

cerulean yacht
amber shale
#

I was trying to get user description from banned user

#

and how to give reason such that it shows in that list

crimson lynx
#

Hey everyone, sorry, probably a v dumb question so asking here; I want to send a message without an interaction, but have it ephemeral & in a specific channel; now with the recent discord API changes in not sure how to achieve this ¿

amber shale
#

i am also a beginner

#

what happen when you use channel.send?

crimson lynx
# amber shale what happen when you use channel.send?

I try to tie it to a specific channel (server related bot), checked permissions, but I didn't figure out how to get it to be ephemeral whilst without a user interaction ; I tried tying it to a user id variable sadly no succes

amber shale
crimson lynx
amber shale
#

ok, i dont know

#

what about dms?

crimson lynx
#

That might work, but due to everything kinda being in that one channel and server related I'd imagine people like to keep it there

#

But thanks anyways 🌻 👍

odd silo
#

Is it possible for a bot to join a group chat?

silver moat
odd silo
#

ok

cerulean drum
#

how do I ignore these when I override run method

sleek arch
#

Ty :)

fervent cradle
#
class DmMes:
    

    def mute_dm(reason, mod, days, hours, minutes, seconds):
        embed = discord.Embed(
                        title=":mute: Вы были заглушины",
                        description="Вы были заглушины  на сервере **HFD**",
                        color=discord.Colour.from_rgb(56, 27, 161)
                    )
        embed.add_field(name="Причина", value=f"`{reason}`")
        embed.add_field(name="Модератор", value=f"`{mod}`")
        embed.add_field(name="Время", value=f"`{days}д. {hours}ч. {minutes}м. {seconds}cек.`")
    
    def ban_dm(reason, mod):
        embed = discord.Embed(
                    title=":hammer: Вы были заблокированны",
                    description="Вы были заблокированны  на сервере **HFD**",
                    color=discord.Colour.from_rgb(56, 27, 161)
                )
        embed.add_field(name="Причина", value=f"`{reason}`")
        embed.add_field(name="Модератор", value=f"`{mod}`")
    
    def warn_dm(reason, mod):
        embed = discord.Embed(
                title=":exclamation: Вы получили предупреждение",
                description="Вы получили предупреждение на сервере **HFD**",
                color=discord.Colour.from_rgb(56, 27, 161)
            )
        embed.add_field(name="Причина", value=f"`{reason}`")
        embed.add_field(name="Модератор", value=f"`{mod}`")```

i want to send this message to user
What i need to return?
rugged lantern
#

learn python

lofty falcon
#
bot = discord.Client(intents=discord.Intents.all())
bot = commands.Bot(intents=discord.Intents.all(),command_prefix="!")
#

how did you import discord

#

which module do you use

#

anyways, just look at my example

fervent cradle
#

intents = discord.Intents.all() should work if you have everything installed right

lofty falcon
#

windows or mac ?

#

which library do you use

#

did you install the dependencies ?

#

with pip

amber shale
#

how to send a paginator in bridge command? i got this error TypeError: expected Interaction or BridgeContext, not <class 'discord.commands.context.ApplicationContext'>

#

it is discord.ext.commands.Bot

#

you can add this statement at the top of the file 👇

#

from discord.ext import commands and then you can use commands.Bot

naive remnant
#

What's the limit of webhooks

amber shale
#

is there any way to get hex_code as user input?

#

i think you will need to create a role for muted user and assign that to user

cyan quail
#

use member.timeout_for

#

(maximum 28 days)

cyan quail
#

think paginator is broken for bridge right now

#

allgood

amber shale
#

thanks

#

i am also going to use that

cyan quail
#

yeah timeouts handle muting for you, pretty cool feature

amber shale
#

yes

cyan quail
#

Yeah that works, though you don't need to purge

#

If you respond as ephemeral=True then it'll be silent

#

Allgood

#

Oh wait

#

Duration

#

Id explain but I can't rn, you need to use datetime.timedelta; just read the docs, it explains there

oblique sonnet
#

how can i make a reaction listener persistent

cyan quail
#

an example would be py from datetime import timedelta ... await member.timeout_for(timedelta(days=1, hours=12)) which would timeout the member for 1 day and 12 hours

#

the docs i linked just there shows you other things you can pass in to customize it

amber shale
#

what if i gave

#

36 hours

cyan quail
#

it would convert it

amber shale
#

ok

cyan quail
#

Only days, seconds and microseconds are stored internally. Arguments are converted to those units:

A millisecond is converted to 1000 microseconds.
A minute is converted to 60 seconds.
An hour is converted to 3600 seconds.
A week is converted to 7 days.

amber shale
#

ok thanks 🙂

cyan quail
#

if you want your duration argument to be in minutes then yeah that works

#

just make sure you import it

amber shale
#

i was thinking to convert time to seconds, so user could input like 7d or 2.5h or 1.3w

cyan quail
#

either way works; in my case, i just made tons of arguments which are all optional

#

i just read the docs GuraShrug

#

timeout uses a datetime.datetime object to specify an exact time

#

but for easier usage, you should use timeout_for with datetime.timedelta

#

though discord's planning on adding a datepicker option for slash commands so timeout may become more convenient

iron halo
#

all my commands work most of the time but at random times it just decides to do this

#

even tho it works 5 seconds earlier

fervent cradle
#

anyone has the code for a delete button which deletes the bot message

pallid trench
#

its very simple to make

lofty falcon
#

when you send the message with the bot

#
botmsg = await msg.channel.send("This MSG is from the bot")
await botmsg.message.delete()
#

you need to store the information from the message you send out in a variable, so you can later access the stuff

#

you can pass over the botmsg to the button callback

#

you can also use a simpler form

#

in the callback the interaction variable has every information you need

#
view=View()
thisbutton = Button(label="Delete Me", row=1, style=discord.ButtonStyle.secondary, custom_id="DelBTN")
  thisbutton.callback=on_interaction
async def on_interaction(interaction: discord.Interaction):
  await interaction.delete_original_message()
granite forge
#

I'm modelling my bot as subclass of discord.Bot
How do I register a slash command in the cog and in the subclass of discord.Bot(my actual Bot class)?
The decorator @discord.Bot.slash_command needs a self argument, and that makes sense, since the examples on docs showed the actual bot instance being used, I've tried that as well, which works.
But I want to have the commands in my subclass/cogs, do I use @discord.slash_command? I've tried that, it doesn't get registered as a slash command in the end.

#
class MyBot(discord.Bot):
  @discord.slash_command(name='ping', description='Latency', guild_ids[x])
  async def ping(self,ctx):
    await ctx.respond(f'Pong! Latency is {self.latency}')
fervent cradle
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/listeners.py", line 60, in on_message
    await ip_embed(ctx)
  File "/home/container/backend.py", line 181, in ip_embed
    await ctx.reply(embed=ipembed, view=DeleteButton(ctx))
  File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1639, in reply
    return await self.channel.send(content, reference=self, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1467, in send
    raise InvalidArgument(f"view parameter must be View not {view.__class__!r}")
discord.errors.InvalidArgument: view parameter must be View not <class 'backend.DeleteButton'>

what does this mean?

serene spindle
#

Quick question: how do you get the content of a deleted message(it's for logging)?

silver moat
#

b!rtfm pyc on_messgae_delete

dire spadeBOT
silver moat
#

b!rtfm pyc on_message_delete

silver moat
#

I can spell

serene spindle
#

so I should use on_raw_message_delete instead of on_message_delete?

fervent cradle
#

is there an example to the delete button code in the bot?

silver moat
granite forge
fervent cradle
# full basin code
class DeleteButton:
    def __init__(self, ctx):
        super().__init__()
        self.value = None
        self.ctx = ctx

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
    async def button_callback(self, button, interaction):
        button.disabled = True  # set button.disabled to True to disable the button
        button.label = "Deleted"  # change the button's label to something else
        await self.ctx.delete_original_message()
        await interaction.response.edit_message(view=self)  # edit the message's view
    await ctx.respond(embed=ipembed, view=DeleteButton(ctx))
silver moat
full basin
#

you're not subclassing discord.ui.View

fervent cradle
#

also

#

how do i delete the bots message?/

silver moat
#

which one lol

fervent cradle
#

the one on which the button is

#

like the bot replies with a message and that message has the delete button

lofty falcon
#

i posted it above

#

interaction

full basin
#

interaction.response.delete_original_measage()?

lofty falcon
#

yes

fervent cradle
#

ah thanks

signal pine
#
async def add(self, ctx, du: discord.Option(discord.Member, description="The user you want to select"):
  ...

Hey! Right now the parameter inside of the slash command is required. How would I make it just a normal option that isn't required?

silver moat
#

inside of the discord.Option

signal pine
silver moat
#

default is what it is if the user skipped it

fervent cradle
#
class DeleteButton(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
    async def button_callback(self, button, interaction):
        interaction.response.delete_original_measage()

TypeError: View.to_components() missing 1 required positional argument: 'self'

signal pine
signal pine
silver moat
#

yes

fervent cradle
# silver moat full traceback thanks
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/listeners.py", line 60, in on_message
    await ip_embed(ctx)
  File "/home/container/backend.py", line 181, in ip_embed
    await ctx.reply(embed=ipembed, view=DeleteButton)
  File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1639, in reply
    return await self.channel.send(content, reference=self, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1469, in send
    components = view.to_components()
TypeError: View.to_components() missing 1 required positional argument: 'self'```
silver moat
#

this should force discord to update

signal pine
#

Also could be the reason, that it didn't work before

silver moat
silver moat
#

np

fervent cradle
#
Ignoring exception in view <DeleteButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Delete' emoji=None row=None>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/backend.py", line 458, in button_callback
    interaction.response.delete_original_message()
AttributeError: 'InteractionResponse' object has no attribute 'delete_original_message'

in ```py
class DeleteButton(discord.ui.View):
def init(self):
super().init()
self.value = None

@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
    interaction.response.delete_original_message()
silver moat
#

so which message do you want to delete?

#

the message that the view is on?

fervent cradle
silver moat
#

so you can pass in ctx and use await self.ctx.message.delete()

fervent cradle
#

lemmetry

fervent cradle
# silver moat so you can pass in ctx and use `await self.ctx.message.delete()`

this gives message has no attribute message, and self.ctx.delete() gives

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/backend.py", line 458, in button_callback
    await self.ctx.delete()
  File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1204, in delete
    await del_func
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 356, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
silver moat
#

oh you're using on_message, not an actual prefixed command

lofty falcon
#

try that, not response

silver moat
#

and interaction.message is the message that was responded with

fervent cradle
fervent cradle
#

i could do

msg = await ctx.send("e")
await msg.edit("e", view=view)

and then could i use msg.delete() within the button?

silver moat
#

I still don't understand your name convensions

subtle jay
#

Is it possible to get a role in a slash comamnd choice?

silver moat
subtle jay
#

if I want to get a certain role in the choices, how would I get that role?

fervent cradle
# silver moat I still don't understand your name convensions

404 again doing

msg = await ctx.respond(embed=ipembed)
wait msg.edit(embed=ipembed, view=DeleteButton(msg))

class DeleteButton(discord.ui.View):
    def __init__(self, msg):
        super().__init__()
        self.msg = msg

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
    async def button_callback(self, button, interaction):
        await self.msg.delete()

fervent cradle
#

wait i have existing code for something like this

silver moat
#

ctx.respond responds with an interaction

fervent cradle
#

oh wait i think i messed something up

fervent cradle
subtle jay
#

this is what I have

silver moat
fervent cradle
fervent cradle
subtle jay
#

what if I only wanted 2 roles in the server?

fervent cradle
#

wait ill show u

subtle jay
#

ok

silver moat
#

then just take a str

#

and then put the roles in the choices and convert them to roles internally

subtle jay
#

yeah Ive done that before but was wondering if there was an easier way

fervent cradle
#
role: discord.Option(choices=
                       [
                            discord.OptionChoice("role1", value="roleid"),
                            discord.OptionChoice("rol2", value="role_id2"),

                           ]),
#

here, make value the role id

#

and you can get the role object

silver moat
#

It really is the same either way, you still need to do it internally

fervent cradle
#

also, fixed the delete button issue

silver moat
#

good

#

mind sending code so future people have a reference?

fervent cradle
#
class DeleteButton(discord.ui.View):
    def __init__(self, message):
        super().__init__()
        self.message = message

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
    async def button_callback(self, button, interaction):
        await self.message.delete()

and the actual message code

message= await ctx.reply(embed=ipembed)
await message.edit(embed=ipembed, view=DeleteButton(message))
silver moat
#

what is ctx

fervent cradle
#

I didn't use CTX in the button

silver moat
#

Is this in a command or on_message

fervent cradle
silver moat
#

then please name your variables to what they actually are

#

if it's a message name it message. if it s a context name it ctx

fervent cradle
#

kk

sleek arch
#

When I click my button I get this:
<main.messageTest object at 0x0000014F21494A30>
I think I need to define something like __init__ but im not sure how as what I have tried is not working.

sleek arch
#
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
    async def login_help2(ctx, user:discord.Member, *, message=None):
        message = "message"
        embed = discord.Embed(title=message)
        embed.title = "title."
        embed.description = "des"
        embed.color = 0x11806a
        await user.send(embed=embed)
        await ctx.respond(content="content", embed=None, ephemeral=True)




class MyTest(discord.ui.View):
    @discord.ui.button(label="Button 1", style=discord.ButtonStyle.primary)
    async def first_button_callback(self, button, interaction):
        await interaction.response.send_message(messageTest())

    @discord.ui.button(label="Button 2", style=discord.ButtonStyle.primary)
    async def second_button_callback(self, button, interaction):
        await interaction.response.send_message("Done")

@client.slash_command() # Create a slash command
async def button(ctx):
    await ctx.respond("Click mee", view=MyTest())```
fervent cradle
#

my question too

silver moat
#

because you are using super() and not supering anything

#

and it doesn't remotely make sense

fervent cradle
sleek arch
#

messageTest is the embed that gets sent in the userDM (top of the code)

sleek arch
fervent cradle
#

@sleek arch

silver moat
fervent cradle
#

he's sending MyTest() and not subclassing discord.ui.VIew

#

Why i can not use bot in select menu? when i use bot in parms from selcet menu then come this error..

Ignoring exception in command test:
Traceback (most recent call last):
  File "", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "", line 63, in test
    await ctx.send(f"Test", view=ticket_select())
TypeError: ticket_select.__init__() missing 1 required positional argument: 'bot'

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

Traceback (most recent call last):
  File "", line 344, in invoke
    await ctx.command.invoke(ctx)
  File "", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: ticket_select.__init__() missing 1 required positional argument: 'bot'
class ticket_select(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=None)
        self.bot = bot
silver moat
fervent cradle
#

ohh

#

i know

#

it's supposed to be view=ticket_select(bot)

sleek arch
#

Okay all I am trying to do is make a button send a user the DM. I have probably done this really wrong

fervent cradle
silver moat
#

so you can send message with await interaction.response.send_message() and sending a DM with await user.send() where user is a either a discord.User or a discord.Member

sleek arch
#

Would I not need the async def login_help2(ctx, user:discord.Member, *, message=None):

silver moat
sleek arch
#

I mean it works

silver moat
#

clearly it doesn't

#

that by itself, sure

#

but not like this

sleek arch
silver moat
#

Do you even know Object Oriented Programming in the slightest?

fervent cradle
#

why does button and interaction have to be there when the IDEs saying they aren't used? without them the button breaks

sleek arch
silver moat
silver moat
fervent cradle
#

ah, got it

fervent cradle
#

AttributeError: 'NoneType' object has no attribute 'create_text_channel' huh? think

fervent cradle
silver moat
#

what's guild

fervent cradle
#

and where's guild from

#

guild = self.bot.get_channel(guild_id)

#

guild_id = 934909638514704474

silver moat
#

well, so you get_ tries to find the guild in your bot's cache.

#

you can turn on guild caching with the guilds intent

fervent cradle
#

guild intent whats that and how turn on ?

#

on the dev portal

#

but this is on?

#

all intent

silver moat
fervent cradle
#

oh

silver moat
#

?tag intents

obtuse juncoBOT
#
import discord
from discord.ext import commands

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

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

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

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

intents=discord.Intents.all()

silver moat
fervent cradle
#

yep

silver moat
#

in that case try fetching the guild

#

b!rtfm pyc fetch_guild

fervent cradle
#

or print?

silver moat
#
guild = await self.bot.fetch_channel(guild_id)
#

like this

fervent cradle
#

ah this is working lul thanks

silver moat
#

np

restive harbor
#

How do I get the voice of an author from a bridgeCommand?

kindred sail
kindred sail
#

are you restarting your bot a lot?

verbal marten
kindred sail
verbal marten
#

Any idea what the ratelimit for command registration is?

cyan quail
#

twice per minute i think?

kindred sail
#

its been a while but that sounds right

verbal marten
#

They haven't appeared all day

short lion
#

hi

#

how do i check if a user has a certain role

kindred sail
#

role in user.roles

golden cairn
#

eyo why user.banner dont work even if I got a banner ?

kindred sail
golden cairn
golden cairn
cyan quail
#

and premium_since is only available for member objects

proud pagoda
#

What's the ApplicationContext version of ext.Context.command_failed?

fervent cradle
#

discord.errors.ExtensionFailed: Extension 'cogs.set' raised an error: AttributeError: 'SlashCommand' object has no attribute 'command'

full basin
#

You're probably doing @discord.slash_command.command()

full basin
#

You use Discord.slash_command

#

Or

from discord import slash_command 

@slash_command```
fervent cradle
full basin
#

Are you sure it's the same line

amber shale
#

is there any way to give user list of permission he can edit in a channel or category in bridge command?

undone falcon
#

Do your bot need special permission to use the button on the paginator in a channel ?

#

I cant change pages

undone falcon
#

I get that error

amber shale
#

code?

undone falcon
#

I fixed it by making it ephemeral=True

amber shale
#

ok

vestal raven
#

I have two folders in which I have cogs. I have this code to load the cogs from both the folders


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

for file in os.listdir("./cogs2"):
    if file.endswith(".py"):
        bot.load_extension(f"cogs2.{file[:-3]}")

For some reason, only the cogs from cogs2 , and 1 cog from cogs is being loaded. I ensured that the cogs I'm looking to load are in the proper folder. Also, I tried moving the cogs from cogs folder, which are not loading, to cogs2, but they're still not loading. I've have proper setup function in every single file.
I also tried to manually add the cog with bot.load_extension("cogs.<filename>") for every cog which is not loading, but it also didn't work.

outer obsidian
vestal raven
outer obsidian
vestal raven
#

didn't make any difference

outer obsidian
vestal raven
#

I'm using MongoDB with pymongo in the cogs which are not loading. Can that be the issue?

outer obsidian
vestal raven
#

I thought if there was any error, it will be raised by itself

outer obsidian
#

and see if any error is raised

vestal raven
#

wait

#

No error came

outer obsidian
#

weird

vestal raven
#

ig I'll just try to import the subclasses Cog and use bot.add_cog() in the main file

outer obsidian
vestal raven
#

wait

#

How do I share it?

#

How to get the url of the code which I pasted. never used it b4

outer obsidian
#

and copy the link

vestal raven
outer obsidian
vestal raven
#
def setup(bot):
    bot.add_cog(Class(bot))

This is how the setup function is, right?

vestal raven
#

Then yes, I've written them correctly

outer obsidian
vestal raven
#

wait

#

These are all the files. No other files are there

outer obsidian
vestal raven
#

ohk wait

#

The lines saying loaded <cog> are because I had the line print("loaded {}".format(__name__)) in __init__ of every cog

outer obsidian
vestal raven
outer obsidian
outer obsidian
vestal raven
#

Well, everything was working b4 I add the snipe_slash.py file, though there was no change in any other file

outer obsidian
#

it could be the problem then

vestal raven
#

wait

#

Well, I removed that file from that directory, but the other files still didn't load

outer obsidian
#

try revert all the changes and see if it works

vestal raven
vestal raven
outer obsidian
#

and might as well as big changes on a file

vestal raven
#

nvm. Figured out. It was because of a a import I was doing. As soon as I commented that line, the cog loaded

vestal raven
outer obsidian
#

you dont need the double dot

vestal raven
#

ohh ok. thanks

amber shale
#

is there anyway to to have grouping in bridge command?

fervent cradle
#

Is there a way to check how long a user is in a vc or do I have to do stuff like take the time where he joined and compare it to the time where he left?

tawdry marten
fervent cradle
#

Works, just wanted to ask if there was an easier way something like member.voice.time

fervent cradle
#

Ik

#

This is why I made this

fiery tiger
fervent cradle
#

in select menu i use py await interaction.followup.send(f"you work in Greggs and earn **{number1}** :key:" )

But i've got this errorpy discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

How can i fix it?

fervent cradle
fervent cradle
#

disable it

fervent cradle
#
class Dropdown(discord.ui.Select):
    def __init__(self, bot):
        self.bot = (
            bot  
        )
        
        options = [
            discord.SelectOption(label="Work in Greggs", emoji="👩‍🍳", ),
            discord.SelectOption(label="Bake cupcakes", emoji="🧁"),
            discord.SelectOption(label="Wash car", emoji="🚓"),
            discord.SelectOption(label="Sell book", emoji="📕"),     
        ]
        

        super().__init__(
            placeholder="Choose work",
            min_values=1,
            max_values=1,
            options=options
            
        )

    async def callback(self, interaction: discord.Interaction):
        user = interaction.user.id
        number = random.randint(500, 1000)
        number1 = random.randint(1000, 1500)

        self.disabled=True
        if self.values[0] == 'Work in Greggs':
            
            
            await interaction.followup.send(
                f"you work in Greggs and earn **{number1}** :key:"
            )
           
            b.add_bal(self=b, user=user, amt=number1)
            self.disabled = True
            await interaction.response.edit_message(view=self)
            
      
        elif self.values[0] == 'Sell book':
            await interaction.response.send_message(
                f"you sell book and earn **{number}** :key:"
                
            )
            b.add_bal(self=b, user=user, amt=number) 
            await interaction.message.delete(delay=0.5, reason='Work complete') 
            
        ```
fervent cradle
# fervent cradle ```py class Dropdown(discord.ui.Select): def __init__(self, bot): se...
class Dropdown(discord.ui.Select):
    def __init__(self, bot):
        self.bot = (
            bot  
        )
        
        options = [
            discord.SelectOption(label="Work in Greggs", emoji="👩‍🍳", ),
            discord.SelectOption(label="Bake cupcakes", emoji="🧁"),
            discord.SelectOption(label="Wash car", emoji="🚓"),
            discord.SelectOption(label="Sell book", emoji="📕"),     
        ]
        

        super().__init__(
            placeholder="Choose work",
            min_values=1,
            max_values=1,
            options=options
            
        )

    async def callback(self, interaction: discord.Interaction):
        user = interaction.user.id
        number = random.randint(500, 1000)
        number1 = random.randint(1000, 1500)

        self.disabled=True
        if self.values[0] == 'Work in Greggs':
            
            
            await interaction.response.send_message(
                f"you work in Greggs and earn **{number1}** :key:"
            )
           
            b.add_bal(self=b, user=user, amt=number1)
            self.disabled = True
            await interaction.response.edit_message(view=self)
            
      
        elif self.values[0] == 'Sell book':
            await interaction.followup.send(
                f"you sell book and earn **{number}** :key:"
                
            )
            b.add_bal(self=b, user=user, amt=number) 
            await interaction.message.delete(delay=0.5, reason='Work complete') 

try this

fervent cradle
#

yea

#

we can't

fervent cradle
#

try the new edit code

#

but we still response it

#

discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
But your error is there or not? the interaction can not find the webhook i think because of followup your first option.

#

But you can wait for someone else Girl_Dance

amber shale
#

how to disable button in paginator?

#

after like 1 min

#

or so

oblique sonnet
#

How can I add a member to a private text channel while creating a channel.... ik i have to use overwrites.... but can figure it out

#

please help ;-;

fervent cradle
#

Is there any way to read the role id of the person who entered the slash command?

wind jay
#

is it possible to execute a loop every 2 days?

fervent cradle
#
AttributeError: 'ReplayButton' object has no attribute 'to_components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 127, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 1171, in _invoke
    await command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ReplayButton' object has no attribute 'to_components'
class ReplayButton(discord.ui.Button):
    def __init__(self, ctx, video_url):
        super().__init__()
        self.ctx = ctx
        self.url = video_url
        self.client = client

    @discord.ui.button(label="Re-Play", style=discord.ButtonStyle.gray)
    async def button_callback(self, button, interaction):  # Don't remove the two unused variables
        await self.client.cogs.get('Music').play_video(self.ctx, self.url)
grizzled sentinel
grizzled sentinel
fervent cradle
fervent cradle
#

is ok?

fervent cradle
#

and no idt it'll work

grizzled sentinel
#

I think you might be looking to make it a view. So instead of sub classing a button you can subclass a view discord.ui.View

fervent cradle
grizzled sentinel
grizzled sentinel
fervent cradle
#

yes

fervent cradle
grizzled sentinel
# fervent cradle yes

You need to loop through the list of roles that you get from ctx.author.roles and in the for loop you can check if role.id == 123

fervent cradle
#
for role in ctx.author.roles:
  if role.id == 123:
    pass
#

fix the indentation

grizzled sentinel
amber shale
fervent cradle
silent kite
#

discord.Permissions().manage_nicknames and discord.Permissions().manage_roles both give me that it's False even though i've enabled those permissions in the developer portal and readded the bot with the correct permissions. Checking the bots permissions in the 'Roles' tab inside the server shows that it has these permissions

errant craneBOT
#

Here's the slash cog groups example.

#

Here's the slash groups example.

grizzled sentinel
fervent cradle
#

yes

grizzled sentinel
#

I suggest you use discords built in setting for that.

fervent cradle
#

And when you say?

grizzled sentinel
#

server settings > integrations > "your bot" > click on the command you want to limit > set everyone to "X" and add the role you want to yes.

grizzled sentinel
# silent kite discord.Permissions().manage_nicknames and discord.Permissions().manage_roles bo...

discord.Permissions is not the permissions for your bot. You are creating a Permissions object that would normally be used for something like Member.set_perms(my_perms) you need to get your bots permissions using this to get the Member version of your bot for that guild
https://docs.pycord.dev/en/master/api.html#discord.Guild.me
and than get the permissions like this
https://docs.pycord.dev/en/master/api.html#discord.Member.guild_permissions

fervent cradle
#

Wave , why is the if query not working?

    @discord.ui.button(label="test", emoji="📌", style=discord.ButtonStyle.green)
    async def test_callback(self, button, interaction):
        role = interaction.guild.get_role(rolle)
        if role in interaction.user:
            await interaction.response.send_message(f"Rechte")
        else:
            await interaction.response.send_message(f"Du hast keine Rechte.")

TypeError: argument of type 'Member' is not iterable..

fervent cradle
#

Ups thanks

silent kite
#

I've given my bot the manage messages permission, put it's role on the highest place possible. But it still can't remove reactions of the lowest role.

#

Only when I give the bot Admin can it do it

minor pecan
#

hello im created a ticket system with select menu but isn't work it

class Ticket(discord.ui.View):
    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "for open ticket click me", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="buy in store",
                emoji=":shop:",
                description="for a simple buy click me"
            ),
            discord.SelectOption(
                label="q before buy",
                emoji=":1095roleiconsupportteam:",
                description="for say your question click me"
            ),
            discord.SelectOption(
                label="درخواست همکاری",
                emoji=":2853612e94fd237b37de09de4ad62a57:",
                description="for send partner message click me"
            ),
            discord.SelectOption(
                label="ss",
                emoji=":alert~1:",
                description="ssss"
            ),
            discord.SelectOption(
                label="other",
                emoji=":2952checkmh:",
                description="fjdsjdjsd"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message(f"creating ticket: {select.values[0]}",ephemeral=True)
        categ=discord.utils.get(self.guild.categories,name="Opened Ticket") # selecting the category(by its name)
        r1=self.guild.get_role(993493250893693022)
        overwrite={
        self.guild.default_role:discord.PermissionOverwrite(read_messages=False),
        self.me:discord.PermissionOverwrite(read_messages=True),
        self.author:discord.PermissionOverwrite(read_messages=True),
        r1:discord.PermissionOverwrite(read_messages=True)
        }
        channel=await categ.create_text_channel(name=f"{self.author.name}-{self.author.discriminator}",overwrites=overwrite,topic=f"{self.author.id}") # creating the channel/ticket
        em=discord.Embed(title="your ticket is created",description=f"Ticket created by {self.author.mention}",timestamp=datetime.utcnow(),color=discord.Color.random())

        await asyncio.sleep(3)

        await interaction.response.send_message(f"{channel.mention} if you want go to ticket click me",ephemeral=True)
        await channel.send(embed=em)


@client.slash_command()
async def ticket(ctx):
    embed=discord.Embed(title=":haraketli_: Create a New Ticket :haraketli_:", description=":3817hammermh: Click on the appropriate option to contact us!", color = discord.Color.blurple())
    embed.set_image(url = "https://cdn.discordapp.com/attachments/993493251690594384/998517377316687892/fortnite-battle-royale-1920x1080-864336699.jpg")
    await ctx.send(embed=embed, view=Ticket())
    await ctx.respond("done!", ephemeral=True)
#

do you know what is the problem

#

?

silent kite
#

maybe create a separate thread for this because it's a bigger problem

silent kite
#

I'm trying to remove the reaction of an user who has the lowest role, I've placed my bots' role as the highest. Yet when I use remove_reaction I get a missing permissions error. My bot has the manage messages and view messages permission. And when I give the bot Admin it runs just fine

grizzled sentinel
#

Is the bots riles overridden in that specific channel?

silent kite
#

Now it is, and it works. Thanks!

naive remnant
#

How can I make my bot send errors

amber shale
#

why is this happening while grouping command

#
class Test(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        super().__init__()
        self.bot = bot

    @commands.group(name="group")
    async def _group(self, ctx: commands.Context):
        await ctx.reply("in group")

    @_group.command(name="command")
    async def _command(self, ctx: commands.Context):
        await ctx.send("in command")```
#

code

rare ice
#

So @commands.group(name="group", invoke_without_command=False)

amber shale
#

ok thanks

oblique sonnet
#

Is it possible for me to give channels under a specific category as options?

rare ice
oblique sonnet
naive remnant
#

b!rtfm pyc member

naive remnant
#

b!rtfm pyc member author

dire spadeBOT
naive remnant
#

b!rtfm pyc member interaction

dire spadeBOT
gleaming falcon
#

Is there a helper method of some sort that would return the lowest role that has a certain permission (e.g. View) in a channel?

I don't know that channel.changed_roles (this doesn't even seem to be what I would expect) or channel.overwrites tell the full story.

Edit: Ended up just iterating channel.permissions_for(role) for all roles in the server. Probably better than just trying to get the lowest role (since roles are linear in theory but not always in practice)

worldly schooner
#

can someone give me a guide on how to make pages on embeds?

silver moat
#

?tag guide

obtuse juncoBOT
worldly schooner
#

thanks

serene spindle
#

So I'm trying to use on_raw_message_delete and I know to get it to work you'll need payload and put payload. somewhere in front of code too iirc, but idk where, could someone tell me how to get it to work?

naive remnant
#

What's the code to know who used the slash command (author)

silver moat
naive remnant
#

Doesn't work

#

Nvm how can I make the bot get errors and then send them

silver moat
#

Why does it not work

worldly schooner
#

how do I make a time limit for a bot.wait_for() response?

worldly schooner
#

use the self if you are in a cog

worldly schooner
naive remnant
silent kite
#

If my bot can't remove reactions, and has the highest role. Also has permission to manage messages, see them and the history. Has access to the channel. What permissions am I still missing? Because the code still gives a missing permissions error.

delicate jolt
#
    @commands.command(description="Sends a list of the bot's commands.")
    async def help(self, ctx):
        embed = discord.Embed(title=f"Cries | Help",
                                description=f"Testing", colour=col)
        await ctx.respond(embed=embed)```
#

Would this automatically create a slash command?

#

If I define debug_guilds in commands.Bot?

#

I've reinvited the bot with applications.commands

young bone
#

but where is the slash_command?

young bone
delicate jolt
#

Oh I see

#

Is it just slash_command.command?

#

from discord import slash_command

young bone
#

from discord.command import slash_command

delicate jolt
#

Why did it ping 😭

young bone
#
@slash_command()
.
delicate jolt
#

Cheers

#

Worked ty

young bone
#

\o

naive remnant
#

Can I make a bot delete all the webhooks of a channel?

delicate jolt
#

How can I disable one single button? by custom_ID?

#

Also I press the button, It completes the function

#

But says this how can I stop that?

pallid trench
#

respond to the interaction

young ledge
#

Hey is there a way to detect if the message sent in a channel is a media (pic or vid) or is it a text

delicate jolt
#
message.attachments[0].url.endswith('mp4'):```
young ledge
#

png and all that crap?

delicate jolt
#

list = ['mp4', 'jpeg']

if message.attachments[0].url.endswith in list:

#

You could just make a list and put those in

young ledge
#

true true

delicate jolt
#

Etc .png .svg

young ledge
#

thx mate

delicate jolt
#

Idk if there is a straight up way

#

Then if just a message

#

if not message.attachments

#

Yeah you get the jist

#

Np

#

@ me if you need anymore help w it

young ledge
#

@delicate jolt why dont i just check if the message is a text or a number and just go based on that

#

cant i do that?

young ledge
#

If anything except a vid or a pic is sent to a channel it gets deleted

delicate jolt
#

Just do

#

if message.attachments:

#

Then ctx.message.delete

delicate jolt
#

Else:

#

pass

young ledge
#

yeah ik but would that be instant?

delicate jolt
#

Yeah

young ledge
#

bet

delicate jolt
#

Am I able to disable the view after say 5 seconds if no interaction

proud pagoda
#

Yeah, set timeout=5

delicate jolt
#

And how can I restrict the interaction to the command executer?

#

ty

proud pagoda
#

Add an interaction_check to the view

#

otherwise, return false after giving an error message so that it doesn't say the Application didn't respond

delicate jolt
#

Epic cheers

proud pagoda
#

You're welcome

delicate jolt
#

Where does the timeout actually go?

#

In the view=MyView()?

#

It does

proud pagoda
#

yeah when you declare the view

#

view=MyView(timeout=5)

delicate jolt
#

Is there a way to disable the button?

#

Like grey it out when timed out?

#

So It can't be clicked

young ledge
#

How do I wait for a message in a specific channel?

#

like using the channel ID

delicate jolt
#
    def check(m):
        return m.channel == ctx.channel

    message = await bot.wait_for('message', check=check)```
#

How to get the ID of the user who originally ran the slash command?

#

Like after pressing the buttons

#

If I pressed Right I want to get the original person who ran the help slash command

young ledge
rare ice
young ledge
#

alright bet

#

am so confused for no reason

proud pagoda
silver moat
#

and then edit the message with the updated view with the updated button

worldly schooner
grizzled sentinel
worldly schooner
#

hold my sc doest not load

#

i added ctx.interaction rn

#

just to see if it works

grizzled sentinel
#

remove the () when setting the callback. you dont want to call the function you want to reference it.

#

buttonleft.callback = button_callback

worldly schooner
#

so it would be like button_callback()

#

oh k

#

thx

#

issue solved, thankyouu

grizzled sentinel
#

other wise you would be calling the function instead of just getting its "name" to call later

worldly schooner
#

understood

night cargo
#

How many discord servers can a bot own?

grizzled sentinel
fervent cradle
#

I'm looking to store a user's ID and their CSID (given manually using this vetting command), but I seem to have an issue relating to a KeyError or something.

    csids[str(user.id)]["CSID"] = csid
KeyError: '706324825181913128'```
#

For clarification, 706324825181913128 is someone's ID.

fervent cradle
#

issue solved btw

fresh gust
#

could someone help me understand what this error is?

    from .voice_client import VoiceClient, VoiceProtocol
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\voice_client.py", line 55, in <module>     
    from .gateway import *
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\gateway.py", line 37, in <module>
    import aiohttp
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\__init__.py", line 6, in <module>
    from .client import (
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 35, in <module>
    from . import hdrs, http, payload
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\http.py", line 7, in <module>
    from .http_parser import (
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\http_parser.py", line 15, in <module>      
    from .helpers import NO_EXTENSIONS, BaseTimerContext
  File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\helpers.py", line 667, in <module>
    class CeilTimeout(async_timeout.timeout):
TypeError: function() argument 'code' must be code, not str```


For context, im trying to use the Spotipy library with my bot
lost lodge
#

hey

#

any one knows how to delete messages of a specific member? with that:

#

await channel.purge(limit=2)```
fervent cradle
amber shale
#

is there any way to invoke a command by bot? for example if bot joins a new guild i want him to run a intro command

amber shale
lost lodge
#
            member = discord.Member
            channel = ctx.channel
            def get_purge_member(m):
                return member == member
            embed = discord.Embed(title='Clear ▼',
                                  description=f"{ctx.author.mention} has cleared **{amount}** messages of {member.name}!",
                                  color=0xdc143c)
            deleted = await channel.purge(limit=amount, check=get_purge_member())
            await ctx.send(embed=embed)
            await asyncio.sleep(3)```
amber shale
#

check=get_purge_member

lost lodge
#

error

amber shale
#

can i get full code

#

member is none here

amber shale
# lost lodge
    @commands.command()
    async def clear(self, ctx, amount: int, member: discord.Member = None):
        if member == None:
            channel = ctx.channel
            embed = discord.Embed(
                title="Clear ▼",
                description=f"{ctx.author.mention} has cleared **{amount}** messages!",
                color=0xDC143C,
            )
            await channel.purge(limit=amount)
            await ctx.send(embed=embed)
            await asyncio.sleep(3)
            await channel.purge(limit=2)
        else:
            channel = ctx.channel

            def get_purge_member(message):
                return message.author == member

            embed = discord.Embed(
                title="Clear ▼",
                description=f"{ctx.author.mention} has cleared **{amount}** messages of {member.name}!",
                color=0xDC143C,
            )
            await channel.purge(limit=amount, check=get_purge_member)
            await ctx.send(embed=embed)
            await asyncio.sleep(3)```
lost lodge
#

works thanks!

merry briar
#

how do I make the buttons work after restarting?

class JoinButton(discord.ui.Button):
    def __init__(self, bot):
        """."""

        super().__init__(
            label=".",
            style=discord.ButtonStyle.green,
            custom_id="join",
            emoji="👥",
        )

        self.bot = bot

    async def callback(self, interaction: discord.Interaction):
        pass
delicate jolt
#

Is there a way to get user id from who ran the slash command?

lost lodge
#

Guys i need help

#

i have a copyright problem

#

can any one help me?

errant craneBOT
#

Here's the persistent example.

grizzled sentinel
grizzled sentinel
grizzled sentinel
#

Edited

grizzled sentinel
lost lodge
# grizzled sentinel Don't ask to ask :) What is the problem? I'm no lawyer tho

i have programmed a discord bot and a former friend has partially helped. He then received the code from me because I was on vacation and he wanted to do something. The problem is now that we have argued and he now threatens to publish the code. I have also offered him to delete his code places but he refused this offer.

grizzled sentinel
#

Did your code have a license?

lost lodge
grizzled sentinel
#

This basically says that sharing unlicensed code is not the agreement of it being open-source. So if you remove there code you would be able to have claims against it I belive.

https://opensource.stackexchange.com/questions/233/what-happens-if-i-share-code-online-without-any-licence-declaration

#

That is the extent I can help tho.

lost lodge
delicate jolt
#
Ignoring exception in view <HelpView timeout=10 children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='▶️' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 375, in _scheduled_task
    await item.callback(interaction)
TypeError: right() missing 1 required positional argument: 'ctx'```
#
    @discord.ui.button(emoji="▶️", style=discord.ButtonStyle.blurple, custom_id="help:right")
    async def right(self, button: discord.ui.Button, interaction: discord.Interaction, ctx):
        m = await interaction.channel.fetch_message(interaction.message.id)
        embed = discord.Embed(title=f"Help", description=f"\nPick a category!", colour=col)
        embed.set_footer(text="Page <2/2>",
                         icon_url="IMAGE_URL")
        await m.edit(embed=embed, view=HelpView(ctx))
        await interaction.response.send_message("")```
grizzled sentinel
delicate jolt
grizzled sentinel
#

sorry i meant
interaction.user.id

delicate jolt
#

I am trying to make it so

#

It brings up a help menu

#

by doing /help

#

But the person who ran /help is only able to use that menu

grizzled sentinel
#

set ephemeral=True in the resonse

delicate jolt
#

But

#

Im using buttons

#

and the bot can't edit the embed

#

When ephemeral is set to true

grizzled sentinel
#

It should be able to. try using interaction.edit_original_message() instead of fetching the message and than editing it

delicate jolt
#

Right okay I'll try that

delicate jolt
grizzled sentinel
#

what do you mean? the buttons? if it is ephemeral only they will be able to see it

delicate jolt
#

Yes

#

Wait hang on

delicate jolt
#
Ignoring exception in view <HelpView timeout=10 children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='◀️' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 375, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\tearx\Documents\GitHub\Cries-Bot\cogs\help.py", line 68, in left
    await interaction.edit_original_message(embed=embed, view=HelpView())
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 388, in edit_original_message
    data = await adapter.edit_original_interaction_response(
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 211, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
#

When it's sent with ephemeral=True

grizzled sentinel
#

can you show your code

delicate jolt
#

Yes

grizzled sentinel
#

for the whole help command (you can cut out parts with lots of text)

delicate jolt
#
    @discord.ui.button(emoji="◀️", style=discord.ButtonStyle.blurple, custom_id="help:left")
    async def left(self, ctx, interaction: discord.Interaction):
        embed = discord.Embed(title=f"Help", description=f"\nPick a category!", colour=col)
        embed.set_footer(text="Page <1/2>",
                         icon_url="IMAGE LINK")
        await interaction.edit_original_message(embed=embed, view=HelpView())```
delicate jolt
# grizzled sentinel for the whole help command (you can cut out parts with lots of text)
    @slash_command(description="See a list of commands available. For more detail type /help <name of a command>")
    async def help(self, ctx):
        embed = discord.Embed(title=f"Help", description=f"""
        **[Help]()**
          ⤷ See a list of commands available.
          For more detail type /help <name of a command>  
          
        **[Ping]()**
          ⤷ Displays bot latency.
        
          """, colour=col)
        embed.set_footer(text="Page <1/2>",
                         icon_url="IMAGE_LINK")
        await ctx.respond(embed=embed, view=HelpView(), ephemeral=True)```
grizzled sentinel
#

try adding interaction.response.defer() as the first line of your buton callback

fierce elm
#

Does discord strip whitespace from the end of a message?

delicate jolt
#

alright

grizzled sentinel
#

there is a line above and below, yup, test got striped

delicate jolt
#
  interaction.response.defer()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in view <HelpView timeout=10 children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name=':arrow_backward:' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 375, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\tearx\Documents\GitHub\Cries-Bot\cogs\help.py", line 69, in left
    await interaction.edit_original_message(embed=embed, view=HelpView())
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 388, in edit_original_message
    data = await adapter.edit_original_interaction_response(
  File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 211, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
delicate jolt
#

i need to await it

#

Okay that works

grizzled sentinel
#

discord only gives 3 seconds to respond to an interaction, if you need more time they allow that command that bumps up the timeout time to 15 min

delicate jolt
#

I see I see thanks

grizzled sentinel
#

when the interaction timeout of discord side and you try to interact with it you get that error. is your ping high?

delicate jolt
#

Yeah

#

250ms

#

For some reason

#

Running on my pc

grizzled sentinel
#

still not super high.

delicate jolt
#

Say I have 8 pages

#

For my help menu

#

And Im on page 4 How could I check that?

#

Is there anything built in or would I need to store it

#

In a DB or something

#

like

Message_Id Page

ID HERE Page here

grizzled sentinel
#

lots of the stuff you are making is built into the pagnater feture of pycord i would suggest cheking it out

delicate jolt
#

You got an example?

#

Please

errant craneBOT
#

Here's the paginator example.

delicate jolt
#

ty

grizzled sentinel
#

and there is a whole section of the docs

delicate jolt
#

I see thanks

restive harbor
golden lake
#

has anyone implemented a generic method for discerning attribute differences from event listeners' before and after objects?

#

really dont want to write a million if statements everywhere

#

yes. see TextChannel.create_webhook() and then use any trivial REST request module to do the HTTP POST to it

#

thats where the REST request module comes in

#

there are many. requests is popular

#

oh i see

#

look at the Webhook object's attributes

#

you want to access Webhook.url

#

i think that includes both the ID and the token

#

TextChannel.create_webhook() returns the Webhook which you can then use

#

no

#

doesnt look like __str__ is implemented

#

you need Webhook.url

#

yeah

#

documentation is ur friend

#

i just ctrl+f'd 'webhook' in the api reference lol

#

you did ctx.create_webhook rather than ctx.channel.create_webhook

#

and also you didnt catch the result in a variable

#
        hook = await ctx.channel.create_webhook(name=name, avatar=avatar, reason=reason)
        await ctx.respond(hook.url)
restive harbor
#

I am using a bridge command and have the problem that with the prefixed command it only takes the first word, f.e.: !play rick roll, will only take "rick" and doesn't do anything with the "roll". Is there anything I can add to the bridge command to fix this problem?

pallid trench
#

because spaces are perceived as separators for params

#

the command cannot have spaces in its name or give your command an argument to take

golden lake
# golden lake has anyone implemented a generic method for discerning attribute differences fro...

this is very silly to me

    @commands.Cog.listener("on_guild_channel_update")
    async def handle_channel_edit(
        self,
        before: GuildChannel,
        after: GuildChannel
    ) -> None:
        """Updates the database with guild channel setting changes."""
        if not before.guild:
            return

        delta = dict()
        column_map = {
            "category": "parent_channel",
            "position": "position",
            "name": "name",
            "topic": "topic",
            "nsfw": "age_gated",
            "slowmode_delay": "slowmode_delay",
        }
        for attrib in dir(after):
            if attrib not in column_map.keys():
                continue
            _before = getattr(before, attrib)
            _after = getattr(after, attrib)
            if _before != _after:
                delta[column_map[attrib]] = _after

        if len(delta) == 0:
            return

        q = "UPDATE guild_channel_settings AS settings SET "
        v = dict(channel=after.id)
        while len(delta) > 0:
            pair = delta.popitem()
            q += f"\"{pair[0]}\" = \%({pair[0]})s"
            if len(delta) > 0:
                q += ",\n"
            v[pair[0]] = pair[1]
        q += """
            FROM guild_channels AS channels
            WHERE
                channels.id = settings.channel_ref
                AND channel = %(channel)s;
        """

        logger.debug(f"Query: {q}")
        logger.debug(f"Bound args: {v}")

        with self._bot.db.connection() as conn:
            conn.execute(q, v)
#

i was looking at an ORM but i dont actually see a way to natively map arbitrary objects to database objects

#

ive never used an ORM before tho

vale wigeon
#

Hi, just wanted to check, there's no official way to check for user connections (e.g. Reddit, YouTube, Twitch, etc.), right?

rare ice
#

No there isn’t at the moment.

worldly schooner
#

im trying to disable my buttons when the on_timeout function is activated, but the view timeout and the buttons are still enable (but ofc they dont respond to interaction)

#

can I have some advise?

smoky forge
#

and on_timeout() does not have any arguments other than self

worldly schooner
worldly schooner
worldly schooner
#

is just that now

smoky forge
#

so to edit the message you'll have to pass the ctx

#

and do await ctx.message.edit(view=self)

worldly schooner
#

only errors

smoky forge
#

what error are you getting?

worldly schooner
#

this one i got from self.ctx.message.edit

smoky forge
#

ohh wait

#

when its a prefixed command and you get the context message, its the command being run

#

ctx.message would be !hello (or with whatever prefix you're using)

worldly schooner
#

figured out

smoky forge
#

does it work?

worldly schooner
#

yes

#

thanks for trying to help

smoky forge
#

no problem

near hollow
#

Is it possible to resync commands in a cog? Have been trying but doesn't seem to work

vital blade
#

reload the cog

near hollow
vital blade
#

i think slash commands load automatically after an hour

#

if you added new slash commands try to kick and reinvite the bot in the server

near hollow
#

Well kicking and reinviting isn't really ideal

fervent cradle
#

Hello. Is there a way to disable all buttons on bot stop

basically there may be multiple buttons active when the bot is on, non persistent and timeout=None. Is there a way to disable them when we stop the bot (i dont expect them to un-disable when it comes online again)

silver moat
fervent cradle
#

yep, but is there a way to "grey them out"

#

when the bot dies

silver moat
#

unless you have a way to know when your bot dies

#

then no

fervent cradle
#

is a way to execute stuff when the bot is going to be killed

silver moat
#

how do you even know that it’s going to be killed

lofty falcon
fervent cradle
#

ooo interesting idea, and example of that being implemented?

lofty falcon
#

you can also store the msg data in a database and have another "bot" or script run in the background that notices if your bot dies and it restarts the bot to grey them out

silver moat
fervent cradle
#

I mean i restart my bot, it doesn't go offlien for long

lofty falcon
fervent cradle
#

also, disabling buttons on timeout, message doesn't exist?

fervent cradle
empty tree
fervent cradle
empty tree
#

ah they might have included it now

#

are you on the latest version

fervent cradle
#

yep

empty tree
#

try adding message as a parameter in the init function and pass it when calling the class (same way you did with voice)

#

like send the message first, save it as a variable and then edit it to include the view with the message passed into it

fervent cradle
#

ah got it

fervent cradle
empty tree
#

i think ctx would just include the message of the person who sent the command

#

not too sure though

lofty falcon
#

ctx.message

empty tree
#

wouldn’t that just be the user’s message

lofty falcon
#

botsmg = await msg.send("something")
and pass over the botmsg

empty tree
#

yeah that’s what I said

lofty falcon
prisma flicker
#

my on_member_join suddenly stopped being called, I even shrunk it down to just print

@commands.Cog.listener()
async def on_member_join(self, member):
    print(f"{member.display_name} joined")```
#

edit and delete aren't working either

#

it would appear the entire cog isn't being loaded

silver moat
#

add store=False to the load_extension()

prisma flicker
#

I had a syntax error in a view

#

is there a cooldown option for modals and/or buttons?

silver moat
storm geode
#

how do i make one of thoes "custom" checks

#

like

@bot.command
@isverifed()
async def command(ctx):
proud pagoda
#

With commands.check:

def check_if_it_is_me(ctx):
    return ctx.message.author.id == 85309593344815104

@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
    await ctx.send('I know you!')
silver moat
#

examples are on the docs

#

b!rtfm pyc commands.checks

proud pagoda
#

As a decorator:

def is_me():
    def predicate(ctx):
        return ctx.message.author.id == 85309593344815104
    return commands.check(predicate)

@bot.command()
@is_me()
async def only_me(ctx):
    await ctx.send('Only you!')
obsidian cargo
#

Is there any way I could get a view from a message?

#

or an interaction

silver moat
obsidian cargo
#

ok thx

silver moat
#

b!rtfm pyc message.components

dire spadeBOT
pallid trench
#

wasnt there a method in View to convert those components into a view?

storm geode
#

aw. these <t:1659292760:R> dont work in footers?

proud pagoda
#

b!rtfm pyc ui.View

next comet
#

Do webhooks have a rate limit?

young ledge
#

when i try to get the link of the attachemnt the user sent this happens

#

print(str(ctx.attachments[0].url))
IndexError: list index out of range

round rivet
#

you probably dont have message content intents, or the message has no attachments

young ledge
#

it does i send a image and it sneds

round rivet
#

then you don't have message content intents

round rivet