#Basic Pycord Help (Quick Questions Only)

1 messages · Page 51 of 1

neat field
#

A quick question about enabling pre-disabled interaction buttons - I am trying to dynamically disable/enable a button depending on the response from the bot (which is either a link (button should be disabled) or just text (button should be enabled))... What would be the best way to handle such a case? (my view is structured like this: https://hastebin.com/mixeyuzibe.py)

silver moat
neat field
#

Therse are not link ones, they're secondaries

silver moat
#

it should be commands.BucketType.user I think.

neat field
silver moat
neat field
#

I know that, however would I need to put that check in the __init__ method? Or somewhere else?

silver moat
#

depends on when you are checking the condition. Is the embed already known when the view is initialized?

neat field
#

Nope, it is just before it is

#

(here)

#

embed is the embed with the response inside of it

silver moat
#

embed is a discord.Embed, so you can pass in the value of embed into the function and check the condition in __init__

neat field
#

I see. Thanks, that's what I was trying to understand 😄

silver moat
#

yw

#

Disregard my previous statement. It appears you are passing in interaction.message, which may or may not exist.

Because get_bucket expects a message with an author, you can do the following:

new_message = interaction.message
new_message.author = interaction.user
bucket = self.cd_mapping.get_bucket(new_message)
quick sand
#

I'm trying to build a string, that holds a conversation. In discord, this conversation will be replies of messages, so message.reference exists in pycord.
I want to recursively go back through all the messages, starting with the beginning, and build a string of all the messages.
I'm having trouble thinking this through and finding a solution to recursively get all messages if message.reference exists.
This is what I'm doing now, and it works to build the previous message and the current message, but I need to keep going until there aren't anymore references and add all the text into the string..

built_message = f"{prev_convo.author.name}: {cleaned_prev_message}\n{message.author.name}: {cleaned_message}"

Any help would be cheffkiss and appreciated ❤️

quick sand
#

fwiw, something like this is halfway working:

            cleaned_prev_message = await sanitize(prev_msg)

            built_message = (
                f"{prev_msg.author.name}: {cleaned_prev_message}\n" + built_message
            )

            if prev_msg.reference is not None:
                prev_msg = await message.channel.fetch_message(
                    prev_msg.reference.message_id
                )
#

but I'm missing the very first message texts...

full basin
#

You could use a loop

west venture
#

how do i make menu like this?

full basin
#

That's a modal

proud mason
#

.guide

winter condorBOT
errant craneBOT
#

Here's the modal dialogs example.

rare ice
proud mason
#

its the solution for everything blobpain

thick hatch
#

hey, sorry guys i couldnt easily find the information as to how to reply to a user in a textbox that only the user can see

civic jayBOT
#
Galactus#9542
About:

Dashboard
Invite link
Commands
Bot support server
Discord bot list Vote
Patreon link
Carl-Bot does what the most popular bots do but does it better, faster, and without the meme commands that spam and annoy you. Carlbot has been used to reduce the number of bots needed in a server from 3 to 4 or more… to just 1.

Members

812,530,108 total
261,215,812 unique

Channels

234,226,863 total
186,172,219 text
48,054,644 voice

Process

3167.85 MiB
7.30% CPU

Servers

7211651
4096 shards

Messages seen

0 messages (-0.0/s)

Uptime

1d 16h 32m 56s

thick hatch
#

or do those just not exist

#

oh i think those are reserved for discord stuff

thick hatch
#

this

#

if you guys know how please tell me a solution cause people are sick and tired of my bot sending messages in a not very active server lol

proud mason
thick hatch
#

hmm

#

where would i do so?

proud mason
#

thats all

thick hatch
#

awesome, thank you so much.

fallow hawk
#

for a modal could i have it require a bool or an integer instead of a string?

west venture
# west venture how do i make menu like this?

uhh i wanted to basically make a ticket channel like that and post all these answers in the ticket channel how do i do so



class MyModal(Modal):
    def __init__(self) -> None:
        super().__init__(title="Ticket Creating")
        self.add_item(InputText(label="why ur unemployed?", placeholder="Your Answer here",style=discord.InputTextStyle.short))
        self.add_item(InputText(label="ohh ye are u that failure?",placeholder="Your Answer here",style=discord.InputTextStyle.short))
        self.add_item(InputText(label="Your A disappointment",placeholder="Your Answer here",style=discord.InputTextStyle.short))
        self.add_item(InputText(label="Also get a job",placeholder="Your Answer here",style=discord.InputTextStyle.short))

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(
            title="Application Ig",
            fields=[
                discord.EmbedField(
                    name="Q)why ur unemployed?", value=f"A: {self.children[0].value}", inline=False
                ),
                discord.EmbedField(
                    name="Q)what are your thoughts on being failure?", value=f"A: {self.children[1].value}", inline=False
                ),
                discord.EmbedField(
                    name="Q)Are you still unhappy that you are disappointment", value=f"A: {self.children[2].value}", inline=False
                ),
                discord.EmbedField(
                    name="Q)Also get a job", value=f"A: {self.children[3].value}", inline=False
                ),
            ],
            color=discord.Color.random(),
            timestamp=datetime.datetime.utcnow()
        )
        await interaction.response.send_message(embeds=[embed]) #instead of sending it in the interaction channel i want it in ticketchannel
proud mason
#

Then create a text channel

#

.rtfm categorychannel.create_text

winter condorBOT
proud mason
#

And send the embed

proud mason
# winter condor

You would want to pass perms overwrites to make it a secret channel yk

ornate current
#

why does the .voicestates return wrong values? When i turn on the bot it shows 2 person in the vc ( which is correct) then it stays at 2 and doesnt update

#

.rtfm voice_channel.voice_states

winter condorBOT
#

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

ornate current
#

.rtfm voicechannel.voice_states

winter condorBOT
polar plume
#

Hello guys

#

How do I make it so that user has to give at least any one of the available options

limber urchin
#

.rtfm discord.Option.required

winter condorBOT
#

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

polar plume
#

Is there something like hintText in an option to let the user know what format the option takes string in

summer fulcrum
#

.rtfm paginator

fervent cradle
#

So I have been trying to make country searcher and I am stuck with this, I can't figure out the problem (it says keyerror '{country i put in}',) which is reading from args (which I set to tuples)

#

(the error seems to only happen with "[tuple(args)]" cause when i put it in as specific country it works

limber urchin
#

Why are you trying to use a tuple as a key? That is not how dicts work in Python at all

fervent cradle
#

so I should put it as object?

limber urchin
#

object?

fervent cradle
#

what should I put it in as?

limber urchin
#

Do you know basic Python?

fervent cradle
#

yeah i guess but doesnt seem to work in anyway

summer fulcrum
#

.rtfm discord.Embed

limber urchin
summer fulcrum
#

ok

limber urchin
fervent cradle
#

nvm gonna move it json instead

limber urchin
#

???

#

I feel like you don't know what you're doing at all

summer fulcrum
#

How to set footer to Embed in pages.Page()
I trying use:

Pages[c_page].set_footer(text=f"Page {page_numbering}/{total}")
fervent cradle
polar plume
#

Why are the docs in light mode. It's hurting my eyes

limber urchin
#

Probably because you aren't using the dark mode?

polar plume
#

wait it has a dark mode?

limber urchin
#

Yes?

polar plume
#

lmao my bad.

limber urchin
#

What do you think this button does?

polar plume
#

yeah, I just figured it out.

#

This icon was so misleading

proud mason
maiden ocean
#

idge

polar plume
#

In Embeds is it possible to add a field with either empty name or value?

grizzled sentinel
#

Kinda, iirc if you use an invisible charecter let my check real qucik

polar plume
#

sure

grizzled sentinel
#

Try using this unicode charecter
\u200B ->

summer fulcrum
#

How to set footer to Embed if it was created via pages.Page()?

summer fulcrum
#

I found a way

Pages[page].embeds[0].set_footer(text=f"Page {page_numbering}/{total}")
summer fulcrum
#

why, when creating a Field via EmbedField, if the name starts with numbers, does it skip the creation of this and subsequent fields?

summer fulcrum
#

oh, it's my error

warm kindle
#

how to delete messages?

cunning furnace
#

How would I go about sending logs of deleted messages/edited messages once the bot has been restarted. It seems to just not log messages from before the restart

young bone
zinc cloak
#

Question, does py-cord protect against rate limiting?

#

Or should I put checks in place so I don't get rate limited

young bone
#

Im not even if the other ones are doing it

zinc cloak
#

Is there something I can do to put checks in place before this happens?

limber urchin
#

Add your own checks wherever you might spam the API

#

usually you shouldn't need checks at all unless you're doing some specific spammy thing

thorny stag
#

I have a bot that creates an emoji, sends it and then deletes it, but deleting the emoji fails sometimes

#

Please ping if you respond

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.

thorny stag
# young bone ?tag idw

I assumed the code would delete the emoji after sending it but it only deletes it sometimes

#

wait no im dumb I think I know why

young bone
#

Why?

thorny stag
#

I forgot to delete the emoji if I got an error from an api

#

im so silly

astral mist
#

how do i get username of the person that did the command

#

.rtfm user

astral mist
#

ping when respond

young bone
astral mist
young bone
#

It should return discord.Member

full basin
full basin
#

They're called attributes

polar plume
#

How do i add a dropdown with a page

astral mist
amber shale
#

how can i do automatic bot testing?

#

i need some basic idea to start, i am new to automated testig

ornate swan
#

is there a way to select users in a select ui?

young bone
ornate swan
#
options = [
            discord.SelectOption(label=self.client.get_guild(get_guild()).get_member(user[0])) for user in get_all_motm_by_id()
  ]
#

im not sure how to give him the self value in that case

lean marten
#

How can I enable the message_content intent?
my bot got verified and the message_content intent activated, how can I enable it?

silver moat
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

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)
Discord Developer Portal

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

lean marten
#

oh

#

ty

silver moat
#

yw

grizzled sun
#

CA how often does a heart beat occur?

#

2-3 seconds or like 100-200 ms?

#

or somewhere in between

surreal elk
#

'TwoCaptcha' object has no attribute 'normal'

silver moat
young bone
rare ice
fallow hawk
#

how would i go about organizing buttons in a list by a number in them?

#

like i have a list of buttons and the labels are "button 1", "button 3", "button 2" but how would i get it to have the buttons in order?

limber urchin
#

Sort the buttons in a list and add them to your view in order

fallow hawk
#

oh ok

mild sigil
#

Hey all, I have a hopefully quick question. I am attempting to run my Bot but each time I run it I get:

Cannot find reference 'Bot' in 'init.py'

I have downloaded pycord with pip and verified that it is in my available packages for python.

mild sigil
young bone
#

and the code pls

silver moat
#

full traceback thanks

mild sigil
#

in what format for code?

silver moat
mild sigil
#

bot = discord.Bot()


@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}.')


testingServers = [1062908565431521363]


@bot.slash_command(guild_ids=testingServers, name="work", description="Checks to see if I am online")
async def work(ctx):
    await ctx.respond(f"I am working! \n\nLatency: {bot.latency * 1000} ms.")


bot.run('token')```
silver moat
mild sigil
#
  File "C:\Users\Akira\Documents\Python\DiscordBot\Test\slashcmds.py", line 3, in <module>
    bot = discord.Bot()
          ^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'```
young bone
mild sigil
#

pip list right?

silver moat
#

Pycharm?

mild sigil
#

pycharm indeed

young bone
#

you have to use the pycharm terminal

silver moat
#

on the bottom right corner there is something called packages

#

you would have to install the packages from there

young bone
#

or that ^

silver moat
mild sigil
silver moat
#

did you restart IDE?

mild sigil
#

just restarted my computer after posting the second code snippet

silver moat
#

did you uninstall discord.py before installing py-cord or after?

mild sigil
#

uninstalled discord.py after installing py-cord, was wondering if that might be a potential cause

silver moat
#

yeah reinstall py-cord

#

so uninstall and install py-cord

mild sigil
#

👍

#

nope, didn't fix it, restarted the ide as well

silver moat
#

do you have a file named Discord?

mild sigil
#

anywhere on the computer or in one of the python directories?

silver moat
#

in the same folder you are running your bot from.

mild sigil
silver moat
#

how are you running your bot

limber urchin
# mild sigil

Aren't you using PyCharm? Reinstalling from your terminal won't do anything

#

PyCharm creates virtual environments for every project, anything you do in your normal terminal will have no effect on things you're running from PyCharm

mild sigil
#

it doesn't grab from the site-packages folder?

young bone
#

Can you try it with the pycharm terminal

mild sigil
#

running it in the pycharm terminal

young bone
#

I mean the installation

silver moat
#

you would use the "python packages" UI

mild sigil
#

using this?

silver moat
#

and right click one to uninstall

mild sigil
#

ok, py-cord was deleted, will try installing it through pycharm

#

hmm, got it through pycharm, still not working. Should I just use a different IDE?

#

this is what I see in the pycord installation

#

that might be the issue, though why I don't see any of the other folders like are shown on Git I have no idea

fringe socket
#

How can I get which user deleted a message?

#

nvm i think i figured it out

#

yep i did

coarse spire
#

what am I doing wrong? I created a .gitignore file and this is the content; venv/ . I don't want it to upload the venv directory to github.

fringe socket
#

wait if you don't upload the venv how do you start the bot?

coarse spire
#

someone opened a issue on my github project with this content, so I don't know...: The venv directory should be ignored, and definitely should not be pushed to GitHub. It's supposed to be on your computer and stay that way, never getting uploaded.

fringe socket
#

Vincent moment

coarse spire
fringe socket
#

dont ask me lol

coarse spire
#

lol

amber shale
#

i want to make a new command creator like slash_command or bridge_command

#

can i get some place to start? (to learn or something like that)

ornate current
#

.rtfm channel.voice_states

winter condorBOT
bitter lance
#

is this wrong way? I don't know why ping command not show

class Testbot(commands.Bot):
    ...
    @slash_command(name="ping", description="ping", guild_ids=[...])
    async def ping(self, ctx):
        ...
proud mason
#

commands dont go inside the bot subclass

#

they go inside a cog class

#

.guide

winter condorBOT
bitter lance
#

aha

proud mason
#

check it out

bitter lance
#

thanks!

light river
#

is it a bad idea to start an event loop in a thread?

#

because i want to make the bot send messages in a thread but that doesn't seem to work

proud mason
#

Also why not use ext.tasks ?

light river
#

i'll check that out l8r

fleet phoenix
#

Hi ! Just updated my bot for the first time in ages, and i get this when reloading one of the cogs ```
File "/.../cogs/antiping.py", line 17, in on_message
mutedRole = discord.utils.get(guild.roles, name="|Muted|")
AttributeError: 'NoneType' object has no attribute 'roles'

File "/.../cogs/antiof.py", line 27, in antibot
guild = msg.channel.guild
AttributeError: 'DMChannel' object has no attribute 'guild'

```py
    @commands.Cog.listener()
    async def on_message(self, msg):
        guild = msg.guild
        mutedRole = discord.utils.get(guild.roles, name="|Muted|") # LINE 17, FIRST ERROR

    @commands.Cog.listener("on_message")
    async def antibot(self, msg):
        guild = msg.channel.guild # LINE 27, SECOND ERROR

Has msg.guild been deprecated ?

hushed ledge
#

One message removed from a suspended account.

strange cradle
#

Hi, i have to questions:
1 - can we somehow get something like a user.banner.url ?

2 - I heard that discord.py v2.0 have a banner method, can i use discord.py 2.0 with pycord?

strange cradle
boreal dust
#

.rtfm on_reaction

boreal dust
#

what is the difference between raw reaction and normal one?

full basin
#

.rtfm DMChannel.guild

winter condorBOT
#

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

full basin
#

No such attribute.

full basin
full basin
boreal dust
#

.rtfm DMChannel

boreal dust
#

.rtfm discord.on_raw

boreal dust
#

means this it will get triggered every time?

full basin
#

Yes

boreal dust
# full basin Yes

how do i change on_reaction_add(reaction:discord.Reaction, user:discord.Member): to data?

#

i am lost

#

is this like payload.message etc?

silver moat
#

read the docs

boreal dust
#

aleready checking that

#

ah bruh

#

ill keep it working with on_reaction_add

hushed ledge
#

One message removed from a suspended account.

proud mason
hushed ledge
#

One message removed from a suspended account.

proud mason
#

?tag botvar

obtuse juncoBOT
#

dynoError No tag botvar found.

proud mason
#

ugh one sec

#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

hushed ledge
#

One message removed from a suspended account.

proud mason
#

.idw

winter condorBOT
#

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

hushed ledge
#

One message removed from a suspended account.

#

One message removed from a suspended account.

proud mason
proud mason
hushed ledge
#

One message removed from a suspended account.

young bone
#

?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

proud mason
#

||zervyrel should be helper too||

#

lulz you pro

errant craneBOT
#

Here's the slash basic example.

proud mason
#

.guide

winter condorBOT
proud mason
#

see that too

young bone
#

For sending a discord crashing video

proud mason
#

lmao

young bone
#

It was in #💩posting x3

proud mason
olive fog
#

By advice from a discord bot-help server, I uninstalled discord.py v2 and then installed py-cord 2.3.2 into PyCharm. There were two py-cord packages, one named py-cord and one named py-cord2, but py-cord2 was broken.

Upon installing py-cord 2.3.2 (and verifying that 2.3.2 is the latest version on Github too), PyCharm complains that discord.app_commands and discord.app_commands.tree are invalid/non-existent imports.

The other server suggested I try asking about this here, with the statement "that should not happen" because py-cord is a direct fork of discord.py.

Did I do something wrong, get a bad package, or any ideas?

olive fog
#

An attempt to install py-cord2 generated another error involving reading the package, not just the description.

proud mason
#

.guide

winter condorBOT
olive fog
#

@proud mason Been doing so, thanks. I just wanted to make sure I didn't get a bad package or bad version through PyCharm. I think you confirmed that I probably have the right thing.

fervent cradle
#

Does a giveaway Bot require a database?

proud mason
fervent cradle
proud mason
fervent cradle
olive fog
# fervent cradle Does a giveaway Bot require a database?

I say it only depends on whether you intend to persist A LOT of data in the backend. Reasons to persist bot-side data include that your bot won't track messages (or events such as reactions) which occurred before your bot joined the server, or occurred if your bot is in the server but shut down/offline for any reason. At that point your bot only tracks the last 5000 messages it saw. So if your bot ever goes down, has to be restarted, etc, it loses track of anything/everything that happened before it shutdown. If you won't persist A LOT of data, you can just serialize objects or arrays (aka lists/dicts/etc) in Python, but if you will persist A LOT or if you'll persist for A LOT OF TARGETS then you'd benefit from a relational database.

fervent cradle
#

Oh okay thank you, i can work with that knowledge now

hushed ledge
#

One message removed from a suspended account.

proud mason
winter condorBOT
proud mason
#

has a good writeup on that

fervent cradle
hushed ledge
olive fog
#

Sorry for ping-spam if that happened to anybody. I switched that from an @ to a reply for clarity.

#

But again, you can store all of that just as easily as a class-instance attribute and serialize the instances to disk. You don't need a relational database for that, especially if it's a custom bot for just 1 server

fervent cradle
#

Sorry for so many questions

proud mason
#

postgres, mysql are good options. you can also use sqlite if you want a file based db rather than a server based db.

#

i suggest postgres as it is considered the fastest

fervent cradle
#

Server based DB can store more DB right? Does postgres use SQL?

olive fog
# fervent cradle It probably will not be one server, meaning i would want to use a relational DB ...

Depends on what you intend to host it on. Debian and forks like Ubuntu default to Maria, which is a fork of MySQL. Oracle's actual MySQL is fine too. I also really like SQLite, which is A LOT EASIER than MySQL, especially for making backups and such, and doesn't require separate hosting. MySQL/Maria is a solution for 88 different services which all need to access the same database, where the DB lives on one server and the remote clients live on other servers.

fervent cradle
#

What would be the fast, and not super hard to learn/understand DB?

olive fog
#

So if you want users to log into your website and sign up for giveaways on their Discord server, then yes, MySQL is a better choice.

fervent cradle
#

A website would not be involved, all discord side

olive fog
proud mason
#

there isnt a very big difference between using postgres, maria, mysql

fervent cradle
olive fog
fervent cradle
#

I have linux on my PC (partioined) if that matters as you guys mentioned it earlier.

proud mason
olive fog
fervent cradle
olive fog
fervent cradle
olive fog
#

Just do yourself a favor and decide, before you start, whether you might ever want to expand into multi-client, because migrating from file-based local databases to web-based databases is a b***h. You have to learn a whole new style of configuration and maintenance on top of a whole new SQL syntax, and fix all your code to use the new thing.

fervent cradle
olive fog
# fervent cradle Hm, I mean of course if i put some time, and effort to see how to use MYSQL/post...

Just want to put this out there: If you decide on a web-based database, like MySQL, don't shy away from good servers like Debian/Ubuntu because they use Maria (the MySQL fork) instead of the original. You literally use the same Connector for both, whether it's Python or PHP or DotNET or embedded C/++, you literally use the same commandset at the CLI, and you literally have all the same features and SQL syntaxes. Where Maria diverges are all "extras" and not "basics"

fervent cradle
olive fog
# fervent cradle What are the main differences between maria and MYSQL? & Why would i use a web D...

I just said main differences are non-existent, as far as you should be concerned at your stated skill level. And I said before that a web-based DB is for when you have multiple clients, like 2 websites and a bot, all using the same data, but not all hosted on the same box. A file-based DB can do the same thing if your bot and webserver are all in the same server environment, but if you needed to access a file-based DB from a different network/internet host you would have to jerry-rig your own SSH interface or web-api type thing to make that happen.

#

MySQL for example allows direct TCP/IP connections to be SSL-encrypted, but if you wanted to imitate that with SQLite you would have to set up Apache (or whatever webserver you like) to proxy database queries for you.

fervent cradle
#

Thank you, just one last question (hopefully), If the bot is being hosted on another PC than it is being created/tested on will that affect the database?

olive fog
#

Well, that's not right.

#

You would probably want segregated test and production databases anyway.

fervent cradle
proud mason
fervent cradle
proud mason
fervent cradle
#

okay so I'm thinking I will do further research then decide what dB to use

gleaming falcon
#

Dumb Python question - can one add async methods to the constructor by using an __await__ method? Would this work for pycord Cogs?

from https://stackoverflow.com/a/58976768/18366895
(ignore args, just curious if the the general concept is sound)

class Foo:
    def __init__(self, settings):
        self.settings = settings

    async def async_init(self):
        await create_pool(dsn)

    def __await__(self):
        return self.async_init().__await__()
olive fog
proud mason
#

but you dont need to do all that

gleaming falcon
#

The idea is to run async commands when the class loads. You can't do it in __init__

gleaming falcon
#

Just seemed so dirty. But okay, I'll go back to using that.

proud mason
#

its the cleanest tbh

olive fog
#
    def __init__(self, some_arg: str):
        self.some_attr: str = some_arg

    @staticmethod
    async def create_new(some_arg: str) -> "SomeClass":
        # Quotes around type-hint-for-return (above) allow you to type-hint without import errors on account of class
        # being not fully initialized
        return SomeClass(some_arg)


some_class = await SomeClass.create_new(r"test")

???

gleaming falcon
# proud mason you can use `asyncio.create_task`

Stupid question, but will this also contextualize non-async code in a way that doesn’t block? I have an identity library that doesn’t support async itself. I thought there was a way to wrap calls so that they don’t block the main thread but I could be dreaming that

proud mason
#

ive realised that asyncio has everything lmao

alpine kernel
#

mmm so when i try and link a user in a response, sometimes i get the actual user, but most of the time i just get a highlighted <@[user id]> can the bot just not see those users somehow?

gleaming falcon
#

IIRC, it's something to do with Discord's crappy caching on your local client, not the bot.

alpine kernel
#

so it's just on my end and some users might see the actual name?

#

or will all users have to restart discord for it to update

gleaming falcon
#

Some, yes. Note that you do have to share a server with the user, just to make that clear for it to even have a chance to work. I don't think you're able to enumerate random user Ids.

But even in times where you do, I have seen it break

alpine kernel
#

yeah i understood some aspect of the bot needing to 'see' the user someway

gleaming falcon
#

To be clear, it's not anything to do with the bot, I'm talking about yourself.
The <@userid> syntax in messages are locally rendered.

hushed ledge
alpine kernel
#

and for some reason the id to user name link isnt cached, is there any way to force the link somehow or cache update?

#

like from a local perspective, not the bot

gleaming falcon
#

One of the most common bugs I come across on Discord.

alpine kernel
#

k thanks though!

proud mason
olive fog
alpine kernel
#

I save the user id and then use

content = f'<@{user}>'
#

this is for helping in a game where people could have a bunch of characters that link to one discord user

#

i also disable allowed_mentions for users

#

might be a possible culpret

#

want to basically link the discord user, but not ping them

gleaming falcon
#

That shouldn't have any bearing on whether it's shown.

olive fog
#

@alpine kernel Try getting a handle on a User object such as via bot.get_user(id) and then using user_object.mention("message")

alpine kernel
#

okey, yeah that might help

olive fog
#

My syntax is bad, sorry.

f"{user_object.mention} rest of message"
gleaming falcon
errant craneBOT
#

discord/user.py lines 251 to 254

@property
def mention(self) -> str:
    """Returns a string that allows you to mention the given user."""
    return f"<@{self.id}>"```
olive fog
#

Sorry then.

alpine kernel
#

worth a shot =T

gleaming falcon
#

Yeah, it's a super-frustrating issue for sure, I'd do everything I could to try to mitigate it, too. Just trying to save you the headache since I know I've gone through this whole process, too.

Strangely I don't see it mentioned a lot.

olive fog
#

@alpine kernel So when this occurs, does the Mention still work as expected on the targeted user's end?

alpine kernel
#

I dunno, i'll have to do more testing

gleaming falcon
#

I'd have to imagine yes, since it's a caching issue and presumably the targeted user has their own information

olive fog
#

If so, then just to clarify for anybody affected by the bug, you could append something like:
f"({user_object.name}#{user_object.discriminator})"
after the mention itself.

alpine kernel
#

yeah I'll have to figure something like that out

olive fog
#

I'm reading through https://guide.pycord.dev/interactions and when I follow the links to User Commands and Message Commands it bounces me to the raw Discord API documentation on JSON interchange. Does that mean these features are not implemented in py-cord? Edit: Sorry about the raw string. I was trying to avoid embed-spam Discord attaches to web-links and then realized that not being able to click on a link is worse

#

Oh, nevermind. I found a working link further down the page. There are a couple of 404s in between there though.

alpine kernel
#

man, frustrating day heh cant even get get_user to work, just returns none >.<

olive fog
#

@alpine kernel I just discovered bot.get_or_fetch_user(id) while looking at my own project. fetch_user is evidently for working around the cache problem, and get_or_fetch_user checks the cache then fetches as needed.

alpine kernel
#

mmm ok i'll check that out

#

oh i was using get_user in an async that's probably why it returned none

#

need more coffee i guess

olive fog
#

Didn't Python give a Trace on it?

alpine kernel
#

yeah, it just returned none though, cant you not do non async calls in an async function? need to go back and read what's ok and whats not heh

#

also, just started using my bot on my game friends server, is there a way to update the bot without interrupting the connection? i'm just running the bot locally and just re executing it when i update. might just make a separate bot for doing testing/dev

olive fog
alpine kernel
#

well that's still weird, get_user wasnt working but fetch_user did

olive fog
#

Again, get_user looks in the cache and fetch_user makes a Discord API request

alpine kernel
olive fog
#

Or so the docs imply

alpine kernel
#

oh, well that's weird that i wasnt in the cache heh

olive fog
#

You know most civilized nations have some law that if you have less than $1 of their currency, you are technically "vagrant." Better hit up an ATM and get yourself some cache!!!

olive fog
alpine kernel
#

ok i'll check it out

#

i was doing something crazy on a project i was working on a few months ago heh

#
    @commands.command(name='restart')
    @commands.is_owner()
    async def _restart(self, ctx):
        """Restarts the bot, can only be used as the owner of the bot"""
        #await interaction.response.send_message(interaction.user.id)
        sys.argv.append("--owner_restart")
        sys.argv.append(str(interaction.channel.id))
        embed = discord.Embed(title=":arrows_counterclockwise:", description = f"Restarting...")
        await interaction.response.send_message(embed=embed)
        os.system("cls")
        os.execv(sys.executable, ['python'] + sys.argv)
#

still seemed like a wonkey way to do it though

olive fog
#

I find programming in Python to be like watching a movie. Check all your rational thought processes at the door and prepare to work around the runtime.

obtuse juncoBOT
#

Tag Credit: discord.py server
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().

Do use:

  • run your bot in a process manager such as:
    • systemd
    • openrc (gentoo, devuan)
    • runit (void linux)
    • supervisord
    • upstart (old ubuntu)
    • docker
  • manually reboot it

Do not use:

  • a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
  • subprocess.call (you will eat your memory up by not letting your old processes die)
  • os.exec*
alpine kernel
#

thanks!

#

mmm now sometimes either my command line gets hung up or people 'stress testing' it is making the command line stall

#

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

fixes itself by 'nudging' the command line

young bone
#

why do you use interaction?

alpine kernel
#

i think it's an error in the package

young bone
alpine kernel
olive fog
#

So I have this weird thing with Context Menu Commands. This is how/why I ended up trying py-cord in the first place. I finally got py-cord to remove old/removed Context Menu items by calling bot.registercommands() but the same thing happens with py-cord that happened with discord.py -- The item shows up where it should, under Apps, when I right-click a user name, but then I get a little popup telling me that "This interaction failed" which a little while later changes to read "The Application did not respond"

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.

olive fog
#
async def ciao(ctx: discord.ext.commands.Context, member: discord.Member):
    await ctx.respond(f"Ciao {member.mention}")```
#

sync_commands does nothing, but register_commands makes it work. "Welcomes User" appears in the Apps part of the Context Menu, as already described. Clicking on it results in a little popup in the message part of Discord which first says "This interaction failed" and then changes to "The Application did not respond" after some time

young bone
#

can you remove : discord.ext.commands.Context?

olive fog
#
@discord.ext.commands.is_owner()
async def shutdown(ctx: discord.ext.commands.Context):
    await ctx.message.delete()
    await ctx.send(f"{bot.user.name} bot engine shut down by {ctx.author.name}")
    await bot.close()

    print(f"{bot.user} Bot engine shut down")```
This one works just fine.
#

It's a /command though.

young bone
#

which client do you use?

olive fog
#

I think I just found the problem.

young bone
#

?tag clients

obtuse juncoBOT
#

dynoError No tag clients found.

young bone
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
young bone
olive fog
#

discord.ext.commands.Bot

#

Ugh. I did not find the problem, nope.

young bone
#

are you sure, that you have py-cord and nothing else installed?

olive fog
#

Yep. I double-checked my venv after removing discord.py

crimson adder
#

Hi, sorry for the inconvenience, I've been looking for a solution to my problem for about 2 hours and I haven't found anything on the internet or in a post here.

So, I want to make a DropDownMenu where the values are put from the command, example :



class MyView(discord.ui.View):
    #options = options that i want
    
    @discord.ui.select( 
        placeholder = "Choose a Flavor!", 
        min_values = 1, 
        max_values = 1, 
        options = options
    )
    async def select_callback(self, select, interaction): 
        await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")

@bot.slash_command(name="view", help="Change the area of the character")
async def view(ctx):

    options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Vanilla",
                description="Pick this if you like vanilla!"
            ),
            discord.SelectOption(
                label="Chocolate",
                description="Pick this if you like chocolate!"
            ),
            discord.SelectOption(
                label="Strawberry",
                description="Pick this if you like strawberry!"
            )
        ]
    
    await ctx.respond("t", ephemeral = True, view = MyView(options))

    character.save_to_db()```

But I can't find anything on how to do it, and on my own I have no idea.

Is there anyone who has a solution ?
young bone
olive fog
#

I installed py-cord fresh after that, yes. I think PyCharm uses PyPi

#

I never had py-cord and discord.py installed alongside each other.

young bone
#

which version?

olive fog
#

2.3.2

young bone
#

Can you create a new project and try it there again?

olive fog
#

Sure. That will take a few though.

#

Done. I totally deleted every __pycache__ and PyCharm's .idea and the existing venv directory. I then re-created the project, re-created the venv, re-installed python-dotenv and py-code -- run the bot, joins the server, updates the context menu item, but clicking on the context menu item results in that little box which says "This interaction failed" and nothing else. No errors, no python trace, nothing.

#

For clarity: When building my bot's "invitation link" in the OAUTH2 configuration, I very carefully combed through all the possible scopes alongside the Discord API docs and I selected absolutely every scope except the 4 or 6 marked "Requires approval from Discord" which are about DMs and RPC.

#

I modified the code thus:@bot.user_command(name=r"Welcomes User") async def ciao(ctx, member: discord.Member): print('user command triggered') await ctx.respond(f"Ciao {member.mention}")
and the print never occurs either, so it seems like the interaction is never relayed to my coroutine.

alpine kernel
#

man, still having issues with get_user() and get_or_fetch_user(), i enabled member intents, dunno if it's some sort of permission blocking, but certain users just return with None =T

alpine kernel
#

getting a user info for a guild

#

yeah, it's just not really clear what exactly i need, I would expect it to throw a permissions error if i didnt have access :T

limber urchin
#

Could you show exactly how you're using the methods?

#

You don't need intents to fetch users, only server members

#

No, you don't need that for users

#

only server members

cyan quail
#

^ fetch_user doesn't require any permissions or intents

olive fog
#

OK, my bad. Just trying to help.

alpine kernel
#

yeah, i researched everything seems like its not a permissions thing, give me a sec to reorder my code

#
    @commands.slash_command(name='howmany', description='1')
    @discord.option("type", choices=['Users', 'Characters'], default='Users')
    async def _howmany(self, ctx, type:str):
        print(f"Got request to howmany {type} by {ctx.author} - <@{ctx.author.id}>")
        if type == 'Users':
            users = json.load(open('data/users-by-id.json', 'r', encoding='utf-8'))
            l = len(users)
            user, info = random.choice(list(users.items()))
            try:
                print(user)
                #got_user = await ctx.guild.fetch_member(int(user))
                print(got_user)
                got_user = await self.bot.get_or_fetch_user(int(user))
                ment = got_user.mention
            except discord.errors.NotFound:
                ment = 'USER NOT FOUND'
                
            await ctx.send_response(content=f'_ _\nThere are {l} users in my database, {ment} is the coolest', ephemeral = True, allowed_mentions=discord.AllowedMentions(users=False))
#

dont bash me for not using a db to get stuff please, slowly building this stuff heh

limber urchin
#

Are you sure you're actually getting an ID from your json? And yeah, don't use json

alpine kernel
#

yes

#

i manually confirm that the id retrieved IS a user on the server where i'm using the command

cyan quail
alpine kernel
#

yes, it's up there in the command

limber urchin
cyan quail
#

yeah

alpine kernel
#

I'm able to manually check my ID works, and some others IDs do work

#

ok

#

yeah it just throws discord.errors.NotFound

cyan quail
#

then the ID's definitely wrong

#

fetch_user is guaranteed to work on any real user

alpine kernel
#

hmph that's annoying, i'll try and triple check everything i guess

young bone
#

can you show the intents?

alpine kernel
#

wouldnt be out of the ordinary for me to be missing something small

#
intents = discord.Intents.members + discord.Intents.default()
MyBot = discord.Bot(intents=intents)

but from the above intents doesnt seem to be the issue, i've also just ran with default intents

limber urchin
#

Yeah no, you definitely have an invalid ID then

cyan quail
#

fwiw, if you manually input the IDs one common misstep people make is copying the message ID instead of the user ID

limber urchin
#

You're most likely saving your IDs incorrectly somehow in your json file

#

unless you manually input them and copied the wrong id, yeah ^

alpine kernel
#

yeah i'm doing something wrong but I dont know what,
so if I do

user = "user number here"
print(type(user))

it says str object is not callable, am I dumb shouldn't that work? this isnt even using json, just a string

#

i think i'm missing something about working in async functions

cyan quail
#

do you have a variable called type

alpine kernel
#

god i'm dumb

cyan quail
#

rip

limber urchin
#

oof

alpine kernel
#

ok so that kinda leads me to another question, i want to use stuff like 'class' as a parameter name at least to SHOW on a option for a command, but it shadows is there any way to display it as one name but change how the variable is named?

#

only thing I can think of is just using something like class_

cyan quail
#

in Option(...) set name

alpine kernel
#

ok I tried that, didnt work but i'll try it again and not be dumb

cyan quail
alpine kernel
#

yeah I might have also been impatient sometimes things take a while to update

limber urchin
#

You might have to refresh your Discord client for them to update with Ctrl + R

alpine kernel
#

oh that's helpful thanks

quartz thunder
#

Hey all hope you are fine ! I need to do a modal with a select menu to select a server role, how can I do that ?

quartz thunder
#

Hmm I can create options looping the roles no ?

cyan quail
#

modals don't support select menus at the moment

quartz thunder
#

Ah :p

alpine kernel
#

ok to conclude, i'm really dumb i was making the discord ID mapping by copying id from the search window, which was copying the message id, not the user, rip about an hour of data entry -.-

quartz thunder
cyan quail
#

rip

cyan quail
#

also note you can't filter which roles are displayed; it will always display all roles in the guild

quartz thunder
#

Have you got an exemple to make that ?

errant craneBOT
#

Here's the dropdown example.

cyan quail
#

ah i guess it's not displayed there

quartz thunder
#

Okey so I foreach the roles and I add options ? :p

#

Hmm ye

cyan quail
#

it depends on what you want

quartz thunder
#

All roles

cyan quail
#

If you don't mind all guild roles showing, you can just use the discord.ui.role_select decorator

#

this won't have an options arg, you just use it

quartz thunder
#

Okey, thanks great informations !

#

😉

sick quest
#

are there message command groups? like slash command groups... but for message commands

sick quest
#

alright cool thanks

mild sigil
#

Back again with the same issue, different question

#

For python packages, I assume they are generally saved to the site-packages folder of the most recent python version?

#

so If I get this

  File "C:\Users\Akira\Documents\Python\DiscordBot\Test\pycord\slashcmds.py", line 3, in <module>     
    bot = discord.bot()
          ^^^^^^^^^^^^^
TypeError: 'module' object is not callable```
mild sigil
#

bot has to be uppercase?

young bone
#

yes

#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
young bone
#

@mild sigil

mild sigil
#

welp

#

I am the dumb, thank you kindly

young bone
#

\o

crimson adder
cyan quail
#

you can access it in the callback still

crimson adder
#

Juste select.value ? Don’t have to take it somewhere before ?

cyan quail
#

well, select.values as always

crimson adder
#

Yeah sure.

#

Well, i just wanted to make things more complicated than they are. Wiggle

#

Thank Nelo. MHXWink

knotty surge
#

Hello all, I am just wondering. For some reason the character ^ is being removed from my file name when sent using my discord bot. Does anyone know why this is happening?

crimson adder
# cyan quail select.value

I'm back for the same problem, i got an error trying to run the code :

NameError: name 'select' is not defined

#

So in know what's the error mean, i just don't know what i should put to correct that.

fringe socket
#

💀 It literally tells you what to do. Define "select"...

crimson adder
#

Thanks Aqua, but if i ask it's because i don't know if there's a specific way.

fringe socket
#

How do you grab the created_at for an AuditLogEntry fetched through message.guild.audit_logs?

crimson adder
proud mason
knotty surge
marble nova
#

for some odd reason custom emojis get converted to their :name: version once a response is edited is there any way to fix that?

proud mason
graceful brook
#

Is there a way to not return an interaction response?

marble nova
#

works now ty

kindred sail
boreal dust
#

if you use button

#

ctx.defer()

graceful brook
#

Unfortunate. My way of "getting around" it in a Modal dialog is to send a response then delete it directly after.

dawn berry
#

in my error handling for permissions error I get a list of strings representing the missing permissions. How do I create a Permissions object from that type of string so that I can compare them to other Permissions objects?

gilded niche
#

How would i let my bot send a message in another discord?

dawn berry
grizzled sentinel
gilded niche
grizzled sentinel
grizzled sentinel
#

You could turn the list into a dict where the keys are your list of permissions and the values are all true or false depending on your situation.

Than pass it to the permissions constrctor like in the accepted answer of this SO post
https://stackoverflow.com/questions/1496346/passing-a-list-of-kwargs

dawn berry
#

I decided on doing it another way and not overcomplicate things.

grizzled sentinel
#

👍

dawn berry
#

I decided to just send the default error message string instead of making my own for each error.

#

on a similar note, why doesn't discord.errors.Forbidden get caught by the on_error handler?

silver moat
#

on_error catches errors in events

dawn berry
#

my error was raised by a message that failed to send in another event handler

#

Is an on_command_error handler not an event?

olive fog
dawn berry
#

I see

olive fog
#

In Server-Client programming, you gotta keep 'em separated.

dawn berry
#

kzitsfine alright thamks

fervent cradle
#

Should i store every user who joins a giveaway in a database? then either delete at end of gw or smth

limber urchin
#

Yes? What else would you do?

fervent cradle
fervent cradle
#

@limber urchin ?

dawn berry
#

can I use dicord.Greedy in type hints to expect the name of a Cog?

#

doesn't seem like it from the docs so nvm

olive fog
#

Do you mean the name of a class which inherits/extends from Cog or do you mean the value of the cog.name attribute from an instance?

fervent cradle
olive fog
#

Also thanks for saying I'm nice. Mostly people tell me I'm "aggressive" and "scary" or that my terminology is too technical.

#

I try to be nice!

#

@fervent cradle Also, gigabytes of storage are cheap AF so don't worry about deleting giveaways after they're done. Make a command Guild admins can use to review past giveaways.

#

A whole novel worth of raw text is to a gigabyte of storage is as a fist-sized rock is to a 5-gallon bucket.

fervent cradle
#

oh okay thanks

olive fog
#

And I'm talking Tolkien/Martin/Jordan novels, not little paperbacks intended to be read on a flight :-) Huge storage is CHEAP and text is itty bitty!

celest gulch
#

I am trying to setup to basic events, on_member_join and on_member_leave. When leaving and joining the server with the bot my bot is not sending in the embeds that are stated.

Upon checking console no error or stack trace appears.

@bot.event
async def on_member_join(member):
    ch = bot.get_channel(1065333151632719977)
    joinem = discord.Embed(title=f"**{member.name} Joined!**", description=f"{member.name} Joined our server, welcome! :grin:")
    await ch.send(embed=joinem)
young bone
#

do you have intents?

#

and you also need on_guild_join for the bot

fervent cradle
#
import discord
from discord.ext import commands
PrizeEmbed=discord.Embed(title="quick test",description="testing")
class create(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command() 
    async def create(self,ctx):
        Input = await ctx.send(input(embed=PrizeEmbed))
        InputNew = await ctx.send(f"{Input}")
def setup(bot):
    bot.add_cog(create(bot))```  (first response) Nothing is  being sent, no error either
fervent cradle
dawn berry
#

I'm trying to start the bot coroutine using the .start() method, then once the bot has started, start a command line tool coroutine. However, when I create both tasks, the command line tool starts first and freezes the program waiting for an input. Any idea how I can make sure the bot coroutine starts fully before I start the command line tool?

#

the bot coroutine also freezes the program

dawn berry
#

I suspect it's because both are trying to access the terminal at the same time

gleaming falcon
#

Not directly pycord related, but perhaps might be the answer to my issue ...
I am posting to a webhook with a payload. I am intentionally doing some error testing by passing a bad embed field. I could've sworn that discord was more verbose about pointing out issues, but all I got was

{'embeds': ['0']}

How do I get better insight into issues? Pycord has a webhook client; would using that give me additional context?

crimson adder
#

A friend of me try to launch a discord bot, but when i launch the code, nothing happen. No error, if there's a print the content of the print appear, but the code just end ignoring the bot.run.

If someone know why. Wiggle

#

& the bot.run return none.

young bone
#

Can you show the pip list?

crimson adder
#

@opal geyser let you do it.

young bone
#

?

crimson adder
#

He's the friend who got the problem. x)

opal geyser
#

I copy-pasted the "Minimal Bot with Slash Commands" example here (https://docs.pycord.dev/en/stable/quickstart.html) and same problem : the program finishes immediatly...

young bone
#

what is the python version?

opal geyser
#

3.11.1

#

(I made a clean uninstall-reinstall of Python)

young bone
#

3.11 is fine with the version, mhm

sweet quiver
#

Hello everyone,
I'm trying to have, as answer to a slash command, a message including multiple select menus
So I have something like this basically as view,

class MyView(discord.ui.View):
  @discord.ui.select(...)
  async def callback_shape(self, select, interaction):
    ...

  @discord.ui.select(...)
  async def callback_color(self, select, interaction):
    ...

callback_shape gives me the selected shape
callback_color gives me the selected color

I'd like to have 'red' and 'triangle' available somewhere together
Is that possible, or I'm joust doing this the wrong way ?

young bone
#

do you have intents enabled at the website?

opal geyser
#

I tried with all intents disabled and enabled, nothing changes

young bone
#

you have to enable them

#

do you gonna use only slash commands?

opal geyser
#

yes, only slash

young bone
#

can you try discord.Bot()?

#

and remove the prefix stuff

opal geyser
#

sure, I also tried the closest I could be from the documentation example, and same result

young bone
#

the code is fine

opal geyser
#

mmh, it's on my end I guess

young bone
#

Can you try it with cmd?

opal geyser
#

yes

#

it works !

#

so it comes from my IDE, I use Pyzo

#

it's not VSCode haha ^^

young bone
#

I changed to PyCharm because it makes the stuff so much easier

opal geyser
#

Yes I think I'll reinstall it too
Thanks a lot for your help !

young bone
#

\o

fallow hawk
#

why arent button callbacks working? i'm using it correctly like this

            channel = self.bot.get_channel(1065374067898732555)
            buttonSeat = discord.ui.Button(label=f'Seat {num}', style=discord.ButtonStyle.blurple, emoji='🪑')
            async def buttonSeat_callback(interaction: discord.Interaction):
                full code here (cant send due to char limit)

            buttonSeat.callback = buttonSeat_callback
            view.add_item(buttonSeat)
        
        await channel.send(embed=embed, view=viewpoo)```
fallow hawk
neon raven
#

Trying out UI components for the first time, how do I defer and interaction and delay it for some minutes to process data? here is my code :

class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
    async def button_callback(self, button, interaction):
        await interaction.defer() # Defer the interaction
        time.sleep(1) # Sleep for 1 second
        embed = discord.Embed(title="Button clicked!", description="You clicked the button!") # Create an embed
        await interaction.response.send_message(embed= embed) # Send a message when the button is clicked
full basin
#

interaction.response.defer

#

And then you must use followups you can't use response.send_message

neon raven
#

Can you edit my code as an example?

full basin
#

No

proud mason
young bone
#

it will block the whole bot

proud mason
fallow hawk
#

oh ok

indigo badger
#

avatar_url is now avatar.url for the member object right?

silver moat
indigo badger
#

Also I am having trouble trying to find what emoji it is telling me is invalid as this is all it says.

#

Do you know what one it could be telling me.

young bone
indigo badger
indigo badger
indigo badger
#

Or anyone else know?

silver moat
#

The last one should be an issue. You are passing in a string for a custom emoji, as opposed to a discord.Emoji or discord.PartialEmoji object

indigo badger
silver moat
#

yes

indigo badger
#

So how would I make it work then? I have forgotten some things as it has been a bit since I coded?

silver moat
#

.rtfm discord.partialemoji

indigo badger
#

And where would I put that tho?

silver moat
#

in place of the emoji

indigo badger
#

So emoji= discord.partialemoji <emoji id here>?

#

Like that?

silver moat
indigo badger
silver moat
#

uhh no

indigo badger
#

And then the id part:

#

It wouldn’t?

silver moat
#

do you know basic python

indigo badger
#

Yes.

silver moat
#

ok, then why are you assigning a class attribute

#

to an argument

#

when the argument takes the class

light river
#

why do i get Can't keep up, shard ID None websocket is 10.6s behind.? i googled that it has to do with blocking events, but doesn't that send heartbeat blocked for more than X seconds?

silver moat
light river
#

what kind of code would cause the behind error tho

silver moat
#

But we can rule out Discord.

silver moat
indigo badger
#

Strange that it worked before but now it errors.

vapid pumice
#

I can't figure out what I'm doing wrong here. I'm getting no error, but the bot is not removing any nicknames.

@bot.slash_command()
@option("role")
async def removenicknames(ctx, role: discord.Role):

    for member in role.members:
        await member.edit(nick = None)

my intents:

intents = discord.Intents.all()
intents.members = True
intents.message_content = True
intents.presences = True

bot = discord.Bot(intents=intents)
#

Mmm...after print role.members I get nothing. Therein lies my issue

silver moat
vapid pumice
#

Seeming to be a permissions error...which is confusing considering intents are enabled, bot has admin, and other admin roles are being ignored.

#

I seem to have been inadequately skipping over users with higher perms. thumbsUp

silver moat
#

fun

vapid pumice
# silver moat fun

yea..I'm still really confused about that role.members interaction tho...

print(role.id) yields proper id so the object is being properly called in the option, but when I print role.members I get nothing - mind blown

silver moat
#

try to get the role from ctx.guild.roles

vapid pumice
#

Am I calling role.members inaccurately?
I can't seem to get a proper list with it for any role

therole = discord.utils.get(ctx.user.guild.roles, name="T1")
print(therole.members)
silver moat
#

hmm what about bot.guilds and then guild.roles

silver moat
vapid pumice
# silver moat hmm what about `bot.guilds` and then `guild.roles`

I tried really hard to figure out what you're suggesting by this, but I failed...
I don't get why the role is being properly input but role.members is not doing its thing 🥹

Are you suggesting that I need to try a for loop taking the desired guild from bot.guilds and then receiving the desired role from guild.roles and then receiving the desired list from said role? something like:

g = <guild id>
for g in bot.guilds:
        print(g.roles)
        for T1 in g.roles:
            print(T1.members)
static juniper
#

how to make a button

#

.rtfm discord.Button

vapid pumice
#

.rtfm intents

coarse spire
#

is there any way to fix this?

400 Bad Request (error code: 30032): Maximum number of application commands reached (100).

vapid pumice
#

Rate limiting stuffz :/

coarse spire
#

oh

#

so, it doesn't mean that I can't have more than 100 commands?

vapid pumice
coarse spire
#

ah, ok. Thanks 🙂

fringe socket
#

nope. you have to wait.

vapid pumice
#

Can someone confirm that my intents are not botched?

intents = discord.Intents.all()
intents.members = True
intents.message_content = True
intents.messages = True
bot = discord.Bot(intents=intents)

I'm getting an error that says
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientException: Intents.members must be enabled to use this.

fringe socket
#

are all the intents enabled in the panel

vapid pumice
#

Going check now! lolo.,l

vapid pumice
fringe socket
#

wait. change it to say this.

intents = discord.Intents.all()
bot = discord.Bot(intents=intents())
fringe socket
#

and if that doesnt work then this

intents = discord.Intents.all()
bot = discord.Bot(intents=intents)
#

did it work?

vapid pumice
#

and intents is not callable :/

vapid pumice
#

Such weird problems tonight 1sweat

coarse spire
#

I'm using this


client = discord.Bot(intents=intents)```

And it's working fine for me 🤔
vapid pumice
coarse spire
#

hmm... weird

fringe socket
#

get rid of the following:

intents.members = True
intents.message_content = True
intents.messages = True

you are trying to pass intents twice

vapid pumice
fringe socket
#

are there any tracebacks?

#

and are you getting any othet erros?

vapid pumice
vapid pumice
#

Agghh, what an L...
I think I have my persistant view bot setup such that it overrides my commands...

fringe socket
#

💀 I'm going to pretend I know what you mean.

vapid pumice
static juniper
#

how to make discord button

fervent cradle
fringe socket
#

yes lol

ornate current
#
e = None

@bot.event
async def on_ready():
  e = "hi"

@bot.command()
async def printHI(ctx):
  print(e)```
#

this prints none

#

why is that

proud mason
#

Use bot vars if you want to retain values across functions

#

?tag botvar

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

ornate current
#

thanks!

proud mason
#

Careful with the names tho

ornate current
#

yeah i will

#

so when I am using tasks.loop ctrl + c does not stop the bot, any fixes?

#

when i remove the taskName.start() from the on_ready event ctrl + c works just fine

merry briar
#

How can I make a beautiful field in embed? So that everything would be on the contrary

#

there it gets out of bounds and it is already unclear

static juniper
#

how to hide the embed color bar like this

frank shale
#

Change the color the same as the embed

limber urchin
merry briar
limber urchin
loud sail
#

@commands.Cog.listener()
    async def on_member_join(self, member):
        channel = await self.bot.fetch_channel(1039573169968787567)


        await channel.send('test', view=WelcomeButton())

Anyone knows, why the command isn't work?

limber urchin
#

Saying "isn't work" is useless, explain what's wrong

loud sail
loud sail
limber urchin
loud sail
limber urchin
#

Do you have them enabled in the code too?

loud sail
formal field
#

Hey, i'm using a basic bot with slash commands and ctx.send works but ctx.respond is giving this error, does anyone know what could be causing this?

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.

olive fog
# young bone ?tag idw

That is never helpful or even anything but agitating to folks. At the very least, change the bot-spam to explain that users should specify their Python version, use of IDE, IDE version, and preferably provide the snippet of code that generates the error. Also you specifically are way too quick to resort to idw. You did it to me a couple of days ago when I DID post the code and the mysterious results of it.

#

@formal field Another user had that same question last night. You're taking too long to send your reply to the Discord Interaction itself. You have 3 seconds to give it any reply at all, unless you defer it, and if you defer it then you have 3 minutes to put in a followup.

formal field
#

Understood, thank you very much. I'll give that a try now.

olive fog
formal field
#

Managed to get it working this way:

@bot.slash_command()
async def download(ctx, url:str):
    await ctx.respond("Downloading video, please wait.")
    await asyncio.ensure_future(download_video(url, ctx))```

Thanks again for the help
young bone
#

for shash commands use ctx.defer()

olive fog
#

@formal field It makes more sense to send the response before doing the paperwork on it, unless it relies on data processing to form that response.

formal field
#

Hm, seems a bit different to asyncio.ensure_future, i'll see if i can find anything in the docs

  File "/usr/local/lib/python3.10/dist-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: InteractionResponse.defer() takes 1 positional argument but 2 were given```
formal field
young bone
#

dont put anything in the ()

formal field
#

Tried that, it's giving:

  File "/usr/local/lib/python3.10/dist-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before
young bone
#

its should look like this```py
await ctx.respond()
await ctx.defer()
await download_video(url, ctx)
.
.

olive fog
#

I think you should use ctx.respond() to give the "downloading" status update, but then you need to hand off to something else entirely. The error shown above indicates that you have to pick between respond and defer.

#

The something else should be a separate coroutine which does the download and reports back to the invoker via a new message to server

formal field
#

Hmm i see

#

I'll give that a try

olive fog
#
async def download(ctx, url: str):
    await ctx.respond("Downloading video, please wait.")
    await do_download(ctx.guild.id, ctx.channel.id, ctx.message.author.id, url)

async def do_download(guild_id: int, channel_id: int, user_id: int, url: str):
    #
    # Download your file from wherever
    #

    user: discord.User = await bot.fetch_user(user_id)
    guild: discord.Guild = await bot.fetch_guild(guild_id)
    channel: discord.abc.Messageable = guild.get_channel(channel_id)
    async def do_download(guild_id: int, channel_id: int, user_id: int, url: str):
    #
    # Download your file from wherever
    #

    user: discord.User = await bot.fetch_user(user_id)
    guild: discord.Guild = await bot.fetch_guild(guild_id)
    channel: discord.abc.Messageable = guild.get_channel(channel_id)
    await channel.send(
        content=f"{user.mention} Your file is ready!",
        file=discord.File(
            fp="local/path/to/downloaded/file",
            filename="User-Friendly Name To Send With Message"
        )
    )
#

I did not run this, but I believe this is the droid you're looking for.

Edit: About an hour after posting I noticed an error in PyCharm. The file parameter can't just be a filename, it must be an instance of discord.File. Fixed that!

#

@formal field

formal field
#

thank you very much, will implement it

fervent cradle
#

import discord
from discord.ext import commands
PrizeEmbed=discord.Embed(title="What do you want to giveaway?",description="")
class create(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
class Req(discord.ui.View): 
    @discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌") 
    async def button_callback(self, button, interaction):
            await interaction.response.send_message("This is where giveaway gets made")
    @discord.ui.button(label="I would like to add some reqs", style=discord.ButtonStyle.primary, emoji="✅")
    async def button_callback(self,button,interaction):
        await interaction.response.send_message("yes")
    @commands.command() 
    async def create(self,ctx):
        EmbedMsg = await ctx.send(embed=PrizeEmbed)
        PrizeInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"How long would you like the giveaway for {PrizeInput} to last?")
        LengthInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"How many winners should their be for this giveaway?")
        WinnersInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"Should their be any requirments for this giveaway?",view=Req())
       
def setup(bot):
    bot.add_cog(create(bot))
``` "Command create was not found" worked fine before adding buttons?
young bone
#

pls use the py if you create the code blocks

fervent cradle
#

so whats the issue, im so confused

olive fog
#

@fervent cradle Not sure how you can be at a beginner's skill level and not use an IDE that annoyingly whines about PEP8/formatting errors. May I suggest PyCharm Community Edition? It should not only help you format things so most Python programmers can read it intuitively, but it should also complain about errors like this one before you try to run the program.

fervent cradle
olive fog
#

And it doesn't tell you how many spaces to put between the end of one class block and the start of another, or between function defs?

#

It took me quite a few reads before I figured out that your class and its method are both lowercased 'create'

#

So bot.add_cog(create.create(bot))

#

Just saying. It'd be nice if you'd help folks who want to help you.

proud mason
proud mason
#

Use PascalCase for class names

olive fog
proud mason
#

Yes ik. I'm telling that to FoolishBlue

#

I should ping him tbh

proud mason
#

Oh wait more issues

olive fog
# proud mason Use PascalCase for class names

I'm actually quite annoyed by PyCharm/PEP8 wanting me to use lower_case_style instead of camelCase for function arguments and variables, but I go with it because it makes the code more readable for folks who don't program in umpteen lingos.

proud mason
proud mason
olive fog
proud mason
#

Oh

#

I've only used C in school so that only had basic stuff kek

proud mason
proud mason
fervent cradle
#
import discord
from discord.ext import commands
PrizeEmbed=discord.Embed(title="What do you want to giveaway?",description="")
class Req(discord.ui.View): 
    @discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌") 
    async def button_callback(self, button, interaction):
            await interaction.response.send_message("This is where giveaway gets made")
    @discord.ui.button(label="I would like to add some reqs", style=discord.ButtonStyle.primary, emoji="✅")
    async def button_callback(self,button,interaction):
        await interaction.response.send_message("yes")
class create(commands.Cog):
    def __init__(self, bot):
        self.bot = bot``` better?
olive fog
#

@fervent cradle What The Om Nom Nom is saying is that I missed the 2nd class definition.

fervent cradle
#

o

proud mason
# loud sail member intent correct?

Yes member and guild both. Does the cog load? Add a print statement in the cog init
Does the event fire? Check that with a print statement too

olive fog
#

That may be just my experience, but it derives my methodology.

fervent cradle
loud sail
proud mason
#

Ctx.guild ctx.author and ctx.channel are guaranteed to be present in a Slash cmd from what i remember. Unless it isn't a Slash cmd (i didn't check)

If you are worried about the cache, you should use partial objects rather than fetching them if you just want to send a message

proud mason
olive fog
proud mason
fervent cradle
loud sail
#

How can I send another context or message?

await channel.send(file=discord.File("willkommen.png"), view=WelcomeButton())
young bone
#

await channel.send()

#

;3

loud sail
#

i mean, this should be one message

young bone
#

"text"?

fervent cradle
fervent cradle
# proud mason Yes but both buttons can't have same callback class name. Also, where is the cmd...

Im getting this when trying to put the users input in a message.


 @commands.command() 
    async def create(self,ctx):
        EmbedMsg = await ctx.send(embed=PrizeEmbed)
        PrizeInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"How long would you like the giveaway for {PrizeInput} to last?")
        LengthInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"How many winners should their be for this giveaway?")
        WinnersInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"Should their be any requirments for this giveaway?",view=Req())```
proud mason
proud mason
proud mason
#

.rtfm message.content

fervent cradle
#

ty

proud mason
boreal dust
#

a.k.a "Test" has to be first.

fervent cradle
#

Yeah i know thats what id normaly do, but i just added it there so he knew roughly what to do, sorry for any confusion

boreal dust
#

What do you need to do?

#

Or is the issue fixed? 💀

fervent cradle
#

?

boreal dust
#

Ah nvm

fervent cradle
# winter condor

Are their any examples of this? Im still struggling to see how id use it.

limber urchin
#

What do you need an example for? You got a message object and access the content attribute from it

fervent cradle
#

Im just struggling to see what i do with it, & where

limber urchin
#

well what are you trying to do?

fervent cradle
#

I want to have the users input, in the next message if that makes sense

proud mason
limber urchin
#

Yeah? Send the content of your message object in your message

fervent cradle
limber urchin
#

I think you've been told like 10 times to learn Python before making a bot, right?

fervent cradle
#

I know python well enough to create what i am creating

limber urchin
#

Mhm, sure

fervent cradle
#

Got it working

proud mason
#

Btw @limber urchin can you make a tag for xy problems ||i think dpy has one if you wanna steal||

proud mason
#

Thanks

limber urchin
obtuse juncoBOT
#

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

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

olive fog
#

That's a good one.

woven gulch
#

Is there a way to get the raw json of on_message?

limber urchin
#

raw json?

young bone
#

you mean just a json file?

woven gulch
#

I want to serialize all messages and events into JSON so I can ingest them into Elasticsearch

young bone
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

  • SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
  • MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
  • PostgreSQL (Very popular and robust SQL based database management system)
  • MySQL (Another popular SQL based system, good start for learning SQL)
limber urchin
#

You only get a message object with on_message. There is no json involved

woven gulch
#

I know I want to turn that message into an NDJSON so I can ingest it later into elastic

still helm
#

What´s the maximum time of the delete_after parameter? I did not find anything about it in the documentation

woven gulch
#

So each message is a line of JSON

limber urchin
young bone
#

or 5 minutes, im not sure anymore

still helm
#

ah ok i understand

woven gulch
#

Cursed regex it is for parsing then

#
    async def on_message(self, message: discord.Message):
        logging.info(f'Message from {message.author} (ID: {message.author.id}) in {message.channel} attachments {message.attachments} '
                     f'mentions {message.mentions}: {message.content}')
limber urchin
#

You also need to specify in your privacy policy that you're logging messages, as it's against ToS to store any data that you don't actually need

proud mason
green hinge
#

Can anyone tell me why I always get the "application not responding" message?
The embed is still displayed but I don't know why I always get the "Application not responding" message....

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

    @commands.Cog.listener()
    async def on_ready(self):
        self.bot.add_view(TicketButton())
        self.bot.add_view(CloseButton())

    @slash_command(description="Erstellen eines Support Tickets")
    @commands.has_permissions(administrator=True)
    async def createticket(self, ctx):

        channel_id = TICKET_CHANNEL_ID

        ticket_embed = discord.Embed(title=f'Herzlich Willkommen beim Support!',
                                     description=f"""Wenn du ein Support Ticket eröffnen möchtest drücke bitte auf den "📩 Ticket erstellen" Button!
                                                  \nEin Supportmitarbeiter wird sich anschließend schnellstmöglich um dein Ticket kümmern und sich mit dir in Verbindung setzen!""",
                                     color=ORANGE)
        ticket_embed.set_thumbnail(url=f"{ctx.guild.icon}")

        await self.bot.get_channel(channel_id).send(embed=ticket_embed, view=TicketButton())

def setup(bot):
    bot.add_cog(ButtonTicketCog(bot))```
limber urchin
#

Because you're not responding to the command

young bone
green hinge
#

Okay so I'll just change this line:

await self.bot.get_channel(channel_id).send(embed=ticket_embed, view=TicketButton()) ```
In this:
```py
await ctx.respond(embed=ticket_embed, view=TicketButton())```?
young bone
#

you know what they are doing?

olive fog
#

@green hinge I recently had the same problem. On the Discord Developer page, where you set up your App or Bot, there are a lot of demands for "a redirect URL" which is just confusing language. If you're on the first item, there are several of those demands which are OPTIONAL, and should all be blank if you're using a library like py-cord, because they redirect Discord messages from the WebSocket aka Gateway API to the HTTP aka REST API.

#

The only redirect URL you should fill in is on the OAUTH2 config page

green hinge
# young bone you know what they are doing?

The first one always sends the embed to the channel with the channel_id. So in this case TICKET_CHANNEL_ID.
And in the second case the embed is always sent to the channel where the slash command is executed or do I have something wrong?

young bone
#

so you could just send a message like that the ticked was created

green hinge
#

Also, can I somehow use ctx.respond to send the message only to a specific channel at a time?

limber urchin
green hinge
proud mason
limber urchin
#

Yeah, that looks like an AI trying to respond to a question lol

proud mason
#

Lmao

young bone
#

^

proud mason
#

Is that a user self bot trying to help?

limber urchin
#

lmao

green hinge
gray peak
green hinge
#

How can I fix the error in this case without sending a message?

        create_channel = await interaction.guild.create_text_channel(
            u'\U0001F4CB-{}'.format(interaction.user.name), overwrites=overwrites, category=category)

        embed = discord.Embed(title=f'Herzlich Willkommen beim Support!',
                              description=f"""Hallo {interaction.user.mention}!
                                                                         \nDein Ticket wurde erfolgreich erstellt! Schreibe dein Anliegen in den Chat und warte bis sich ein {admin_role.mention} oder {mod_role.mention} bei dir meldet.
                                                                         \nUm das Ticket zu schließen drücke bitte auf den Button 🔒 Schließen""",
                              color=ORANGE)

        msg = await create_channel.send(embed=embed, view=CloseButton())```
limber urchin
#

what?

olive fog
green hinge
#

When I click the button from the created embed I also get "This interaction failed" but my new room is created anyway....

class TicketButton(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label='Ticket erstellen', custom_id="TicketErstellen", style=discord.ButtonStyle.secondary,
                       emoji='📩')
    async def callback(self, button, interaction):
        user = interaction.user
        admin_role = discord.utils.get(interaction.guild.roles, id=ADMIN_ROLE)
        mod_role = discord.utils.get(interaction.guild.roles, id=MOD_ROLE)
        category = discord.utils.get(interaction.guild.categories, id=TICKET_CATEGORY)

        overwrites = {
            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            user: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True),
            admin_role: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True),
            mod_role: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True)
        }

        create_channel = await interaction.guild.create_text_channel(
            u'\U0001F4CB-{}'.format(interaction.user.name), overwrites=overwrites, category=category)

        embed = discord.Embed(title=f'Herzlich Willkommen beim Support!',
                              description=f"""Hallo {interaction.user.mention}!
                                                                         \nDein Ticket wurde erfolgreich erstellt! Schreibe dein Anliegen in den Chat und warte bis sich ein {admin_role.mention} oder {mod_role.mention} bei dir meldet.
                                                                         \nUm das Ticket zu schließen drücke bitte auf den Button 🔒 Schließen""",
                              color=ORANGE)

        msg = await create_channel.send(embed=embed, view=CloseButton())```
young bone
#

you are not responding to the button

green hinge
#

How can I do that?

young bone
#

you do it with the interaction

green hinge
#

What can I put behind here so I don't have to send a message or anything?
interaction.response.

young bone
#

You have to send a message

green hinge
#

I can use this:

        await create_channel.send(embed=embed, view=CloseButton())
        await interaction.response.edit_message(view=self)``` 
? 😄
fervent cradle
#

Does discord store the users messages (aka accessing how many they've sent)? or do i need a db

#

Any idea?

#

If i set something up on on_message to add a message to user every message, then stored in a database would that work?

fervent cradle
young bone
gleaming falcon
#

I'm trying to access the response message (that is, the message the bot sends after a user invokes a command)

My understanding is that it's interaction.original_response(), but I'm getting Unknown webhook. What fundamental thing am I missing?

class SentinalConfirmation(discord.ui.View):
    def __init__(self, sentinel: SentinelTimelockRequest, callback: callable):
        super().__init__(timeout=300, disable_on_timeout=True)

        self.callback = callback
        self.sentinel = sentinel

        self.add_item(EventSelect(sentinel))

    # [...snip...]

class EventSelect(discord.ui.Select):
    def __init__(self, sentinel: SentinelTimelockRequest):
        self.sentinel = sentinel
        
        super().__init__(
          ...
        )

    async def callback(self, interaction: discord.Interaction):
        """ This is failing """
        msg = await interaction.original_response()  # type: discord.Message
        embed = msg.embeds[0]
        embed.fields[2] = '\n'.join(self.values)

        self.sentinel.conditions = self.values

        await interaction.response.edit_message(embed=embed)
fervent cradle
#

Anyway to get a users total message count?

fervent cradle
gleaming falcon
full basin
#

You're asking twice

fervent cradle
gleaming falcon
#

I could, yes. But this is a separate, potentially-easier question for people to answer, versus the specific thread that many people may not care to visit. Don't overthink it.

fervent cradle
#

please

full basin
#

.rtfm Member.history

winter condorBOT
full basin
#

Flatten it

#

Then check len

fervent cradle
#

Much appreictaed, should i then store the amount i get back from that in a DB or without be fine?

green hinge
#

Can I run a loop only every 60 days?

@tasks.loop(seconds=60)```
full basin
#

¯_(ツ)_/¯

#

Up to you

full basin
fervent cradle
green hinge
#

I think the maximum is every 24 hours or?

#

Or can I extrapolate the hours to 60 days and do it that way?

@tasks.loop(hours=1440)```
gleaming falcon
gleaming falcon
#

More general Select questions (not a crosspost 😉 )

When selecting values in a Select and drop focus, it submits the value, which then appears to refresh the UI item.

Is there a way to retain the context of the selected options so that they still have the check mark next to them?

meager heron
#

https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_application_command

How can I use this to create a mention to a group command? I've tried:

bot.get_application_command("group command").mention

I also tried setting type to discord.commands.SlashCommandGroup

#

(When I use the mention, it just displays the command name in plain text, not as a link)

worn void
#
...
    @discord.ui.select(
        custom_id="app_dropdown",
        placeholder = "Choose the position to apply into!",
        min_values = 1,
        max_values = 1,
        options = [
            discord.SelectOption(
                label="Option 1",
                description=""
            ),
            discord.SelectOption(
                label="Option 2",
                description=""
            ),
            discord.SelectOption(
                label="Option 3",
                description=""
            )
        ]
    )
    async def select_callback(self, select, interaction):
        await interaction.response.send_modal(TeamAppModal(title=f"Apply to the team."))

class TeamAppModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="question 1"))
        self.add_item(discord.ui.InputText(label="question 2", style=discord.InputTextStyle.long))
        self.add_item(discord.ui.InputText(label="question 3"))

    async def callback(self, interaction: discord.Interaction):
        selection = "" # <<< Make this the "label" selected in the dropdown.
        embed=discord.Embed(title=f"{selection} Application")
        embed.set_author(name=f"{interaction.user}", icon_url=interaction.user.avatar.url)
        embed.add_field(name="question 1", value=self.children[0].value, inline=False)
        embed.add_field(name="question 2", value=self.children[1].value, inline=False)
        embed.add_field(name="question 3", value=self.children[2].value, inline=False)
        await interaction.response.send_message(embed=embed)
...

Can I get the value they picked in the dropdown and pass it to the embed title?
selection = "" # <<< Make this the "label" selected in the dropdown.

meager heron
#

Just pass the selection as an argument to the modal's constructor and use it from there

worn void
#

class TeamAppModal(arg, discord.ui.Modal): like this?

meager heron
#
def __init__(self, selection, *args, **kwargs):
  self.selection = selection
  ...

Then use self.selection wherever you want in the modal

worn void
#

ah ok

worn void
#

just

meager heron
#

Get the selection in your select_callback and pass it with TeamAppModal(selection, title="...")

worn void
#

await interaction.response.send_modal(TeamAppModal(title=f"Apply to the team.", selection=selection))

#

yeah