#Basic Pycord Help (Quick Questions Only)

1 messages ¡ Page 26 of 1

silver moat
#

if you have any suggestions, feel free to suggest them.

wary rover
#

Why is my button added after my first one? Logically it is in the __init__ so it should be added first, right?

wary rover
silver moat
wary rover
#

I thought __init__ was absolutely always loaded first

silver moat
#

well, init isn't called until an object created with this class is used.

#

while the class comes with all those items.

wary rover
# silver moat specifically which part?

Something like this, just to have the necessary code to display the link button

class ExempleView(discord.ui.View):
    def __init__(self):
        super().__init__()
        
        #Add link button
        self.add_item(discord.ui.Button(label="Click Here", url="https://google.com"))
    
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!")
#

@silver moat @cyan quail
Thank you so much for taking the time to help me! 🙂

cyan quail
#

allgood

rotund current
#

Is it possible to have the bot check to see if it has the proper permissions in a channel before attempting to post a message?

wary rover
#

When I deactivate buttons, they automatically change place and the link goes first, any idea?

patent escarp
#

https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording.py
Tried copying all the lines in this one, replacing what was need to apply to my bot, but when I tried out the commands, and spoke in the VC, I got the error: discord.opus.OpusNotLoaded

After using the /stop command, the console was spammed with the message: Decoder Process Killed

Assuming the /stop error was a direct occurence with discord.opus.OpusNotLoaded, I searched a bunch of articles of how to fix this, but none of the solutions worked

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/audio_recording.py at master ¡ Pycord-Development/pycord

#

Any ideas?

#

Full error: py Exception in thread DecodeManager: Traceback (most recent call last): File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 545, in run data.decoded_data = self.get_decoder(data.ssrc).decode(data.decrypted_data) File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 564, in get_decoder self.decoder[ssrc] = Decoder() File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 440, in __init__ _OpusStruct.get_opus_version() File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 373, in get_opus_version raise OpusNotLoaded() discord.opus.OpusNotLoaded

#

apparently, adding discord.opus.load_opus() does not work, since it requires one positional argument name. However, multiple sources say that it does not need a name

unreal ibex
#

how do i take string args in slash command?
async def dumb(ctx,idea:str):

gleaming falcon
glossy sand
#

AttributeError: module 'discord.commands.permissions' has no attribute 'is_user'

My bot was written in version 2.0.05b, I'm trying to rewrite to the latest version, since permissions was changed, how do you know check if the discord user using a slash command has a certain ID?

Also where do I find how many things have changed since that version?

tribal bough
sinful osprey
#

How do people go about implementing multiline input considering we still don't have that built into slash commands? Can either add a separator to split text on or add a reply listener? Any better ideas?

tender seal
#

How do I attach files to a message using Slash Commands?

tender seal
#

U+2424 is the newline character

#

in a for loop

#

you'd check every character

spice oyster
#

You need to convert oldest to date() before comparing it at the end.

tender seal
#

if it isn't U+2424 add it to the string

#

and if it is, just add ```python
f'\n'

spice oyster
#
oldest = datetime.today().date()
sinful osprey
#

I mean the problem is that you can't enter multiline text in a slash command to begind with, it's currently still only single line (with planned(?) support for multiline input being talked about half a year ago)

tender seal
#

oh, you mean that

#

well..

#

I guess

#

you could add a separator string

#

to indicate a new line

spice oyster
tender seal
spice oyster
tender seal
#

I know you're gonna say ReadTheDocs

tender seal
#

ok I'll try that

spice oyster
sinful osprey
#

Forgot what the other method was (edit: it's followup), but respond is just a property/convinience alias so you don't have to use a specific one

spice oyster
#

Then that part was fine and I didn't see it well. I don't know what's wrong.

#

You could also try this, together with the previous suggestion, although I feel like there is a better solution.

if msg.created_at.date() < oldest:
tender seal
#

hey uh

#

how would I make a my bot look like it's typing?

#

and is it possible to hide the person who used a slash command

#

that sucks

#

how exactly

#

I'm a newbie

tranquil thunder
#

what does this mean?

dull smelt
#

it comes up when you try to make the bot send message.embeds and the embed is from the bot itself

fervent cradle
#

what type of errors are logged with the logging module of py-cord

#

file errors or anything like that have not been logged, so i dont understand which errors will get logged

lost lodge
#

how to get the member that send the context

proud mason
#

can i use interaction.response.edit_message if I have deferred the response?

#

how else do i edit the original msg if i have deferred?

#

(its a button)

dull smelt
#

hello

#

How can I check whether someone responds to my modal or just presses cancel?

lost lodge
#

how can i check if a user have a permission (not with @commands.has_permission())

spice oyster
# tranquil thunder what does this mean?

You sent an Embed as content. When sending/editing the message, you need to write embeds = [embed] as parameter or something like that, depending on the rest of your code.

dull smelt
spice oyster
fringe socket
spice oyster
fringe socket
#

Exactly why I don't suggest it elite

dull smelt
#

i'll make a thread incase someone knows a way

spice oyster
fringe socket
#

But just in case you still want to...

async def command(ctx):
     ctx.send('<response you want>')
     ctx.respond('<doesn't matter what you put here>',ephemeral=True)
dull smelt
naive steppe
#

is there a way to make the "waiting for response" timeout longer than 10 seconds?

#

or would i have to send a message and just edit it after the desired result executes

spice oyster
#

For doing what, exactly? Are you already using defer?

naive steppe
#

no
so i have a command like /build_users

it gets all users and puts into a text doc

tho while it does that it ends up timing out and then not sending when getting to ctx.respond since its no longer an alive command

spice oyster
#

Try with defer then.

naive steppe
#

defer?

naive steppe
#

thank you

#

perfect

errant craneBOT
#

Here's the slash cog example.

hollow vale
#

Is there any docs for permissions in bridge commands?

fervent cradle
#
    def __init__(self, bot):
        self.bot = bot
     

class Verify(discord.ui.View): 
    @discord.ui.button(label="Verify Me", style=discord.ButtonStyle.primary, emoji="🤝") 
    async def button_callback(self, button, interaction):

        verification = discord.Embed(title="Get Verified!", description="Click the button below to get verified and be able to access the entire server!")
        @commands.command(name="startverify", description="Start The Verification Progress")
        async def startverify(self,ctx):
             await interaction.response.send_message(self,ctx,embed = verification, view=Verify())
             print("e")``` Why isnt the section after verification = being run? the print was for a test to check, and it isnt being run (the startverify is greyed out)
young bone
fervent cradle
#

i had ctx.respond before, i changed it to interaction whilst trying to fix ut

#

it*

#

and its a slash command

#

self is cause its in a cog and is self.bot = bot

young bone
#

But you use commands.command

fervent cradle
#

should it be commands.slash_command?

young bone
#

Yes

fervent cradle
#

I changed it, Its still greyed out

young bone
#

And than ctx.respond()

fervent cradle
#

I have changed both thanks, although still greyed out ill restart the bot and see if it works

#

dosent work, no slash command

#

I think it might be an indentation error but im not sure

#

@young bone

lost lodge
#

Hello, why my \n are not hidden and don't do a new line in my embed?

sinful pivot
#

I've been trying to use asyncio.sleep() for adding a 24 hour time delay since I have a poll type of thing with dropdowns(on discord) and it just seems to not sleep at all. It just expires after like 4 minutes, what's the best way to sleep?

fringe socket
fringe socket
fervent cradle
#
    def __init__(self, bot):
        self.bot = bot
     

class Verify(discord.ui.View): 
    @discord.ui.button(label="Verify Me", style=discord.ButtonStyle.primary, emoji="🤝") 
    async def button_callback(self, button, interaction):

verification = discord.Embed(title="Get Verified!", description="Click the button below to get verified and be able to access the entire server!")
@commands.slash_command(name="startverify", description="Start The Verification Progress")
async def startverify(self,ctx:discord.ApplicationContext):
    await ctx.respond(self,embed = verification, view=Verify())``` its this now,
fringe socket
#

Not sure tbh. Kinda new to Pycord still learnng

fervent cradle
spice oyster
fervent cradle
proud pagoda
livid salmon
#

This is definitely less a python specific question and more towards Discord programming in general, but is there any way to make good, large tables in Discord without the formatting breaking on mobile??

Embeds don't work, since they only go up to three columns on PC and only one on mobile. I tried making ASCII tables using the codeblock formatting as well but that can only go so wide too.

spice oyster
cyan quail
#

i guess you could render it as an image and upload it but that would seem pretty stupid on the user end

livid salmon
#

Yeah, that was one of my options of last recourse. Either that or writing values to like a google spreadsheet and sending the user that link.

storm hinge
#

is it possible to find the message that the command is replying to?
for example,
A sends a message, B replies to A's message and B's replying message is a bot command (like !help)
responding to B's command, is it possible to fetch A's message?

livid salmon
silver moat
ionic snow
#

How can I make a slash response only visible to the user who sent the command?

dull smelt
#

ctx.respond('whatever', ephemeral = True)

#

@ionic snow

ionic snow
#

Thanks

ionic snow
fervent cradle
#

Can webhooks be server-wide, or at least post to multiple channels?

dull smelt
silver moat
fervent cradle
cyan quail
silver moat
#

hmm true

cyan quail
#

webhooks being able to post to any channel would be like

#

the antithesis of their purpose

fervent cradle
still helm
#

in the examplecode of recording audio is the filename the user_id.mp3
I want to add the username, but i don´t understand how to solve this. I don´t understand how the id is generated


    async def finished_callback(self, sink, channel: discord.TextChannel, *args):
        recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
        await sink.vc.disconnect()
        files = [
            discord.File(audio.file, f"{user_id}.{sink.encoding}")
            for user_id, audio in sink.audio_data.items()
fervent cradle
#

how do I implement this with a slash command

@bot.command()
async def upload_file(ctx):
    attachment_url = ctx.message.attachments[0].url
    file_request = requests.get(attachment_url)
    print(file_request.content)```
errant craneBOT
#

examples/app_commands/slash_options.py lines 51 to 67

@bot.slash_command(name="attach_file")
@option(
    "attachment",
    discord.Attachment,
    description="A file to attach to the message",
    required=False,  # The default value will be None if the user doesn't provide a file.
)
async def say(
    ctx: discord.ApplicationContext,
    attachment: discord.Attachment,
):
    """This demonstrates how to attach a file with a slash command."""
    if attachment:
        file = await attachment.to_file()
        await ctx.respond("Here's your file!", file=file)
    else:
        await ctx.respond("You didn't give me a file to reply with! :sob:")```
fervent cradle
#

brilliant

#

I love squids

umbral island
#

Can someone help with getting a user banner url. Ive tried some methods found on google but it for some reason it gives a nontype error for the user when using member.banner.url
I am getting member from a discord option in the command member: discord.Option(discord.Member, description="The User In The Guild.", required=False)
ERROR:
'NoneType' object has no attribute 'banner'

I know that the member object is not nontype because I can get the user avatar url just fine.

Using pycord version 2.2.2

ionic snow
#

Is there a way to check if the bot and the author in the same channel? I only have ctx available since it's commands.check annotation for commands

woeful spindle
#

Also, make sure the user actually has a banner. The plain banners provided by discord don’t actually count as banners - you need a custom one!

umbral island
#

and dont worry I have a custom

#

MotorDatabase object is not callable. If you meant to call the 'fetch_user' method on a AsyncIOMotorClient object it is failing because no such method exists.

I must be doing it wrong

#
try: banner_url = Client.fetch_user(member)
except AttributeError: banner_url = Client.fetch_user(ctx.author)```
woeful spindle
umbral island
#

ah i sees

#

ty ty

woeful spindle
#

Of course :)

umbral island
#

finally got it, thank you!

lost lodge
#

Hello
I have the problem that when i have a \n from a arg in a embed it just doesn't works. Can anyone solve that problem?

full basin
#

Re-do your indentation

rare ice
#

.docslink discord.Interaction.user

rare ice
#

It’s interaction.user not .author

fervent cradle
#

is there a method to change bot's profile picture?

vast tusk
#

hey so im trying to make a user info command it worked well, but when i convert it to a slash command i got this error AttributeError: 'NoneType' object has no attribute 'created_at'

full basin
#

What did you define as user

vast tusk
#

ctx.author

spice oyster
lost lodge
# silver moat show code ty
    @commands.command()
    @commands.has_any_role('「TEAM」')
    async def projects_add(self, ctx, button_text, title, *, description):
        title.split()
        description.split()
        button_label = ""
        if button_text.startswith('https://discord.gg/'):
            button_label = "Discord"
        else:
            button_label = "Website"
        embed = discord.Embed(title=title, description=description, colour=0x7fffd4)
        embed.add_field(name="jbk", value="dnnand \n sad")
        embed.set_footer(text=f"Project Owner -> {ctx.author}")
        button = discord.ui.Button(label=button_label, style=discord.ButtonStyle.gray, url=button_text)
        view = View()
        view.add_item(button)
        channel = self.bot.get_channel(1028240598060257352)
        await channel.send(embed=embed, view=view)
        await asyncio.sleep(5)
        await ctx.message.delete()```
silver moat
#

and what does it show currently

lost lodge
silver moat
#

yes

lost lodge
patent escarp
#

https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording.py
Tried copying all the lines in this one, replacing what was need to apply to my bot, but when I tried out the commands, and spoke in the VC, I got the error: discord.opus.OpusNotLoaded

After using the /stop command, the console was spammed with the message: Decoder Process Killed

Assuming the /stop error was a direct occurence with discord.opus.OpusNotLoaded, I searched a bunch of articles of how to fix this, but none of the solutions worked
Full error: py Exception in thread DecodeManager: Traceback (most recent call last): File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 545, in run data.decoded_data = self.get_decoder(data.ssrc).decode(data.decrypted_data) File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 564, in get_decoder self.decoder[ssrc] = Decoder() File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 440, in __init__ _OpusStruct.get_opus_version() File "/home/runner/Recron/venv/lib/python3.8/site-packages/discord/opus.py", line 373, in get_opus_version raise OpusNotLoaded() discord.opus.OpusNotLoadedAny ideas?

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/audio_recording.py at master ¡ Pycord-Development/pycord

silver moat
#

how are you giving your arguments

lost lodge
silver moat
patent escarp
#

Ok

silver moat
lost lodge
#

yes

lost lodge
silver moat
lost lodge
#

ye

silver moat
#

python don’t recognize that escape character

silver moat
#

try removing spaces?

lost lodge
cyan quail
#

that's a prefix command, right? don't bother with \n, just use actual line breaks

cyan quail
#

description is your final command argument

lost lodge
#

aha

#

and how to fix it?

cyan quail
#

so instead of typing \n like \n this you can
type
like
this

lost lodge
#

ah

#

ok

cyan quail
#

if i had to guess, something is pre-emptively escaping the character for you

lost lodge
cyan quail
#

go on

silver moat
#

i think you can use
description = repr(description)

lost lodge
#

i have the problem that i have a runtime error with that:

@bot.event
async def on_ready():
    print("-------------------")
    print(f"Logged in as {bot.user.name}")
    print("-------------------")
    print(f'Ping Âť {round(bot.latency*1000)} ms')
    print("-------------------")
    print(f"PyCord API version: {discord.__version__}")
    print("-------------------")
    print(f"Python version: {platform.python_version()}")
    print("-------------------")
    status_task.start()

@tasks.loop(minutes=1.0)
async def status_task():
    await bot.change_presence(status=discord.Status.idle, activity=discord.Game(name=f"dm me for support!"))
    await asyncio.sleep(20)
    await bot.change_presence(status=discord.Status.idle, activity=discord.Game(name="mention for help"))
    await asyncio.sleep(20)
    await bot.change_presence(status=discord.Status.idle, activity=discord.Game(name="https://unviewed.xyz/"))
    await asyncio.sleep(20)```
cyan quail
#

ehh

#

idk the ratelimit for change_presence but isn't it pretty low?

#

anyway what's the actual error

young bone
lost lodge
cyan quail
#

sure

lost lodge
#

thx

fervent cradle
#

still unable to create slash commands

#

it doesn't show up

fervent cradle
young bone
fervent cradle
young bone
#

oh, ye you cannot use capital letters in a command

fervent cradle
#

How to edit an ephemeral slash command response message?

#

or it's not possible?

cyan quail
fast totem
#

hey. i need help.
some error with await bot.sync_commands()

spice oyster
proud pagoda
#

So you need to change the name of one of them

fast totem
#

check all slash, bridge commands name

spice oyster
#

What's the best way to turn "140~180 seconds (other text here)" into "2:20~3:00 minutes (other text here)"? Is it possible to do it without using Regex? I need to do that for every string in a list. Some strings in the list have 2 blocks like that, separated by "\n".

silver moat
#

if they are seperated by the same amount of spaces/same characters, you can use .split()

spice oyster
#

Can I do something like .split("~ ")?

silver moat
#

yes

fast totem
#

I found the cause.
one command with guild_ids set to multiple servers now, and it seems to recognize this command as duplicates.
Is there any way to solve it?

spice oyster
cyan quail
#

it's not particularly scary either, just test it with a site like regex101 beforehand

#

but if you know the formatting is gonna be consistent then split will work either way

spice oyster
#

I'm more than familiar with it already. I said without it because I used to overuse it. Maybe in this case is better because the alternative solution is just too much code.

cyan quail
#

is there an example of like, a set of these strings you need to parse?

#

since you were saying it isn't as simple as split

spice oyster
#
timings = [
    "140~180 - 2 * X:00 seconds (after Cavalry death)",
    "80~110 seconds (after Tribute capture)\n150~190 seconds (after Curse end)",
    "185 seconds (after Nukes collection)"
]
#

These are the 3 types that are in the list. I need to convert from seconds to minutes, or from minutes to seconds. It doesn't matter which one I use as a base.

cyan quail
#

that's certainly interesting

#

is it always seconds?

spice oyster
#

Yes, it's either all seconds or all minutes in the list.

cyan quail
#

i'd say uhh

spice oyster
#

Now I'm using two separate lists for each version but I'd like to set up a conversion.

cyan quail
#

- 2 * X:00 seconds
does this part matter

spice oyster
#

Yes, it gives important information to the reader.

#

That part is not going to be converted, though.

cyan quail
#

ah ok that makes it easier

#

i guess .split()[0] to remove everything after the numbers

#

then you can attempt to .split("~")

spice oyster
#
for timing in timings:
    values = []
    values.append(timing.split(" ")[0])
    if "\n" in timing:
        values.append(timing.split("\n")[0].split(" ")[0].split("~"))
    else:
        values.append(timing.split(" ")[0].split("~"))
for value in values:
    minutes, seconds = value // 60, value % 60
    value = f"{minutes}:{seconds}"
cyan quail
#

and convert each item in that list

#

well yeah that's fine

#

it's ultimately using splits or regex

#

there's probably some lib out there that'll magically parse it for you but it's likely not worth the effort

spice oyster
#

It's not working. I'm going with Regex because it's easier. blobpain

dusty wraith
#

Is it possible to "reregister" all slash commands without restarting the entire bot? I have a reload command that reloads all cogs, but if I make any new slash commands, they don't register with Discord.

rotund current
#

Is it possible to get a ApplicationContext out of an AutocompleteContext?

spice oyster
# spice oyster It's not working. I'm going with Regex because it's easier. <:blobpain:881536122...

Done! What else can I improve? I couldn't make it work without using a temp list. rooThink

if format == "Minutes":
    temp = []
    for timing in timings:
        values_in_seconds = re.findall("[0-9]+", timing)
        values_in_minutes = [f"{(int(value) // 60):02}:{(int(value) % 60):02}" for value in values_in_seconds if int(value) > 2]
        for value_in_seconds, value_in_minutes in zip(values_in_seconds, values_in_minutes):
            timing = timing.replace(value_in_seconds, value_in_minutes)
        temp.append(timing.replace("seconds", "minutes"))
    timings = temp
spice oyster
spice oyster
rotund current
spice oyster
dusty wraith
spice oyster
cyan quail
#

nah it's a lib issue

#

but if i'm not mistaken, you can fix it by doing bot._pending_application_commands = [] before sync_commands

fallow hawk
#

are heartbeats broken for anyone else?

cyan quail
#

you might be better off asking a doctor about that

undone estuary
#

or smoke weed instead

fallow hawk
dusty wraith
cyan quail
#

before

#

(i don't think it matters too much but just to be safe i suppose)

dusty wraith
#

The cogs haven't reloaded yet though.

cyan quail
#

?

#

clear pending list > reload cogs > sync commands

dusty wraith
#

Ah, okay. I'll try that. Thanks.

livid salmon
#

Is there any way to do variable length arguments with slash/bridge commands?

gleaming falcon
gleaming falcon
#

My thought for doing something like that is to build a pseudo-dict (ie:

my_arg1: enter_value
my_arg2: enter_value

and put it as the value in a modal for users to replace. Then simply build a parser for that.

Ugly and prone to breakage, but I feel like it’d work, depending on use case

livid salmon
#

Damn, sad. Thanks anyways though

surreal glade
#
@bot.event
async def on_raw_reaction_add(payload):
    message_id = payload.message_id
    if message_id == 1028484247952048148:
        guild_id = payload.guild_id
        guild = bot.get_guild(1014307996618203216)

        if payload.emoji.name == "ohio":
            role = discord.utils.get(guild.roles, name="OHIO CITIZEN")
        else:
            pass

        if role is not None:
            member = discord.utils.get(lambda m : m.id == payload.user_id, guild.members)
            if member is not None:
                await member.add_roles(role)
            else:
                pass
#

my reaction roles are not adding

#

@silver moat

silver moat
#

?tag idw

obtuse juncoBOT
#

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

surreal glade
#

When i add the ohio reaction, nothing happens on the bots end, no errors or anything, yet it does not add the role that i want

silver moat
#

do you have reaction intents?

surreal glade
#

testing now

#

@silver moat still doesnt work

silver moat
#

does the event fire at all?

surreal glade
surreal glade
silver moat
surreal glade
#

@silver moat i modified my code a little, and now it gives me an error (hope!!)

@bot.event
async def on_raw_reaction_add(payload):
    print("tes")
    message_id = payload.message_id
    if message_id == 1028490427202023526:
        guild = discord.utils.find(lambda g : g.id == payload.guild_id, client.guilds)

        if payload.emoji.name == "ohio":
            role = discord.utils.get(guild.roles, name="OHIO CITIZEN")
        else:
            pass

        if role is not None:
            member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
            if member is not None:
                await member.add_roles(role)
                print("te")
            else:
                print("mnf")
-Ignoring exception in on_raw_reaction_add
-Traceback (most recent call last):
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\client.py", line 382, in _run_event
-    await coro(*args, **kwargs)
-  File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 26, in on_raw_reaction_add
-    guild = discord.utils.find(lambda g : g.id == payload.guild_id, client.guilds)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\utils.py", line 406, in find
-    for element in seq:
-TypeError: 'property' object is not iterable
tes
silver moat
#

you can just bot.get_guild(id)

surreal glade
silver moat
#

what are all of your intents?

surreal glade
#

@silver moat

gleaming falcon
#

Dumb question - paginators (i.e. dropdowns with buttons) can be added to regular messages, or only slash interactions?

In other words, could someone use a 'legacy' command and get a message (non-ephemeral, obvs) with a View?
(It's late, apologies for clunky wording)

[edit: nm, https://guide.pycord.dev/interactions/ui-components/dropdowns implies yes]

surreal glade
#

ur the only other person i could think of that would know this

undone falcon
#

what would be a great database to use with a small bot, that is easy to set up ?

copper dew
undone falcon
#

i was think that but I saw there was no support for await. Would it affect badly ?

copper dew
undone falcon
#

I see that is a very interresting option ! Thanks you !

undone falcon
#

I will certainly be better than using pickle !

#

😅

plush meadow
#

hi everyone! forgive me if this is a common question. I'm kinda deep using discord.py, and i've just found out that pycord even exists. how much is changed? will I have trouble just swapping out my import statement?

copper dew
plush meadow
#

son of a gun

#

looks like i'm at square one

copper dew
#

most of the stuff is still the same, but with some tweaks. creating slash commands and stuff are completely different from dpy irc

plush meadow
#

i don't have any intricate stuff, mostly just sending messages and embeds at the moment

#

i guess i'll swap and run, and start putting out fires

#

thank you for the insanely fast response btw, much appreciated

undone falcon
#

Is it possible to know what slash commands failed, with what parameters ?

tame rose
#

Why does the bot don't add cogs when it's put inside the on_ready() event?

copper dew
tame rose
#

Not bot.add_cog()?

copper dew
tame rose
#

What

#

🤔

#
from sample import Example
import discord

bot = discord.Bot()

@bot.event
async def on_ready():
    print('Ready')

bot.add_cog(Example(bot))
bot.run('token')
#

This is what I'm using rn. Is thing wrong?

copper dew
# tame rose This is what I'm using rn. Is thing wrong?

probably would look like this:

from sample import Example
import discord

bot = discord.Bot()

@bot.event
async def on_ready():
    print('Ready')

bot.load_extension("Cog") # assumes that your cog is named Cog.py, and is in the same directory as your bot file
bot.run('token')
#

and at the end of each cog:

example.py

from discord.commands import commands

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

def setup(bot):
    bot.add_cog(Example(bot))
tame rose
fringe socket
#

Hey, how do I make mentioning the bot a bridge prefix?

#

@copper dew ?

copper dew
fringe socket
#

Can anyone help me in #1028563234552283156

#

@copper dew

#

?

sinful osprey
coral kindle
#

Hello, how can I make so after restart buttons work?

fringe socket
#

I don't think so.

#

The interaction probably cancels after a reboot.

still helm
spice oyster
#

What does the | mean here? Code from Pycord.

class Modal:
    def __init__(
        self,
        *children: InputText,
        title: str,
        custom_id: str | None = None,
        timeout: float | None = None,
    ) -> None:
        self.timeout: float | None = timeout

And why do the docs not show that Modals have a timeout parameter?

#

Can you pip freeze and share the results?

dull smelt
fringe socket
spice oyster
#

We need a new emote: :ReadTheIncompleteDocs:. ReadTheDocs

fringe socket
#

Hey @spice oyster want to help me in #1028603114690977863

#

?

spice oyster
#

Uninstall discord==2.0.0, discord.py==2.0.1, py-cord=2.0.1. After that, install py-cord=2.2.2. Restart your console and editor if needed.

#

I don't remember if they fixed it in the last minor version. Let me see. eddaniSherlock

#

I can't find that information. Just try if it works. If not, downgrade.

#

The important part is that you get rid of other libraries and reinstall Pycord, whatever version you want.

#

Try replacing it with original_response().

fringe socket
#

How do I make a command delete the message that invoked the command? @spice oyster ?

spice oyster
lost lodge
#

Hello
Why does the error still apears?:

class MyView(discord.ui.View):
    @discord.ui.select(
        custom_id="button_100",
        placeholder = "Choose a reason!",
        min_values = 1,
        max_values = 1,
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Support-Ticket",
                description="Create a support ticket!"
            ),
            discord.SelectOption(
                label="Application",
                description="Apply for our Team!"
            ),
            discord.SelectOption(
                label="Order",
                description="Create an order!"
            )
        ]
    )```
#
Ignoring exception in on_ready
Traceback (most recent call last):
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/Development/unviewed/discord/main/cogs/view/permanent.py", line 20, in on_ready
    self.bot.add_view(MyView())
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/client.py", line 1757, in add_view
    raise ValueError("View is not persistent. Items need to have a custom_id set and View must have no timeout")
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
spice oyster
#

Because you didn't fix it yet. hehehe

lost lodge
still helm
#

Items need to have a custom_id set and View must have no timeout

timeout not set to none and the custom_id is not visible in your code snippet

still helm
#

and the other?

lost lodge
#

here

still helm
#

oh sorry

lost lodge
#

haha

#

no problem

still helm
#

but timeout is still not there (i hope) 😄

lost lodge
#

yes

#

there is no timeout

still helm
#

no

#

you have to set it to none

lost lodge
#

and where?

still helm
#

timeout = None 😄

lost lodge
#

ah

spice oyster
lost lodge
#
@discord.ui.select(
        custom_id="button_100",
        timeout=None,
        placeholder = "Choose a reason!",
        min_values = 1,
        max_values = 1,
        options = []```
still helm
#

no

#

in your view

lost lodge
#

ah

#

i see

#

thx

spice oyster
#

Read the example in the link I shared.

lost lodge
#

i've already read it but im to stupid to read the whole example

#
member = bot.user
member.display_avatar.url```
#

or py member= ctx.author

fringe socket
pseudo glen
#

what veriosn

#

..

#

use py-cord 2.2.2 please

#

code:

#

error:

spice oyster
#

When unloading a cog, how to disable a Slash Command that's part of that cog? rooThink

#

Where do you get that interaction from?

#

And where do you pass that parameter to list()?

#

You called it interaction but the error says it's a context.

spice oyster
lost lodge
#

@cyan quail I have the error:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/Development/unviewed/discord/main/main.py", line 75, in on_ready
    status_task.start()
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 334, in start
    raise RuntimeError("Task is already launched and is not completed.")
RuntimeError: Task is already launched and is not completed.```
#
@bot.event
async def on_ready():
    print("-------------------")
    print(f"Logged in as {bot.user.name}")
    print("-------------------")
    print(f'Ping Âť {round(bot.latency*1000)} ms')
    print("-------------------")
    print(f"PyCord API version: {discord.__version__}")
    print("-------------------")
    print(f"Python version: {platform.python_version()}")
    print("-------------------")
    status_task.start()

@tasks.loop(minutes=1.0)
async def status_task():
    x = 1
    await bot.change_presence(status=discord.Status.idle, activity=discord.Activity(type=discord.ActivityType.watching, name=f"on {project_json} projects"))
    await asyncio.sleep(20)
    await bot.change_presence(status=discord.Status.idle, activity=discord.Activity(type=discord.ActivityType.watching, name=f"mention for help"))
    await asyncio.sleep(20)
    await bot.change_presence(status=discord.Status.idle, activity=discord.Activity(type=discord.ActivityType.watching, name=f"https://unviewed.xyz/"))
    await asyncio.sleep(20)```
cyan quail
#

you should check if the task is already running before starting it

lost lodge
cyan quail
#

you could just invert the logic and remove the else

lost lodge
#

?

#

ah

#
if not status_task.is_running():
    status_task.start()```
lost lodge
cyan quail
#

pretty much

lost lodge
#

thx

#

hmmm
when i stop my script i have now that error:

Traceback (most recent call last):
  File "/Development/unviewed/discord/main/main.py", line 127, in <module>
    bot.run(token)
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/client.py", line 702, in run
    future = asyncio.ensure_future(runner(), loop=loop)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py", line 615, in ensure_future
    return _ensure_future(coro_or_future, loop=loop)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py", line 636, in _ensure_future
    return loop.create_task(coro_or_future)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 436, in create_task
    self._check_closed()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
spice oyster
#

That's not enough but at this point I give up. Find where that interaction comes from and name it appropriately. I suppose doing interaction.interaction where you get the error will fix it but you would still have the wrong name. Good luck.

still helm
#

How to get the name from this:

[<User id=707919780467965956 name='C1trix' discriminator='5689' bot=False>]

ionic snow
#

Can you center a footer in the embed? ( I want the footer to always center itself according to the message )

full basin
#

So just access the attribute

still helm
#

or am i wrong?

rugged lantern
spice oyster
ionic snow
#

Tnx!

shrewd dome
#

iirc

rugged lantern
spice oyster
full basin
rugged lantern
#

it was a direct answer to their request, not that i would ever spam a footer with \u200b or whatever it is

ionic snow
#

Is it possible to get guild's voice client? I wanna check if the bot is currently playing audio in a custom check

still helm
full basin
#

Indexes..

#

Lists...

#

Basic python

still helm
# full basin Lists...

But ... this is not a list?

a list looks like this :
["apple", "banana", "cherry", "apple", "cherry"]

i have this
[<User id=707919780467965956 name='C1trix' discriminator='5689' bot=False>]

ionic snow
#

In the first my_list[0] = "apple"
In the second my_list[0] = <User id=707919780467965956 name='C1trix' discriminator='5689' bot=False>

#

in Python you can have a list which can contain all kinds of objects, from int to string

still helm
#

so it is my_list[0]["name"] to get to the username?

full basin
#

no

#

my_list[0].name

#

You're access an object attribute

ionic snow
full basin
#

But this ain't json

ionic snow
still helm
#

Ahhhh i´m sorry. i never see an object in a list before so this was very new to me

ionic snow
#

Did you learn about classes?

#

Did you learn how you create and handle classes in python? If not it's highly advised to do so before jumping to bots in python

still helm
#

the most things i´ve learned is by programming my python bot 😄

ionic snow
#

So jump on youtube and learn about the classes, conditions, async functions, variables, comprehansions, dictionaries, etc... It'll help you a lot

still helm
#

i did this for 3 years now and the most time it works good. but i know there are a lot of things to learn.

but there is work, family, hobby and so on 😄

ionic snow
#

Still, highly advised to at least learn the beginning of python just so you know the fundamentals of it

still helm
#

i know i know 😦

ionic snow
#

👍

still helm
#

But thanks for the help, that was very educational for me

ionic snow
still helm
#

thank you 🙂

spice oyster
#

Do you prefer using send_response() and send_followup() based on the situation (1) or using respond() all the time (2)?

errant craneBOT
#

discord/commands/context.py lines 269 to 288

async def respond(self, *args, **kwargs) -> Interaction | WebhookMessage:
    """|coro|

    Sends either a response or a message using the followup webhook determined by whether the interaction
    has been responded to or not.

    Returns
    -------
    Union[:class:`​discord.Interaction`​, :class:`​discord.WebhookMessage`​]:
        The response, its type depending on whether it's an interaction response or a followup.
    """
    try:
        if not self.interaction.response.is_done():
            return await self.interaction.response.send_message(
                *args, **kwargs
            )  # self.response
        else:
            return await self.followup.send(*args, **kwargs)  # self.send_followup
    except discord.errors.InteractionResponded:
        return await self.followup.send(*args, **kwargs)```
cyan quail
#

i guess one reason to not use respond is that it might be ambiguous as to whether you got interaction or webhookmessage back, which could lead to confusion later on in your code

#

but if you know you've responded in your code before then it's guaranteed to be WebhookMessage every subsequent time

spice oyster
#

That's exactly what I was thinking about. I saw that in the docs and was wondering if there was something else I didn't consider.

cold hamlet
#

What's the max length of an autocomplete response?

silver moat
cold hamlet
#

i meant as in the values

#

Like what's the maximum length of a string my autocomplete function can return

silver moat
#

the same as every option: 32

cold hamlet
#

oh okay thanks

cyan quail
#

pretty sure it's 100

silver moat
#

they're talking about the name field, no?

cyan quail
#

they're saying response so i was assuming the value

silver moat
cyan quail
#

right, the option name itself is max 32 but all choice names/values are max 100

harsh dust
#

every time I use view.on_timeout to remove a view at the end of the timeout on a message that has an attachment, the attachment gets deleted from discords servers and I have no clue why

#

which is forcing me to ditch view.on_timeout and keep the view there

silver moat
#

Maybe a Discord bug?

harsh dust
#

but other bots have this feature and they have no problem

#

To me this seems like a py-cord issue but i wouldnt know

#

and this only happened after i transferred to slash commands

silver moat
#

show code ty

harsh dust
#
with save_image_data("graph", rendered) as file:
    msg = await respond(ctx, file=file, view=view)

async def timeout():
    try:
        await msg.edit(view=None)
    except:
        pass

# view.on_timeout = timeout

One example of many other commands that have this

tender seal
#

how do I get the user that used a slash command?

young bone
#

ctx.author

woeful spindle
#

fixed

regal sigil
#

how to retrieve their pfp using ctx

regal sigil
#

Ye that hasn't been working

#

And docs is very unsuable

rugged lantern
#

it'd help if u could read

fervent cradle
#

is it possible to add a drop down selection menu within a modal?

young bone
#

only text

fervent cradle
#

Damn ok, thanks

young bone
#

discord ist not really supporting it

silver moat
rare ice
rare ice
#

bruh why does my client scroll up

proud mason
#

if i defer a response from a button interaction, is it necessary that i send a followup message?

i need to edit the original message, and works without deferring and using interaction.responsee.edit_message. But i have some i/o and db stuff going on so i thought it would be a good idea to defer it. But docs say this- (image)

according to that sentence, i have to send a followup msg for InteractionResponseType.deferred_message_update and not for deferred_channel_message

currently im deferring and then using interaction.edit_original_message

young bone
gleaming falcon
silver moat
#

yeah. but they will be implementing them in modals soon after that

gleaming falcon
#

For Discord-defined values of "soon" after 😬

#

At least it's on the list, that's all I can expect at this point.

silver moat
#

yeah ig

silver moat
#

try it and see

proud mason
# silver moat yes?

it works. my questiton is will say application did not respond or smth after 15 mins

silver moat
#

probably not

proud mason
#

hmm

#

kden

fleet parcel
#

Is it possible to send variables to a class from a commands? like a drop down menu for example. I am trying to make a select menu that has options for multiple things and those things change per server. Basically for loop adding select options to a list and then i want to send that list to a select class.

lost lodge
#

help pls

limber bison
#

How would i get the content of an embed field with message id? i found the thread talking about getting the description name/value but cant figure out fields

#

nvm. fields are also a list embeds[0].fields[0].value

lost lodge
#

How can I delete the message in which the view was sent when clicking on the view?

spice oyster
ionic snow
#

How can I give a description for values in slash commands? Talking about the values people type before executing the command

spice oyster
#

Do you mean this?

ionic snow
#

Yep

ionic snow
copper dew
# ionic snow Exactly that
from discord.commands import Option

async def command(self, ctx, word: Option(str, "This is the description for that")):
    ...
cold hamlet
#

I’ve added a discord.SlashCommandGroup to my cog, but it isn’t being added to the commands list? It doesn’t show up in discord nor the internal command list?

#

Adding it manually in __init__ via bot.add_app_command makes it throw an error too (TypeError: Parameter limit does not match input type of ctx., my argument order is correct)

full basin
#

?tag paste

obtuse juncoBOT
cold hamlet
#

Yeah let me grab an extract, its massive

#

Mystbin is fully not saving one sec

cold hamlet
#

It’s loaded just before bot.run via bot.load_extension()

#

It loads successfully but the commands don’t show up

cold hamlet
#

FFR I overwrote the on_connect function and forgot to call super()

#

So no commands were being created

fair crescent
#

any reason that this wont work in a cog?
the cog is loaded corretly i have a command in there that works

 from discord.ext import tasks, commands ,bridge

class mycog(commands.Cog):

    def __init__(self, bot):
        self.bot = bot    

    @commands.Cog.listener()
    async def on_member_join(self, member):
        print(f"hello there {member.name}")

Solved: intents.member = True 🙂

regal sigil
#

Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'display_avatar'

#

I get this when using ctx.author.display_avatar.url on slash command

silver moat
#

send code.

#

thanks

livid salmon
#

I'm trying to make a slash command with a variable containing a selectable list of players in a database. Whenever the list updates though the list of player names doesn't change, even though choices= is set to the command to get the list of player names from the database. Is there any way to do this so it does update?

# spreadsheet.
range_ = f"{ratings_sheet}!A:A"

@bot.slash_command(name="recent_scores", description="Gets the 20 most recent "
                                                     "scores for a specific "
                                                     "player.")
# choices= gets all player names in the database, sorted in alphabetical order.
# The player names are embedded in a one-element long list, so we just need the
# first element to get the list of players.
async def pullscores(ctx, player_name:
                     discord.Option(description="Enter the player name",
                                    choices=sorted([name[0] for name in get_values_from_sheet(DATABASE_SHEET_ID, range_)]))):

^ code for reference

frozen salmon
#
class Background(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(
        description = 'Hello!'
    )
    async def hello(self, ctx):
        await ctx.send('Hello!')

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

    @commands.slash_command(
        description = 'Add a bot to the database!'
    )
    async def addbot(self, ctx):
        if ctx.author.id == bot_owner:
            class Project(Modal):
                def __init__(self, *args, **kwargs) -> None:
                    super().__init__(*args, **kwargs)

                    self.add_item(InputText(label='Discord Bot Token', custom_id='token', style=discord.InputTextStyle.long, placeholder='Insert Token.'))
                    self.add_item(InputText(label='Discord Bot ID / Application ID', custom_id='id', style=discord.InputTextStyle.long, placeholder='Insert ID.'))
                    self.add_item(InputText(label='Linked Guild', custom_id='guild', style=discord.InputTextStyle.long, placeholder='Provide your Server ID.'))


                    async def callback(self_, interaction):
                        database.addbot(self.children[0], self.children['guild'], self.children['id'], False)
                        try:
                            await interaction.send()
                        except:
                            pass
                        await database.disconnect_all()

            await ctx.response.send_modal(Project(title="Add bot", timeout=600, custom_id="addbot"))
        else:
            await ctx.send('You are not allowed to use this command.')
#

any idea why it doesnt work?

silver moat
#

?tag idw

obtuse juncoBOT
#

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

silver moat
frozen salmon
#

No error, I tried to make an modal but it just says something went wrong

silver moat
#

you don't need self. My guess is that interaction is None

#

nvm

frozen salmon
#

oh

silver moat
#

interaction.send doesn't exist.

frozen salmon
silver moat
#

.docslink interaction.response.send_response

silver moat
#

.docslink discord.Interaction.response

silver moat
#

.docslink discord.Interaction.response

silver moat
#

.docslink discord.InteractionResponse.send_response

frozen salmon
#

Whats the difference?

silver moat
livid salmon
silver moat
livid salmon
#

Just replacing choices with it makes a menu pop up like choices does, but it seems to time out with no results, even if I type something in

errant craneBOT
#

Here's the slash autocomplete example.

silver moat
#

remove the try-except in the Modal callback and see what errors are raised.

frozen salmon
#

Yeah, Im doing that now

silver moat
#

what is your current code?

frozen salmon
#

    @commands.slash_command(
        description = 'Add a bot to the database!'
    )
    async def addbot(self, ctx):
        if ctx.author.id == bot_owner:
            class Project(Modal):
                def __init__(self, *args, **kwargs) -> None:
                    super().__init__(*args, **kwargs)

                    self.add_item(InputText(label='Discord Bot Token', custom_id='token', style=discord.InputTextStyle.long, placeholder='Insert Token.'))
                    self.add_item(InputText(label='Discord Bot ID / Application ID', custom_id='id', style=discord.InputTextStyle.long, placeholder='Insert ID.'))
                    self.add_item(InputText(label='Linked Guild', custom_id='guild', style=discord.InputTextStyle.long, placeholder='Provide your Server ID.'))


                    async def callback(self_, interaction):
                        database.addbot(self.children[0], self.children['guild'], self.children['id'], False)
                        await database.disconnect_all()

            await ctx.response.send_modal(Project(title="Add bot", timeout=600, custom_id="addbot"))
        else:
            await ctx.send('You are not allowed to use this command.')
silver moat
livid salmon
fervent cradle
#

hey quick question, is there an event that triggers when someone boosts the server?

fervent cradle
#

ty

frozen salmon
silver moat
#

did you add a response?

frozen salmon
#

yes

silver moat
#

what type of response was it?

frozen salmon
#

a message, i sent hey

#

await interaction.response.send_message('hey')

young bone
# silver moat nope.

Can you not check if a user boost the server if the user get the Server booster role?

frozen salmon
silver moat
young bone
frozen salmon
silver moat
#

so the user sees "Something went wrong. Try again"?

frozen salmon
#

yes

silver moat
#

no errors?

frozen salmon
#

no

silver moat
#

I'm wondering if the error was caught in on_application_command_error and not raised

marble nova
#

are emojis in the responses messed up? I do await interaction.response.send_message(f"{emoji}") and it just shows :emojiname: but when I do await interaction.message.reply(f"{emoji}" it works fine.

silver moat
frozen salmon
#

Squid, you find anything wrong?

round rivet
#

iirc

silver moat
marble nova
#

the bot has admin tho

round rivet
#

since july

silver moat
marble nova
#

yep

lost lodge
#

Hello how can i get a emoji and add a reaction with it

spice oyster
glossy socket
#

so i can instantiate the bot from another file

lost lodge
ionic snow
#

Is there a way to make an argument have a strict format? ( like hhmmss and the user won't be able to execute the command if it's not that same format )

spice oyster
ionic snow
glossy socket
#

how can i add slash commands to the bot class itself like this?

from discord import Option, slash_command

class Bot(discord.Bot):
  
  @slash_command
  def slash(self):
    pass

the slash commands dont work in the server this way

spice oyster
#

@ionic snow I understood. Try with autocomplete or split the field in 3 parts (hours, minutes, seconds).

lost lodge
spice oyster
ionic snow
#

Anybody knows if I can change the red message to a custom one in case the value gets an error?

lost lodge
ionic snow
#

Just search it

ionic snow
lost lodge
ionic snow
#

Well because it's a custom emoji, I don't think you can put custom emojis

lost lodge
#

You can

glossy socket
#

i want to run the bot from another file

ionic snow
#

You mean cogs?

#

?paste

glossy socket
#

idk how its called but i want to have a main.py file where i can import the class of the bot

#

and call bot.run from there

ionic snow
errant craneBOT
glossy socket
#

okay thanks! im going to check it out

ionic snow
#

In the bot itself you can do bot.loadextension(name="file name or folder containing lots of files") which will load the files

#

Type cogs in the documentation it will help you more than me

glossy socket
#

but id still need to instantiate the bot in the same file?

#

with the bot.run()?

rugged lantern
#

why not just have it all in one file

glossy socket
#

because i want to instantiate it from another class, since i need to inject classes and other stuff from that class in the discord bot class

rugged lantern
#

you can just make a bot class object and make it inherit or use whatever you want inside of itself

glossy socket
#

tho id rather keep the bot class and my main class split

pseudo glen
rugged lantern
# glossy socket tho id rather keep the bot class and my main class split

but if you really want to i suppose you could do this (for commands.Bot)

class Main(commands.Bot):
    def __init__(self, command_prefix, intents):
        commands.Bot.__init__(self, command_prefix=command_prefix, intents=intents)
  
    ...
``` then in the other file you want to run it from you do:
```py
from name import Main
intents = discord.Intents.default()
...
main = Main(command_prefix="whatever", intents=intents)
main.run(token)
glossy socket
rugged lantern
#

it's the same concept

glossy socket
#
    def start_bot(self):
        self.bot.add_cog(BoostCommands(self.bot, self))
        self.bot.run("")
    bot.add_command(command)
AttributeError: 'MainBot' object has no attribute 'add_command'. Did you mean: 'all_commands'?

what am i doing wrong?

tame rose
#

Is there a better way to do this?

@poll.command(description = 'Create a reaction poll')
@discord.option('question', required = True)
@discord.option('choice1', required = True)
@discord.option('choice2', required = True)
@discord.option('choice3', required = False)
@discord.option('choice4', required = False)
@discord.option('choice5', required = False)
@discord.option('choice6', required = False)
@discord.option('choice7', required = False)
@discord.option('choice8', required = False)
@discord.option('choice9', required = False)
@discord.option('choice10', required = False)

async def normal(ctx, question, choice1, choice2, choice3, choice4, choice5, choice6, choice7, choice8, choice9, choice10):
fervent cradle
#

why do i get this error, when delete_message_seconds is actually a parameter in member.ban(), my code is below

@commands.slash_command(description='Ban a user easily')
    async def ban(self, ctx, user: Option(discord.Member, 'The user you want to ban', required=True), reason: Option(str, 'The reason for banning the user', required=False), history: Option(str, 'Message history of user to delete', choices=['Delete none', 'Last 24 hours', 'Last 7 days'], required=False)):
        if not reason:
            b_reason = f'Initiated by {ctx.author} | ID: {ctx.author.id}'
            b_resp = discord.Embed(description=f'Successfully banned `{user}`.', colour=discord.Colour.green())
        else:
            b_reason = f'{reason} | Initiated by {ctx.author} | ID: {ctx.author.id}'
            b_resp = discord.Embed(description=f'Successfully banned `{user}` for reason `{b_reason}`.', colour=discord.Colour.red())
        
        if history == 'Last 24 hours':
            msg_del = 86400
        elif history == 'Last 7 days':
            msg_del = 604800
        else:
            msg_del = 0
        
        await user.ban(delete_message_seconds=msg_del, reason=b_reason)
        await ctx.respond(b_resp)
spice oyster
rugged lantern
spice oyster
#

Where you declare the command itself, below the decorator, but I think you still have to list them one by one (eg. choice7 = choices[6]).

tame rose
#

Wait. Is this what you meant?

async def frame(itrc, *choices):
spice oyster
#

You can try that too. I'm not sure if it works.

tame rose
young bone
glossy socket
tame rose
tame rose
#

That looks like an on_message() event, but my bot is unverified. Also I got default values and autocomplete so I was using slash commands

regal sigil
# silver moat send code.

pico.set_thumbnail(url=discord.User.display_avatar.url) - basicly display_avatar works but shows memory instead of returning the url but .url just says its not apart of User

#

Application Command raised an exception: AttributeError: 'property' object has no attribute 'url'

#

bruh

#

i finnaly got it my dumbass

#

ctx.author.display_avatar - been a while since ive used discord.py since 2021 but goddamn i got alot to learn huh

tame rose
#

It's regarded as the default value

spice oyster
drifting birch
#

when using discord.ChannelType as input_type for discord.Option, it returns an int. How can I get a name instead, or how do I convert that int into the correct type name?

cyan quail
#

...damnit that still isn't documented

#

also ChannelType returns an int because it's an Enum that mirrors the int that discord uses for channel types

errant craneBOT
#

discord/enums.py lines 212 to 227

class ChannelType(Enum):
    text = 0
    private = 1
    voice = 2
    group = 3
    category = 4
    news = 5
    news_thread = 10
    public_thread = 11
    private_thread = 12
    stage_voice = 13
    directory = 14
    forum = 15

    def __str__(self):
        return self.name```
glossy socket
fervent cradle
drifting birch
# drifting birch when using `discord.ChannelType` as `input_type` for `discord.Option`, it return...

To clarify, what I have is a command to create a channel of the type provided by the user.
Right now, what I'm doing is, I'm getting discord.ChannelType with discord.Option in the command and then I want to do an eval on f"ctx.guild.create_{type}_channel" to create the channel (I really don't want to use eval, but I can't think of any other way). However the Option actually returns an int, so obviously I can't eval it like that.

cyan quail
#

but if you make commands normally then you never have to run that function anyway

cyan quail
#

also i wouldn't eval

glossy socket
#

and the function add_cog is giving that exception

cyan quail
cyan quail
cyan quail
drifting birch
# cyan quail also i wouldn't eval

I know, but I don't think there is a function to do that... I guess I could do an if statement (or equivalent) for each of the types, but then if a new channel type is created, then I have to change the code (also, if statements aren't great either)

cyan quail
#

i just showed you one

#

getattr is used in tons of places in the lib

drifting birch
#

oh, sorry. Didn't see your message

glossy socket
cyan quail
#

all good

drifting birch
cyan quail
#

isee

drifting birch
#

It works, thank you!

glossy socket
#

do i need to do something else then creating a Cog class with slash commands inside that, and then add that class with add_cog, but the slash commands still dont show up

cyan quail
#

make sure the cog is loaded before starting the bot

glossy socket
cyan quail
#

can you show the cog file?

void mirage
#

Can someone help me?

TypeError: Client.start() got an unexpected keyword argument 'bot'
I got this error

glossy socket
#

just needed to wait for like 10 min orso

cyan quail
#

ah nice

coral kindle
#
channel = discord.utils.get(guild.channels, name='(📁)bot-requests')
        await channel.send('Test')```
#

???

silver moat
#

well? you haven't defined guild

glossy socket
#

is it somehow possible to receive a txt file with slashcommands?

silver moat
#

yes

livid salmon
#
    filename = "table.png"
    font = ImageFont.truetype("C:/Windows/Fonts/consola.ttf", 20)
    # Getting the size of the table to create the size of the blank image
    box = font.getsize_multiline(str(table))
    # Set the background color. Add 10 to the table width and 32 to the height
    # for margins
    im = Image.new("RGB", (box[0] + 10, box[1] + 32), "#2f3137")
    # Draw the background
    draw = ImageDraw.Draw(im)
    # Insert the text
    draw.text((5, 15), str(table), font=font, fill="#bbbcbf")
    output = io.BytesIO()
    im.save(output, format="PNG")
    return output


@bot.slash_command(name="rankings")
async def get_rankings(ctx):
    """Get the rankings of the top 10 players from the leaderboard."""
    rankings = create_rankings()
    top_10 = rankings[:10]
    field_names = ["Rank", "Player", "Rating"]
    title = "SERVER RANKINGS"
    logging.debug(f"rankings = {rankings}")
    logging.debug(f"top_10 = {top_10}")
    table = create_image_table(title, field_names, top_10)
    with open(table, "rb") as fp:
        file_ = discord.File(fp, "table.png")
        await ctx.respond(file=file_)
        table.close()```
I'm trying to pass my bot an image file created with Pillow as a binary stream so I don't have to read/write from a hard drive. Does anyone know why this isn't working?
errant craneBOT
#

examples/app_commands/slash_options.py lines 51 to 67

@bot.slash_command(name="attach_file")
@option(
    "attachment",
    discord.Attachment,
    description="A file to attach to the message",
    required=False,  # The default value will be None if the user doesn't provide a file.
)
async def say(
    ctx: discord.ApplicationContext,
    attachment: discord.Attachment,
):
    """This demonstrates how to attach a file with a slash command."""
    if attachment:
        file = await attachment.to_file()
        await ctx.respond("Here's your file!", file=file)
    else:
        await ctx.respond("You didn't give me a file to reply with! :sob:")```
glossy socket
#

ahh thanks!

livid salmon
cyan quail
#

if i had to guess, you should probably await ctx.defer() before generating the image

livid salmon
#

Right now the bot simply times out when the command is input and the console gives this error

cyan quail
#

table is already Bytes so you don't need to open it

livid salmon
#
    filename = "table.png"
    font = ImageFont.truetype("C:/Windows/Fonts/consola.ttf", 20)
    # Getting the size of the table to create the size of the blank image
    box = font.getsize_multiline(str(table))
    # Set the background color. Add 10 to the table width and 32 to the height
    # for margins
    im = Image.new("RGB", (box[0] + 10, box[1] + 32), "#2f3137")
    # Draw the background
    draw = ImageDraw.Draw(im)
    # Insert the text
    draw.text((5, 15), str(table), font=font, fill="#bbbcbf")
    output = io.BytesIO()
    im.save(output, format="PNG")
    output.seek(0)
    return output


@bot.slash_command(name="rankings")
async def get_rankings(ctx):
    """Get the rankings of the top 10 players from the leaderboard."""
    rankings = create_rankings()
    top_10 = rankings[:10]
    field_names = ["Rank", "Player", "Rating"]
    title = "SERVER RANKINGS"
    logging.debug(f"rankings = {rankings}")
    logging.debug(f"top_10 = {top_10}")
    table = create_image_table(title, field_names, top_10)
    file_ = discord.File(fp=table, filename="table.png")
    await ctx.respond(file=file_)
    table.close()

All right I managed to get it working. Had to do one more step with .seek(0) on the output to get the file to actually send properly, because Pillow puts the pointer at the end of the file when it saves for some reason. Thanks!

plush meadow
#

Hopefully someone can help me out, because I am absolutely burning through my API credits through trial and error

#
for generation in generations:
        url = generation['generation']['image_path']
        image = requests.get(url).content
        message.channel.send(file=discord.File(image))

shouldn't this work? I am trying to send the API response as an actual image attachment

proud pagoda
plush meadow
#

aw for real

#

that kinda stinks, I didn't know that

#

I thought you could save the binary in a variable and attach that, no?

proud pagoda
#

I don't believe discord.File supports that

plush meadow
#

son of a gun

#

that complicates things for me tremendously, I have quite the small server

#

i'm gonna need to clean house every couple days

proud pagoda
#

Try doing something like this:

with open ("filename.png", "wb") as f:
  f.write(image)
message.channel.send(file=discord.File("filename.png"))
os.remove("filename.png")
proud pagoda
plush meadow
#

you're right actually

#

it gets hosted on discord CDN thereafter, correct?

proud pagoda
#

Yep

plush meadow
#

do you know off the top of your head how long discord holds them for?

proud pagoda
#

Ik its at least two months

#

Since for me, I usually use embeds, so I need an img url, not a file

#

So I send the file to a dump channel and Discord adds it to tehir cdn, so I pull the url from that

#

And I don't delete the stuff from the dump channel, and I can see stuff that was dumped there over two months ago

plush meadow
#

that's really smart

proud pagoda
#

Thanks

plush meadow
#

i'll give it a go myself

#

thanks for your help

proud pagoda
#

You're welcome, happy to help

plush meadow
#

that's what I was thinking, but no cigar

cyan quail
#

discord.File's first arg is either a filepath or binary

#

if you use binary, then you should also specify filename="..."

#

are you sure the content you got back was the binary data?

plush meadow
#

oh, really? perhaps that's why it was sending nothing

#

yes because if I instead write the image to the disk, i get it no problem

cyan quail
#

isee

plush meadow
#

using wb

#

let me try that

cyan quail
#

everything there is painful, but uhh you missed a range

#

and your variable name shouldn't be the same as your function name

#

also typo in first if

loud pier
#

I have a slash command /lottery that send a random number with ctx.interaction.response.send_message. Is there a way afterward to find which user used the command with the message id?

cyan quail
#

that's not what i meant

#

read all your lines with respond and spot the difference

#

cmon man this is just reading

#

you typed emed instead of embed

#

well

#

look at all your if statements

spice oyster
#

elif is a thing.

#

The first keyword is always if, the rest is elif unless you need something more complex, and then you usually end with else.

plush meadow
# cyan quail if you use binary, then you should also specify `filename="..."`
message.channel.send(file=discord.File(image), filename='image.webp')
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/file.py", line 99, in __init__
    self.fp = open(fp, "rb")
ValueError: embedded null byte

this same error persists, it's driving me nuts. maybe i am actually not receiving the binary data?

cyan quail
#

try use it with BytesIO?

#

wait

#

it shouldn't be file=

#

it's just first positional

plush meadow
#

dammit

#

one sec

#

same thing, this is nuts

cyan quail
#

BytesIO it is then

#

import BytesIO from io and then wrap image with BytesIO(...)

plush meadow
#

this is crazy

#

this is actually crazy, i am going to faint

#

i never awaited it

cyan quail
#

oh

#

that too

plush meadow
#

it was never even getting the data

cold hamlet
#

What permission does Guild.fetch_auto_moderation_rules need?

#

its not manage server since I check for that and it gives me Forbidden

#
        if guild.me.guild_permissions.manage_guild:
            invites = len(await guild.invites())
            automod_rules = len(await guild.fetch_auto_moderation_rules())
        else:
            invites = "Missing 'manage server' permission."
            automod_rules = "Missing 'manage server' permission."

Throws

Traceback (most recent call last):
  File "/home/pi/.local/pipx/venvs/spanner/lib/python3.10/site-packages/discord/commands/core.py", line 127, in wrapped
    ret = await coro(arg)
  File "/home/pi/.local/pipx/venvs/spanner/lib/python3.10/site-packages/discord/commands/core.py", line 907, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/home/pi/.local/pipx/venvs/spanner/lib/python3.10/site-packages/src/cogs/official/info.py", line 990, in server_info
    embed = await self.get_server_data(ctx)
  File "/home/pi/.local/pipx/venvs/spanner/lib/python3.10/site-packages/src/cogs/official/info.py", line 220, in get_server_data
    automod_rules = len(await guild.fetch_auto_moderation_rules())
  File "/home/pi/.local/pipx/venvs/spanner/lib/python3.10/site-packages/discord/guild.py", line 3604, in fetch_auto_moderation_rules
    data = await self._state.http.get_auto_moderation_rules(self.id)
  File "/home/pi/.local/pipx/venvs/spanner/lib/python3.10/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
cold hamlet
#

I'll just chuck it in a try/except

#

typical discord reliability and consistency kekw

plush meadow
#

allegedly, although i vividly remember using filename before

cyan quail
#

...? that's definitely not correct

plush meadow
#
TypeError: Messageable.send() got an unexpected keyword argument 'filename'
cyan quail
#

nono

#

inside discord.File

plush meadow
#

this is what happens when you let stupid people code

#

my bad

sinful osprey
#

Is there a good way to check whether an emoji is valid or not? I was thinking of adding a reaction to the interaction message, but didn't find a method for it in the docs.

cyan quail
#

if it's unicode, maybe try converting it to PartialEmoji

sinful osprey
#

Already tried that, you can pass any string into that and it will be okay with it, even "asdf" for example

cyan quail
#

idk then

#

emojis suck to deal with

sinful osprey
#

Actually, I guess I could send a dummy view as a response to validate the emoji

#

Through the value parameter I believe

errant craneBOT
#

examples/modal_dialogs.py line 23

value="Longer Value\nSuper Long Value",```
sinful osprey
#

What exactly is modal

#

Why pass value into the modal if your only constuctor argument is title

#

You have to pass the value into the InputText component

cyan quail
#

check modal.children

#

which is a list of items

#

and when you select from there you can check item.value

sinful osprey
#

Inside the callback, but you're not even saving the value to the modal, it's just passed to the parent __init__ as part of kwargs. You have to add value as a parameter to your __init__ (similar to title)

proud mason
#

do we need to specify both min_value and max_value for int options rooThink

proud mason
#

ty

sinful osprey
#

I'd suggest you to check some basic python tutorials first. But what you want is basically something along the lines of the following ```py
class SpellingBeeModal(discord.Modal):
def init(self, word, info, title="a", *args, **kwargs) -> None:
super().init(title, *args, **kwargs)
self.word = word
self.info = info
self.add_item(InputText(label="a", placeholder="a"))

async def callback(self, interaction: discord.Interaction):
    print(modal.children)
    print(self.word)
    print(self.info)

wherever you send the modal

await interaction.response.send_modal(SpellingBeeModal(word=self.word, info=self.info)))

sinful osprey
silver moat
#

mention via reply

fervent cradle
silver moat
#

message.reply() or Context.reply()

#

view.message.reply

#

well, interaction.message is your response message. so that's useless.

#

well, you need a message object.

cyan quail
#

interaction.message is the message that the interaction came from, which CAN be the response but not always

frozen salmon
#

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

    @commands.slash_command(
        description = 'Add a bot to the database!'
    )
    async def addbot(self, ctx):
        if ctx.author.id == bot_owner:
            class Project(Modal):
                def __init__(self, *args, **kwargs) -> None:
                    super().__init__(*args, **kwargs)

                    self.add_item(InputText(label='Discord Bot Token', custom_id='token', style=discord.InputTextStyle.long, placeholder='Insert Token.'))
                    self.add_item(InputText(label='Discord Bot ID / Application ID', custom_id='id', style=discord.InputTextStyle.long, placeholder='Insert ID.'))
                    self.add_item(InputText(label='Linked Guild', custom_id='guild', style=discord.InputTextStyle.long, placeholder='Provide your Server ID.'))


                    async def callback(self_, interaction):
                        database.addbot(self.children[0], self.children['guild'], self.children['id'], False)
                        await database.disconnect_all()
                        await interaction.response.send_message('hey')

            await ctx.response.send_modal(Project(title="Add bot", timeout=600, custom_id="addbot"))
        else:
            await ctx.send('You are not allowed to use this command.')

def setup(bot):
#

I have an problemm with modals. The modal loads when you attemp to submit it, it says "Something went Wrong Try again" no error what so ever.

cyan quail
#

and self.children is a list, so something like self.children['guild'] will error

frozen salmon
#

So what, are custom_ids for?

cyan quail
#

they're just general use for sending data with the interaction

#

but individual InputText objects don't have a custom_id

#

if you want to get a child by custom_id use discord.utils.get, but you could just do children[1] and children[2]

frozen salmon
#

Should i remove self.children, and use children?

cyan quail
#

i was using children as an example

frozen salmon
#

ah

#
  File "/home/runner/rewrite/cogs/background.py", line 40, in callback
    database.addbot(self.children[0], self.children[1], self.children[2], False)
AttributeError: 'Owner' object has no attribute 'children'
cyan quail
#

oh i guess self_ in your case

frozen salmon
#

Thanks!, im more happy to see another error! At least i'm no longer stuck on this

obtuse patrol
#

i've installed pycord in py, but it wont work in pycharm

young bone
obtuse patrol
#

probably

young bone
#

also show the pip list

obtuse patrol
#

pip list?

young bone
#

type it in the terminal

#

?tag install

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

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

2b. Update py-cord
python pip install -U py-cord

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

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

obtuse patrol
#

shows its installed

#

but doesnt work

young bone
#

pycord

young bone
#

uninstall pycord

obtuse patrol
#

it worked, thanks

young bone
obtuse patrol
#

of?

young bone
obtuse patrol
#

i have py-cord 2.2.2

simple canopy
#

you're good to code ^

plush meadow
#

any way to ignore a guild in a @client.event?

#

more specifically, on_presence_update()

simple canopy
#

if guild id == bad guild id
return

plush meadow
#

i'm not certain that on_presence_update() holds the guild ID

#

i guess that's what the docs are for

simple canopy
#

before and after are discord.Member objects

#

work around that

plush meadow
#

oh it's just a member object facepalm

#

embarrassing, my bad

#

would've been faster to just read than to even ask a question

simple canopy
#

that's why people are trying to figure things out themselves before asking something

#

because its easier and faster, AND you will learn/understand more

plush meadow
#

when I looked it up, someone on stack overflow said to kick the bot from the guild so I just came here and skipped the docs because i'm braindead

simple canopy
#

stackoverflow moment

#

💀

frozen salmon
simple canopy
#

i'm pretty sure its a list of objects

#

if we're speaking about modal

#

i guess you are not, bruh

frozen salmon
simple canopy
#

👍🏻

frozen salmon
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/runner/rewrite/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/rewrite/venv/lib/python3.8/site-packages/discord/bot.py", line 1054, in on_connect
    await self.sync_commands()
  File "/home/runner/rewrite/venv/lib/python3.8/site-packages/discord/bot.py", line 657, in sync_commands
    app_cmds = await self.register_commands(
  File "/home/runner/rewrite/venv/lib/python3.8/site-packages/discord/bot.py", line 485, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(self._bot.user.id, guild_id)
  File "/home/runner/rewrite/venv/lib/python3.8/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
``` randomly getting this error, I have indeed invited the bot to the correct server, with applications commands
silver moat
silver moat
#

do you have a guild_ids parameter on an application command decorator?

frozen salmon
#

no

silver moat
#

or a debug_guilds parameter on the bot constructor?

frozen salmon
#

@silver moat i may or may not know the problem.

silver moat
#

what do you think it's?

frozen salmon
#

I should probably say whats going on

tawdry cedar
#

Feel like i'm being dumb here. How can I link "options.1" to a specific item.

In options.1: Required options must be placed before non-required options

silver moat
#

send code?

silver moat
tawdry cedar
silver moat
frozen salmon
#

So, I am making a code that will run my personal bots. Right now its just /addbot token, it adds the bot, to my database running it with every other bot. The code turns the bot on, but only the prefix commands seem to load

tawdry cedar
# silver moat you

alright give me a sec, need to find a place to put this. Its long and ugly af

silver moat
#

thread

frozen salmon
#

ill make a post

silver moat
#

I think

#

Please give full traceback.

tawdry cedar
# silver moat Please give full traceback.
Oct 10 06:56:38 PM  Ignoring exception in on_connect
Oct 10 06:56:38 PM  Traceback (most recent call last):
Oct 10 06:56:38 PM    File "/opt/render/project/src/.venv/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
Oct 10 06:56:38 PM      await coro(*args, **kwargs)
Oct 10 06:56:38 PM    File "/opt/render/project/src/.venv/lib/python3.9/site-packages/discord/bot.py", line 1138, in on_connect
Oct 10 06:56:38 PM      await self.sync_commands()
Oct 10 06:56:38 PM    File "/opt/render/project/src/.venv/lib/python3.9/site-packages/discord/bot.py", line 711, in sync_commands
Oct 10 06:56:38 PM      app_cmds = await self.register_commands(
Oct 10 06:56:38 PM    File "/opt/render/project/src/.venv/lib/python3.9/site-packages/discord/bot.py", line 581, in register_commands
Oct 10 06:56:38 PM      registered = await register("bulk", data, _log=False)
Oct 10 06:56:38 PM    File "/opt/render/project/src/.venv/lib/python3.9/site-packages/discord/http.py", line 359, in request
Oct 10 06:56:38 PM      raise HTTPException(response, data)
Oct 10 06:56:38 PM  discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
Oct 10 06:56:38 PM  In options.1: Required options must be placed before non-required options```
#

I will note I did upgrade from an older 2.x version of pycharm before this (at the same time I made a code change to add the quote stuff)

silver moat
tawdry cedar
#

pycord not pycharm*

#

interesting I'll give it a try. Must be a syntax change then as I didn't touch that part

#

@silver moat that fixed it thanks. I must have missed it on the change log

tawdry cedar
#

Are you able to use items like <@id> in discord embeds?

full basin
#

Yes?

lyric parrot
#

hey, i just had the same problem, but adding delete_message_seconds=0 results in this error

TypeError: Member.ban() got an unexpected keyword argument 'delete_message_seconds'
tawdry cedar
silver moat
#

as markdown just doesn't exist in those fields.

tawdry cedar
errant craneBOT
#
Toolkit

A bot built to help you manage your Discord server as easily as possible.
Use the menu below to view commands.

Server Count

73

User Count

21407

Ping

108.34ms

wary rover
#

?tag install

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

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

2b. Update py-cord
python pip install -U py-cord

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

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

wheat stirrup
#

hey, i am trying to declare a class to store some variables in an object for a poker bot. I don't exactly understand what is causing this error or how to correct it, could someone point me in the right direction, much appreciated!

copper dew
# wheat stirrup hey, i am trying to declare a class to store some variables in an object for a p...

the error is pretty simple actually. if you look at the line with the bot.add_cog() method, you are passing in the player class with the default constructor arg of bot. and i'm assuming you are trying to make a cog out of it. here's an example for how it would look like:

from discord.ext import commands
from discord.commands import slash_command

# in order to create a cog, you need to subclass the `commands.Cog` class first
class Player(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    ...
    
def setup(bot):
    bot.add_cog(Player(bot))
wheat stirrup
copper dew
wheat stirrup
copper dew
#

what i would do is to create another class as a model, and create it as an object so i can store data in it. for long term data, i would probably just put it in a db

wheat stirrup
#

its not long term, just the duration of the poker game and I don't want to ping a database every time someone bets

wheat stirrup
copper dew
#

yeah good point

#

probably would be able to get away with just making new objects instead

wheat stirrup
#

is it possible to just declare a class but not add it in the extensions?

#

and it would still be usable for the projec

fringe socket
copper dew
#

yeah you would be able to make a class, and just instantiate it as a object, and then use that object to store the data for that game

wheat stirrup
#

okay cool i will play around with that, thanks!

fleet tusk
#

How do I know when I receive a response from a certain site?

still helm
#

Are there any changes that i does not know?

    async def on_ready(self):
        user = await self.fetch_user(322812067994140672)
        await user.send('Bot ist wieder online')
        await bot.change_presence(status=discord.Status.online,
                                  activity=discord.Activity(
                                      name="Youtube",
                                      details="xxx",
                                      platform='YouTube',
                                      game='xxx',
                                      type='streaming',
                                      url="xxx"))
Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\xxx\Desktop\Drache\Python38\WiP\mainBot.py", line 29, in on_ready
    await bot.change_presence(status=discord.Status.online,
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 1208, in change_presence
    await self.ws.change_presence(activity=activity, status=status_str)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\gateway.py", line 656, in change_presence
    activity = [activity.to_dict()]
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\activity.py", line 275, in to_dict
    ret["type"] = int(self.type)
TypeError: __int__ returned non-int (type str)
pseudo glen
#

never do that in on_ready

still helm
#

ok

#

where then?

cobalt tangle
#

how to create a subgroup of a subgroup

cobalt tangle
still helm
#

same error

round rivet
grizzled sentinel
still helm
undone falcon
#

All my parameters are there except add_to_existing_members. Why is it not loading ? guildIds is set to my test server

    @slash_command(guild_ids=guildIds, description="Add a server timed role.Users getting that role will get a timed role")    
    @discord.default_permissions(manage_roles=True)
    async def add_timed_role_to_server(self, ctx: discord.ApplicationContext, role: discord.Option(discord.Role, "The Role that will be a time role for yoru server"),
                                    days: discord.Option(int, "The number of days before the role expire", min_value=0),
                                    hours : discord.Option(int, "The number of hours days before the role expire (is adding time on top of days)", min_value=0, default=0), 
                                    minutes : discord.Option(int, "The number of minutes days before the role expire (is adding time on top of days and hours)", min_value=0, default=0),
                                    add_to_existing_members : discord.Option(bool, "If the bot need to give the time role to member who already have it", default=True)):

I even put a print(add_to_existing_members) in the method and it is printing true

gleaming falcon
silver moat
undone falcon
#

when I try running the command, it disappear, but now the commands is not coming back even when restarting the bot

spice oyster
undone falcon
#

yes they are all there

#

except that one I just commented and decommented

#

I am running version 2.2.1

#

for some reason all commands registration are not working, and where working before

spice oyster
undone falcon
spice oyster
undone falcon
#

but looks like any change I make is not register, except the one when I commented the function (and even then it only worked after I try to use the function in discord and it didn't respond)

spice oyster