#Basic Pycord Help (Quick Questions Only)

1 messages · Page 13 of 1

fiery tiger
#

yes but how can i set them to default

#

is it possible? or i have to create a channel for that

cyan quail
#

just select an existing channel

smoky forge
#

when you set ur guild to community you have to specify those two

#

it can either create one for you or select an existing one

cyan quail
#

not sure if the api will let you do the former

fiery tiger
cyan quail
#

then just create the channels on the fly...?

#

guild.create_text_channel

fiery tiger
#

yeh will do it

#

ty

smoky forge
#

would it be good to make it so if community is set to True but rules and updates channels aren't specified to create ones like discord does?

cyan quail
#

looking at the api it's not clear if that's actually possible

#

i wouldn't be surprised if the UI makes separate channel creation requests for that before editing the guild

fiery tiger
#

I was able to make it so the channels will get deleted after guild community is being set to false

cyan quail
#

why are you even toggling community

fiery tiger
#

1 sec

#

Well, this can be toggled if u want it or not. it's for extra security. Up to the guild owner

#

any of those can be enabled / disabled

cyan quail
#

but why disable it at all

#

what security is it providing

fiery tiger
#

well there's a bypass

#

nukers will create channels using guild community

#

turning on - off will just spam channels inside the guild

#

which is dumb but sadly this is what happens

cyan quail
#

there's a very high chance there's a ratelimit on that though

fiery tiger
#

yes but till they get ratelimited.... also imagine nuking with multiple bots

#

confusion is what they mostly like lol

cyan quail
#

no, guild-wide ratelimit

fiery tiger
#

well idk but a lot of people tested my bot with it. I was surprised at first idk how they do that

#

but luckly i found a way to fix it

cyan quail
#

fair enough i guess

fiery tiger
cyan quail
#

though

#

wouldn't the nuker very easily be able to kick the bot

fiery tiger
fiery tiger
cyan quail
#

then why doesn't the bot just ban the nuker(s)

fiery tiger
#

In case they move it after it won't be the bot fault

fiery tiger
#

if something doesn't happen

cyan quail
#

isn't that the entire point of antinuke

fiery tiger
cyan quail
#

scanning actions and determining if someone is acting maliciously

fiery tiger
#

if something happens what the bot will do is just back up everything changed by the non trusted member

#

yep that's what it does basically

#

it will also ban the non-trusted member

#

once something happens by a non trusted member (can be bot) -> ban the non trusted member -> replace everything back

#

i turned it on. what the bot did was to turn it off then delete the channels

#

@cyan quail I've done what u told me. Using create_text_channel

cyan quail
#

nice

gritty pond
#

How do i get invite link data from on_member_join

dry echo
#

not possible

gritty pond
#

i mean invite link code/owner

prisma flicker
#

You have to query all the invites and see which one increased in count

gritty pond
#

):

gritty pond
golden lake
#

so whats up with pycord sometimes returning truncated log lines

#

it seems to happen when a rate limit is encountered

#

im seeing api calls fail, and its not being reported through the framework as an exception

#

for example, the log line will say its retrying, and then

DELETE https://discord.com/api/v10/channels/.../messages/.../reactions/ave
rify%3A.../... has received
#

without the error code actually being there

#

also, when i navigate through my terminal theres some weird display shit going on as if there are ctrl characters in there that it doesnt like

#

this has been a thing for like.. as long as ive used pycord, which has been idk >6 months

#

anyone know something about it or?

#

seems like it ought to be a known issue by now

#

hm maybe i should post this in #discussion

prisma flicker
prisma flicker
golden lake
#

it wasnt a big deal at first but im starting to get more users and shit is breaking as a result

#

should i not rely on the built in rate limiter?

#

i seem to recall seeing a lot of pycord projects handling rate limiting themselves

prisma flicker
#

Are you logging weird strings with control characters?

golden lake
#

not that i am aware of lol

#

maybe there are weird strings in some of the message contents it prints to debug

#

perhaps thats the culprit for that bit

#

im not actually sure if this is just a display bug and the return code would be there if not for this

#

but also, this problem is correlated with api call failures so id like

#

expect to see a traceback if i didnt handle an exception its throwing due to rate limiting correctly

#

but im not

#

and im only catching Forbidden in that call, not HTTPException

#

i dont even know what pycord throws if it gives up retrying

#

id imagine it shouldnt, since the discord gateway just tells it to progessively back off

#

and yet, these calls never complete

#

gtg. ping me if u have an idea

obtuse juncoBOT
#

dynoError No tag localization found.

full basin
#

The has_permissions decorator still works

cyan quail
#

^ all decorators from ext.commands also work with slash commands

#

just note these are all internal and won't hide them on discord's end; the user will still be able to see and "run" the command, but the bot will raise CheckFailure as always

smoky forge
#

you can use the @default_permissions() decorator that, by default, hides the command to those who don't have certain permissions. Using the ext.commands @has_permissions() is gonna make your command visible, but CheckFailure (i think) is gonna be raised when the user doesn't have enough permissions.

meager heron
#

I'm trying to deploy my bot using v2.0.1, and I'm getting the following error on startup:

          File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/pages/__init__.py", line 10, in <module>
            from .pagination import *
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 27, in <module>
            from discord.ext.bridge import BridgeContext
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/bridge/__init__.py", line 26, in <module>
            from .bot import *
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/bridge/bot.py", line 32, in <module>
            from .context import BridgeApplicationContext, BridgeExtContext
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/bridge/context.py", line 28, in <module>
            from discord.commands import ApplicationContext
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/commands/__init__.py", line 26, in <module>
            from .context import *
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/commands/context.py", line 69, in <module>
            class ApplicationContext(discord.abc.Messageable):
          File "/app/.heroku/python/lib/python3.10/site-packages/discord/commands/context.py", line 319, in ApplicationContext
            @discord.utils.copy_doc(Interaction.edit_original_message)
        AttributeError: type object 'Interaction' has no attribute 'edit_original_message'. Did you mean: 'edit_original_response'?```
meager heron
#

discord.py doesn't even have ext/pages/pagination.py

#

Nor ext/bridge

silver moat
meager heron
#
boto3==1.24.36
fastapi==0.78.0
flatdict==4.0.1
markdown==3.3.7
motor==3.0.0
numpy==1.23.1
Pillow==9.2.0
pymongo[srv]==4.2.0
python-dotenv==0.20.0
statcord.py==3.1.0
topggpy==1.4.0
uvicorn==0.18.2
validators==0.20.0
py-cord==2.0.1
meager heron
#

(I've been doing this for months)

silver moat
#

consider using github version of topggpy

errant craneBOT
#

requirements.txt line 1

discord.py```
silver moat
meager heron
#

Very gross that they just had a versionless requirement

silver moat
#

¯_(ツ)_/¯

errant craneBOT
#

requirements.txt line 1

aiohttp>=3.6.0,<3.9.0```
gentle flare
#

Hey how do I send a message to s specific guild? I want to send the message with the help of my guild id. Can someone help me?

silver moat
#
guild = bot.get_guild(id)
guild = await bot.fetch_guild(id)
gentle flare
#

ah thx

fervent cradle
#

How do i get amount of server bots?

ionic snow
#

Hey I need a hand here, I looked up pycord docs about select menus and I didn't find anything about subclassing Select to create a custom Select Menu, anyone has a good tutorial regarding creating Select Menus while subclassing Select

hearty mauve
#

How do i use datetime to show a users time in their timezone

cyan quail
cyan quail
cyan quail
#

subclassing isn't a must btw, use whatever method you wish

ionic snow
prisma flicker
hearty mauve
#

What?

ionic snow
cyan quail
#

you have to edit the view again after setting disabled=True

ionic snow
#

So I need to pass the view to the new class in order to edit it?

cyan quail
#

kind of

ionic snow
#

Yeah because I'm using multiple select menus

cyan quail
#

i don't think it'll include the original callbacks though, but it'd be fine if the view will remain disabled

#

oh wait

cyan quail
#

i.e. self.view

ionic snow
#

Thanks, I'll check

hearty mauve
cyan quail
#

oh if it's in the footer then set embed.timestamp instead

hearty mauve
#

Huh?

cyan quail
#

what

hearty mauve
#

embed.timestamp(text"discord.utils.utcnow()")?

#

@cyan quail

cyan quail
#

no

#

embed.timestamp = ...

#

providing a datetime object

#

or as you said discord.utils.utcnow()

hearty mauve
#

embed.timestamp = discord.utils.utcnow()

#

?

#

Im so confused rn

cyan quail
hearty mauve
#

Lmao

prisma flicker
#
embed = discord.Embed(title="hello")
embed.timestamp = discord.utils.utcnow()
await ctx.send(embed=embed)```
hearty mauve
#

But i want it with my footer, i dont want it to take over

prisma flicker
cyan quail
#

literally

#

try it

#

and you'll see what it does

prisma flicker
#

it doesn't replace it lmao

hearty mauve
#

Ok

#

Thanks

#

Ya learn sum new everyday

fervent cradle
#

How can my bot use another bot slash_command

cyan quail
#

it can't

hearty mauve
#
@client.command(aliases=["av"])
async def avatar(ctx, member: discord.Member = None):
  if not ctx.author.bot:
      if member == None:
          member = ctx.author
  embed = discord.Embed(title=f"", color=0x2F3136)
  embed.set_author(name=f"{member}'s Avatar", icon_url=f"{member.avatar_url}")
  embed.set_image(url=f"{member.avatar_url}")
  await ctx.reply(embed=embed)
``` ok im having an issue with this command
cyan quail
#

avatar.url

hearty mauve
#

Ok

fervent cradle
#

hey, is there a way to have a callback for paginators to say that for example they cant click on it

#

oh nevermind

golden wadi
#

How can i add permissions to slash group? ik that there is default_member_permissions but i cant understand how to use it with groups

cyan quail
#

nearly

#

you use permissions with kwargs

#

like discord.Permissions(administrator=True, manage_roles=True, ban_members=True, ...) and so on

#

so you just pass in as much as you want there

golden wadi
#

it finally works. thanks!

cyan quail
#

allgood

full basin
#

commands.Bot

#

commands.Bot supports prefix commands and slash commands.

coral kindle
#

How can i detect when my bot has been added to other guild

fervent cradle
bronze vector
fervent cradle
#

where bot 👀 unless i did prefix wrong

bronze vector
#

dead

fervent cradle
copper dew
#

press f to pay respects

rigid sable
#

How do I set permissions for slash cmds?

prisma flicker
young bone
coral kindle
#
bot.slash_command(name='test')
async def test(ctx):
    if ctx.author.guild_permissions.administrator:
        ctx.respond('test')```
real stirrup
#

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
what im trying to do: await channel.send("example")
unless I set the bots role to admin this error occurs

full basin
#

Missing Access comes from application commands

#

Didn't invite the bot with the application.commands scope

fervent cradle
#
    async def userinfo(self, ctx, member: discord.Member = None):
        if member == None:
            member = ctx.author
        if member == "":
            member = ctx.author
        embed = discord.Embed(title="User Information", color=0x8eabf7, timestamp=ctx.message.created_at)
        embed.set_thumbnail(url=ctx.guild.icon_url)
        embed.add_field(name="User ID", value="**`%s`**" % (member.id), inline=False)
        embed.add_field(name="Name", value="**`%s`**" % (member.display_name), inline=False)
        embed.add_field(name="Discriminator", value="**`%s`**" % (member.discriminator), inline=False)
        embed.add_field(name="Creation Date", value="**`%s`**" % (member.created_at.strftime("%a, %d %B %Y, %I:%M %p")), inline=False)
        embed.add_field(name="Bot Check", value="**`%s`**" % (member.bot), inline=False)
        embed.set_thumbnail(url=member.avatar_url)
        await ctx.send(embed=embed)
real stirrup
fervent cradle
fiery tiger
#

How can i check if 'COMMUNITY' is in before guild features but not in after guild features

real stirrup
fervent cradle
#

    @commands.hybrid_command(
        name="userinfo",
         description="Userinfo basically Lol",
         aliases=["ui"]
    )

    @checks.not_blacklisted()
    async def userinfo(self, ctx, member: discord.Member = None):
        if member == None:
            member = ctx.author
        if member == "":
            member = ctx.author
        embed = discord.Embed(title="User Information", color=0x8eabf7, timestamp=ctx.message.created_at)
        embed.set_thumbnail(url=ctx.guild.icon_url)
        embed.add_field(name="User ID", value="**`%s`**" % (member.id), inline=False)
        embed.add_field(name="Name", value="**`%s`**" % (member.display_name), inline=False)
        embed.add_field(name="Discriminator", value="**`%s`**" % (member.discriminator), inline=False)
        embed.add_field(name="Creation Date", value="**`%s`**" % (member.created_at.strftime("%a, %d %B %Y, %I:%M %p")), inline=False)
        embed.add_field(name="Bot Check", value="**`%s`**" % (member.bot), inline=False)
        embed.set_thumbnail(url=member.avatar_url)
        await ctx.send(embed=embed)
 
real stirrup
fervent cradle
#

it lets you

#

use / and normal prefix

#

the decorator is not the issue

rigid sable
#

?tag example

obtuse juncoBOT
#

dynoError No tag example found.

errant craneBOT
#

Here's the slash perms example.

rigid sable
#

Also, in my commands (slash), I don't add the ctx : discord.ApplicationContext thing but it still works

#

what is the reason for adding that?

dry echo
harsh dust
#

I'm so confused
I'm running my bot with slash commands for the first time on another script and it works for like a minute and then the commands just disappear

#

like this:

rigid sable
harsh dust
#

Idk what is there to show?

dry echo
harsh dust
#
intents = discord.Intents().default()
setattr(intents, "members", True)
bot = commands.Bot(command_prefix=['qt!', 'QT!'], intents=intents, help_command=None)
dry echo
#

and your slash commands?

harsh dust
#

there's hundreds

dry echo
#

show one or two

#

and how you initialize all

harsh dust
#

each command has this as its decorator

@commands.slash_command(guild_ids=NONE_TYPE)
#

NONE_TYPE is None

#

idk theres nothing to show with the slash commands

#

they all work fine

dry echo
#

remove the whole arg or change it two a list of ids

harsh dust
#

yeah but you need the presence intent for that right?

#

to specificy a guild_id

dry echo
#

no

#

just if a member updates a avatar or something

harsh dust
#

so it worked, Questify had the Slash Commands badge which means it worked

#

but then after like 30 seconds

#

i try repeating the last command using the up arrow and now it can't access it anymore

#

and questify's slash commands badge is gone

#

same issue with guild_ids=None

#

and also idk why but my on_ready function is being called like a solid 3 minutes after all the cogs are loaded which makes no sense

dry echo
#

without any code i cant help you....

round aspen
#

Hi there, I'm making a bot for a client and they keep getting this error which is stopping the bot from actually registering the slash commands

round aspen
#

most of the slash commands are in cogs folders as well

dry echo
#

the ones where you use inputs

#

@round aspen

round aspen
#
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role('Staff')
    async def create_giveaway(self, ctx: discord.ApplicationContext, 
    name: Option(str, "The name of the giveaway")):

        """Create a new giveaway (Staff Only) | Usage: esw create_giveaway <name of the giveaway>"""
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role('Staff')
    async def announce_giveaway(self, ctx: discord.ApplicationContext, 
    winners: Option(int, "The number of winners to announce (Default: 1)", required=False, default=1)):
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role('Staff')
    async def delete_giveaway(self, ctx: discord.ApplicationContext):
        
        """Delete the current giveaway (Staff Only) | Usage: /delete_giveaway"""
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role('Staff')
    async def csv(self, ctx: discord.ApplicationContext):

        """Returns a CSV(Excel-like file) with the current giveaway's user data (Staff Only) | Usage: /csw"""
#

ignore the indent with between the two decorators

#

@dry echo

dry echo
round aspen
#

wait nvm

#

my bad

#
@commands.slash_command(guild_ids=guildIDs)
    async def balance(self, ctx: discord.ApplicationContext, 
    user: Option(discord.Member, "The user whose balance you want to check.", required=False)=None):
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role('Staff')
    async def remove(self, ctx: discord.ApplicationContext, 
        points: Option(int, "The amount of points to remove."), 
        user: Option(discord.Member, "The user to remove points from.")):
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role("Staff")
    async def add(self, ctx: discord.ApplicationContext, 
        points: Option(int, "The amount of points to add on."), 
        user: Option(discord.Member, "The user to give points to.")):
#

would it be bc of the balance cmd?

dry echo
#

remove the none and use default=None

#

@round aspen works?

round aspen
harsh dust
# dry echo without any code i cant help you....

yeah so I tested with a brand new file with just one command from an example and it's doing the same thing..

tokenfile = open('token.txt')
token = tokenfile.read().strip()
tokenfile.close()

bot = discord.Bot(debug_guilds=[763520052484898886])  # specify the guild IDs in debug_guilds

# since global slash commands can take up to an hour to register,
# we need to limit the guilds for testing purposes

@bot.command(description="Sends the bot's latency.")  # this decorator makes a slash command
async def ping(ctx):  # a slash command will be created with the name "ping"
    await ctx.respond(f"Pong! Latency is {bot.latency}")

@bot.event
async def on_ready():
    print(f"Logged in » {bot.user.name} | {bot.user.id}")

print("Running")

bot.run(token)
#

is there some sort of debug mode for py-cord that i can enable

#

or is this a discord issue

#

because i'm lost lol

proud pagoda
harsh dust
#

I do

#

One that currently is running with text commands and this instance which is on my PC to test slash commands

cyan quail
#

don't run multiple instances at once

harsh dust
#

oh, i saw a stackoverflow thing saying it was okay to do so i thought it would be fine

cyan quail
#

*maybe* before slash commands existed but it generally isn't recommended regardless

proud pagoda
#

Yeah with slash commands it can get really screwed up

harsh dust
#

i see

proud pagoda
#

I've had this exact issue before, when I had a message command running on the beta version of the bot and not on the prod version

#

Every time I started the beta, the command would only be able to run once and then it would just disappear

#

So its highly recommended to use a separate bot during development and the actual bot for production

harsh dust
#

Yeah I do, I just wanted to test with the main bot because it's a verified bot and a little different to the testing bot

cyan quail
#

ah you didn't get intents i guess

harsh dust
#

i have the server members intent, that's it

proud pagoda
harsh dust
#

Fair enough

meager heron
#

Should I care at all about a 40ms difference in ping? (Using slash commands.) Comparing a couple of different VPS providers

cyan quail
#

ehh pretty negligible

copper dew
#

dont think it's going to cause a major difference

stuck kite
#

Is there a API wrapper function that will take a jpeg file and upload it into an embed, I see a method for using a URL but nothing for uploading from the hosted computer.

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

guild.me doesn't work in overwrites after pressing button

dry echo
#

Show code

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

    @discord.ui.button(emoji='📩', label='Создать тикет', style=discord.ButtonStyle.grey, custom_id="create_ticket")
    async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message(f'Тикет создаётся...', ephemeral=True)
        overwrites = {
            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            interaction.guild.me: discord.PermissionOverwrite(read_messages=True)
        }

        ch = await interaction.guild.create_text_channel(name=f'{interaction.user.name}-тикет', overwrites=overwrites,
                                                         reason=f'Тикет открыт {interaction.user} (ID: {interaction.user.id})')
        
dry echo
#

What exactly doesnt work?

fervent cradle
#

user doesn't see channel

dry echo
#

view_channel=True

fervent cradle
dry echo
#

Sorry, without the s at the end

prisma flicker
#

Your code only lets the bot see the channel

#

If you want the user it's interaction.user

dry echo
#

guild.me is the bot not the owner of the bot

fervent cradle
#

ahh

dawn gyro
#

Does this happen for anyone else with
commands.HelpCommand

dry echo
#

Is this your full code?

dawn gyro
dry echo
#

Remove the return

dawn gyro
night cargo
#

How do I make an AutoCompleteContext

dawn gyro
#

HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

#

but it did send hi

dry echo
#

What is self.context?

#

Have you defined it or is it form the super()

#

Try to send the string

dawn gyro
dawn gyro
dry echo
#

Send the string then

dawn gyro
dry echo
#

idk much about the help commands sorry

round rivet
#

you should return the value to be sent I believe

dry echo
tiny wagon
#

how can i start a game activity like chess in vc from pycord??

errant craneBOT
#
|coro|

A shortcut method that creates an instant activity invite.

You must have the :attr:`~discord.Permissions.start_embedded_activities` permission to
do this.

Parameters
------------
activity: Union[:class:`discord.EmbeddedActivity`, :class:`int`]
    The activity to create an invite for which can be an application id as well.
max_age: :class:`int`
    How long the invite should last in seconds. If it's 0 then the invite
    doesn't expire. Defaults to ``0``.
max_uses: :class:`int`
    How many uses the invite could be used for. If it's 0 then there
    are unlimited uses. Defaults to ``0``.
temporary: :class:`bool`
    Denotes that the invite grants temporary membership
    (i.e. they get kicked after they disconnect). Defaults to ``False``.
unique: :class:`bool`
    Indicates if a unique invite URL should be created. Defaults to True.
    If this is set to ``False`` then it will return a previously created
    invite.
reason: Optional[:class:`str`]
    The reason for creating this invite. Shows up on the audit log.


Raises
-------
TypeError
    If the activity is not a valid activity or application id.
~discord.HTTPException
    Invite creation failed.

Returns
--------
:class:`~discord.Invite`
    The invite that was created.```
smoky forge
#

remember discord wont verify bots that give access to embedded activities

smoky forge
#

i do think this statement is odd bc there's one bot thats verified and its entire thing is that it gives access to activities

sick lake
#

How to check if the bot is tagged?

dry echo
olive acorn
#

Hey Guys what's the latest version of Pycord?

round rivet
coral kindle
#

how can i check ping and bot uptime

round rivet
#

for uptime just store the current time when the bot starts

#

and compare to later time

dry echo
round rivet
#

Yes

sick lake
#

Alright, thankyou!

harsh dust
#

Hey, so I'm moving my bot to slash commands but I want users to know about this change so I need to keep it so it can still read messages beginning with the command prefix.
I have the server members intent which is fine but the message content intent I don't. Do I need to enable the message_content intent manually for it to work?

intents = discord.Intents().default()
intents.members = True
# intents.message_content = True
bot = commands.Bot(command_prefix=['qt!', 'QT!'], intents=intents, help_command=None)
#

Idk because I'm pretty sure I tried enabling it yesterday but an error occured saying I don't have access to the intent

round rivet
#

yeah you'd need message content intents

#

you can also downgrade to api v9

#

#library-updates message

harsh dust
#

Ah ok

round rivet
#

where message content intents are not yet required

#

but will be in like 9 days

harsh dust
#

yeah

#

so if i switch to api v9 for now do i need to switch back to v10 on the 1st of september or will it still work fine

cyan quail
harsh dust
#

gotcha

coral kindle
#

how can i send message to specific channel

dry echo
#

create channel obj and then channel.send() readTheDocs

coral kindle
#

what

harsh dust
#

wtf

#

so my bot is working, the slash commands are there but all of them apart from the ones with slash command groups ??

#

is it because they take a while to load?

flat merlin
#

My bot randomly stopped responding to commands. Has anything changed about the Discord API? When I first installed Py-cord version 2.0.1, everything worked just fine. Yesterday it completely stopped replying to commands. Even the old version, the exact one that worked two days ago.

harsh dust
#

this is one of them
main.py

bot.groups = Placeholder()
bot.groups.completions = SlashCommandGroup("completions", "View Individual Quest Completions")

overview.py

def setup(bot):

    class Overview(commands.Cog):
        completions = bot.groups.completions

        @completions.command(name="general", guild_ids=NONE_TYPE)
        async def general_completions(self, ctx: discord.ApplicationContext,
                                      username: Option(str, "A valid Minecraft username or UUID", default="", required=False):
            """View General individual quest completions"""
            await getOverview(self.bot, ctx, "General", username, mode="completions")
fervent cradle
flat merlin
#

I've tried both.

flat merlin
#

Indeed, something unexpected changed.

#

Now I've got a new problem: which intent do I need to enable to create a channel? I don't want to enable all of them, so it doesn't receive tons of information it doesn't need.

#

It's a private channel, and it's trying to add specific users to it.

flat merlin
#

Yes, and I don't know when it has changed, and why it stopped working overnight.

#

I can't find what I'm looking for on that page.

cyan quail
#

what are you looking for then

#

if you're trying to work with guilds then surely you want the guilds intent

flat merlin
#

I've got the guilds intent enabled.

cyan quail
#

then what's the issue

flat merlin
#
Traceback (most recent call last):
  File "/home/whiskey/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 184, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/whiskey/Desktop/0.37/cogs/dungeons.py", line 65, in enter_dungeon
    dungeon_channel = await cat.create_text_channel(name=dungeon[1] + " - " + ctx.author.name, overwrites=overwrites)
  File "/home/whiskey/.local/lib/python3.8/site-packages/discord/channel.py", line 2077, in create_text_channel
    return await self.guild.create_text_channel(name, category=self, **options)
  File "/home/whiskey/.local/lib/python3.8/site-packages/discord/guild.py", line 1205, in create_text_channel
    data = await self._create_channel(
  File "/home/whiskey/.local/lib/python3.8/site-packages/discord/guild.py", line 1086, in _create_channel
    "id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'
cyan quail
#

just as a test, can you enable the members intent?

flat merlin
#

I've found this, but I don't want to enable strictly all intents.

#

I've already got the members intent enabled.

#

messages=True, message_content=True, members=True, typing=False, presences=False, guilds=True, reactions=True

cyan quail
#

or rather, show the overwrites object you passed in

flat merlin
#

overwrites = {
    ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
    bot_role: discord.PermissionOverwrite(read_messages=True),
    ctx.author: discord.PermissionOverwrite(read_messages=True),
    ctx.guild.owner: discord.PermissionOverwrite(read_messages=True)
}```
#

It used to work.

cyan quail
#

can you show what happens if you print all the keys there?

#

at least one of them resolved to None

celest lichen
#

i'm porting my bot over from using psycopg2 to asyncpg so it runs faster - does asyncpg not require committing changes? my connection object doesn't have a .commit method so

flat merlin
#

🤔

#

Thanks, dude. That role doesn't seem to exist.

cyan quail
#

allgood

#

generally better to get the role by ID if you think it may change names

flat merlin
#

That was correct, I changed the role name to the new one, and it works again.

#

I agree with that, but isn't the role id different if the bot is in a different server?

celest lichen
cyan quail
#

fair enough, but guild has a bot_role attribute i think anyway

celest lichen
#

very much still getting the hang of asyncio - it's very confusing compared to everything else i've done in python lol

cyan quail
#

guild.self_role

flat merlin
#

Interesting. 🤔

#

Thanks, that'll work better.

cyan quail
#

do note this isn't guaranteed to exist either though

#

e.g. someone invites the bot without permissions=...

#

may be best to validate that all the roles exist before putting it into overwrites (or conversely remove all None keys after)

flat merlin
#

Does guild.self_role return None if it doesn't exist?

cyan quail
#

yes

flat merlin
#

Thanks.

celest lichen
#

this is the func i'm using to create my db pool - the if/else is so i can run the db locally when i'm changing stuff on my pc - how do i make it so my 'conn' var is visible to my commands outside of create_db_pool itself? am i missing something really basic here

flat merlin
#

Global variable. 🤔

#

I created the connection globally, outside any function, and I can use it anywhere.

celest lichen
#

oh right hahaha

#

i sort of thought having the variable inside a function like this made it less resource intensive

#

i have this down at the bottom of my fle

flat merlin
#

You can create a global variable within a function too.

full basin
#

or return it and set it as a bot attribute?

celest lichen
#

so something like this?

#

i also read in the docs that putting my db queries outside of a .transaction thingy means they just autocommit - what's the advantage of committing with the async with bot.db.transaction() then?

gentle flare
#

Hey I want to use discord.ext.bridge for my commands but I have @commands.has_permission() in my code. How do I use has_permission with .bridge?
Can someone help me?

prisma flicker
gentle flare
#

no
My Code:

@bridge.has_permissions(administrator=True)

Error:

AttributeError: module 'discord.ext.bridge' has no attribute 'has_permissions'
#

But in the guide it says that bridge can do everything that commands can do

#

So thats why Im wondering if I did something wrong.

prisma flicker
gentle flare
#

I needed to make my commands all lowercase and now It works with

@client.bridge_command()
@commands.has_permissions()
#

Buts thats something thats wrong in the guide

#

I think Im going to add that later

prisma flicker
#

nice

near hollow
#
from bot import Bot
import discord
from discord.ext import commands
from discord.ext.tasks import loop


class Notifier(Cog):
    def __init__(self, bot: Bot) -> None:
        super().__init__()
        self.bot = bot
        self.test.start()


    @loop(minutes=30)
    async def test(self):
        print("test")



def setup(bot):
    bot.add_cog(Notifier(bot))```

The cog loads fine according to console but nothing loads and it doesn't print anything
#

All other cogs work fine with commands and what nots. Just this one doesn't load

prisma flicker
#

add store=False to load_extension

gentle flare
#

Ok now I have a different problem.
I can send the command with the helps of /
and it sends the message
but I get an error that the Application cant react

prisma flicker
gentle flare
#

this is the code

prisma flicker
#

yes change it to ctx.respond

gentle flare
#

ok do I need to do that with every message that is send from a command now?

prisma flicker
#

yes

near hollow
fervent cradle
#

Hey, I want to register a command for one guild only, but it gets registert in every guild. Is there anything wrong with it?

fervent cradle
gleaming falcon
#

If I simply have a discord.User (e.g. from an on_user_update event), what's the best way to ban them?

proud pagoda
meager mica
#

i was wondering how i can make a group command in cogs

#

group slash command that is

#

nvm i manually used class

gleaming falcon
lapis quarry
#

I'm having trouble tagging a role. I send the role ID in a message in the angle brackets like this <@&role_id> but the role does not get tagged (I don't do it within an embed).

#

It does result in the role name getting displayed, so I know the ID is correct, it just doesn't tag users with that role.

dry echo
#

Possible to hide Slash commands completly for users?

prisma flicker
prime remnant
#

@commands.has_permissions

prisma flicker
prime remnant
#

@commands.has_permissions(administrator=True)

lapis quarry
prime remnant
#

how to make a message about a new person who entered the server from the bot's discord be written to a specific channel welcome on all servers but not by id channel

prisma flicker
neat temple
#

Im trying to handle the error for discord.errors.CheckFailure, but when implementing the following code, it still shows the exception. How can I get it to not raise any exceptions?

@bot.check
async def checkBlacklisted(ctx):
    if not isNotBlacklisted(ctx):
        await HandleBlacklistError(ctx)
        return False
    return True

@bot.event
async def on_command_error(ctx, error):
    pass
tulip bobcat
#

is the timeout for views reset after an interaction?
And if yes, how can I change that?

neat temple
#

update: I was able to make it work. It wasnt "on_command_error", it was "on_application_command_error"

fervent cradle
#

Is there some sort of way to catch errors with failed connection?
In pycord

like a on_error for on_ready or on_connection?

In NodeJS client.login("token")---
.catch(err() => does the thing.

tulip bobcat
#

look at the message above

silver moat
fervent cradle
silver moat
#

np

fervent cradle
celest lichen
#

are there any good tutorials for working with asyncpg and pycord?? i just cannot figure out how it works at all lol

tulip bobcat
silver moat
silver moat
prisma flicker
wind thunder
#

is there title

#

kwarg in Embed.add_field?

fervent cradle
proud pagoda
proud pagoda
cyan quail
#

or if you're not subclassing, @bot.event

fervent cradle
hearty mauve
#

Im using these two files and the second file won't work when i ping, but there is no error

verbal gulch
#

what does this error means? ```py
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1041, in on_connect
await self.sync_commands()
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 628, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 473, in register_commands
desynced = await self.get_desynced_commands(guild_id=guild_id, prefetched=prefetched_commands)
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 321, in get_desynced_commands
elif _check_command(cmd, match):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 256, in _check_command
as_dict = cmd.to_dict()
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 765, in to_dict
"options": [o.to_dict() for o in self.options],
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 765, in <listcomp>
"options": [o.to_dict() for o in self.options],
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\options.py", line 246, in to_dict
"type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'

dim flicker
#

how to make a check in the select menu, what exactly was selected by the user? To give out a specific role

proud pagoda
proud pagoda
proud pagoda
tulip bobcat
#

not as far as I know

cyan quail
#

well... the bot has to be in the server at the very minimum

#

the best you could do is manually grab the emote and upload it to a private server with the bot or something

round aspen
# dry echo <@316288809216245762> works?
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 1041, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 643, in sync_commands
    registered_guild_commands[guild_id] = await self.register_commands(
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 517, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 517, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 765, in to_dict
    "options": [o.to_dict() for o in self.options],
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 765, in <listcomp>
    "options": [o.to_dict() for o in self.options],
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/options.py", line 246, in to_dict
    "type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
Esports Wales Bot#3449 has connected in Discord!```
cyan quail
#

uhhh

#

it'd have to be an actual emoji

#

you can't just throw images into description

#

no

#

is there a particular reason you're trying to use an emoji the bot can't access?

#

surely you could just upload it yourself

rose lynx
#

anyone getting AttributeError: 'Object' object has no attribute 'get_thread' when making a thread? either from a message or not

cyan quail
#

if you see it on your client you can usually just right click it and open the image

rose lynx
# cyan quail show code and full error

just a stub atm

async def post(channel):
    '''A'''
    # empty
    question = await pop()

    if question:
        await channel.create_thread(name=question, auto_archive_duration=60 * 24)
    else:
        # role mention
        await channel.send('I am out of questions')
Unhandled exception in internal background task 'post_question'.
Traceback (most recent call last):
  File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "/Users/kyle/Code/nexbot/bot.py", line 31, in post_question
    await post(channel)
  File "/Users/kyle/Code/nexbot/library/questions.py", line 28, in post
    await channel.create_thread(name=question, auto_archive_duration=60 * 24)
  File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/channel.py", line 799, in create_thread
    return Thread(guild=self.guild, state=self._state, data=data)
  File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/threads.py", line 160, in __init__
    self._from_data(data)
  File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/threads.py", line 190, in _from_data
    if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False):
AttributeError: 'Object' object has no attribute 'get_thread'
cyan quail
#

do you have the guild's intent enabled?

#

guild typically fallsback on discord.Object if it wasn't recieved for some reason

rose lynx
#

the server members intent?

cyan quail
#

guilds

#

if you're using at least intents.default then you will have it

rose lynx
#

the intents should be the default

#

bot = discord.Bot()

cyan quail
#

the latter

#

a: being animated

rose lynx
#

so i didn't pass anything to the intents property in construction so that would use the default intents?

cyan quail
#

yeah it should be

#

what happens if you print channel.guild

rose lynx
#

sec

#

prints <Object id=255161337116622850>

#

possible bug is im using the channel straight from a bot.fetch_channel() call and not via a guild

#
@tasks.loop(hours=24)
async def post_question():
    '''A'''
    snowflake = 941697109227356180
    channel = await bot.fetch_channel(snowflake)
    print(channel.guild)
    await post(channel)
cyan quail
#

strictly speaking that shouldn't have an effect but yeah try get_channel without the await

fervent cradle
#

I am facing into slash commands not showing up.
I Imported with the applications.command flag and the cog file works on a different bot...
hmm, anyone knows what shit has to be turned on so commands show up. I doubt that I am missing out on anything.

import discord
from discord import Option, OptionChoice
from discord.commands import slash_command
from discord.ext import commands


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

    @slash_command(guild_ids=get.config("gid"), description="Runtime Information")
    async def testv(self, ctx):
        await ctx.respond('test')


def setup(bot):
    bot.add_cog(Responsive(bot))

this is the slash command

"loaded via" via

for filename in listdir("./cogs"):
    if filename.endswith(".py"):
        bot.load_extension(f"cogs.{filename[:-3]}")
rose lynx
#

ty

proud mason
#

That will only run before the first iteration iirc

proud pagoda
hearty mauve
#

I dont know much about pycord

proud pagoda
#

Functions and classes are python things, not just pycord things

round aspen
# cyan quail what's your new code
@commands.slash_command(guild_ids=guildIDs)
    async def balance(self, ctx: discord.ApplicationContext, 
    user: Option(discord.Member, "The user whose balance you want to check.", required=False, default=None)):
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role('Staff')
    async def remove(self, ctx: discord.ApplicationContext, 
        points: Option(int, "The amount of points to remove."), 
        user: Option(discord.Member, "The user to remove points from.")):
@commands.slash_command(guild_ids=guildIDs)
    @commands.has_role("Staff")
    async def add(self, ctx: discord.ApplicationContext, 
        points: Option(int, "The amount of points to add on."), 
        user: Option(discord.Member, "The user to give points to.")):
#

#998272089343668364 message

everything here except balanxe which was changed as above

hearty mauve
hearty mauve
#

In the prefix section

proud pagoda
#

?tag learnpython

obtuse juncoBOT
#

We're glad to help where we can, but come with at least a basic understanding of Python.

Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/

Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers

Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)

round aspen
#

or @commands.slash_command if its cogd

#

cogs*

fiery tiger
#

@cyan quail finally back home

#

life change hahaa

hearty mauve
meager mica
#

hey guys so i was trying to add bool paramater

#

async def join(self, ctx: discord.ApplicationContext, button_enabled: Option(bool)):

#

i also tried buttton_disabled: bool but it ownt show up

fervent cradle
#

Hello, whats wrong with the code?

            modal = ticket_modal(title="Question")
            await interaction.response.send_message(modal)

Error:
TypeError: Modal.__init__() missing 1 required keyword-only argument: 'title'

Discord issue:
<load.ticketsystem.ticket_modal object at 0x00000143C5C2E440>

smoky forge
#

did you pass in the kwargs in the classes' super()?

#
class ticket_modal(Modal):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    ...

fervent cradle
#

ye

#
class ticket_modal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
smoky forge
#

try taking out *args

fervent cradle
#

okay

fiery tiger
fervent cradle
fiery tiger
#

i restarted vsc, why is this happening

smoky forge
#

could you try defining the title in the super()

#

instead of when initializing the class

fervent cradle
#
    super().__init__(title="Question", *args, **kwargs)
TypeError: discord.ui.modal.Modal.__init__() got multiple values for keyword argument 'title'

```Mhmmm.. :((
smoky forge
#

did you take out the title parameter in the class initialization

fervent cradle
smoky forge
#

not you

#

i have no idea what your error is

fervent cradle
#

😦

#

Oh ups i have see the error hehe i have found now the error thanks

meager mica
silver moat
#

what is a group command

fiery tiger
#

but not if i run it via poetry

meager mica
#

but i figured it out

#

i just made it normal then put it back and i fixed itself

#

but another questionnow how do i make button not timeout i but it in @discord.ui.button but it said it waas unexpected

errant craneBOT
#

Here's the persistent example.

meager mica
#

oh thanks

harsh dust
#

idk why but with some of my slash commands that have an attachment and a view that disappears 5 minutes after the command is sent, shortly after the images are disappearing from the api resulting in them not loading

#

and sometimes its fine

cyan quail
fervent cradle
#

is there a way to reload cogs with the use of slash commands?

gentle flare
#

Hey I want to use PostgreSQL as my database. What libary should I use to work with psql?

cyan quail
cyan quail
gentle flare
#

Ok thx I didnt find anything in the guide so I asked here. Thx

harsh dust
iron halo
#

when i start my bot sometimes it just doesnt reply to slash commands for like 10 seconds to a minute

#

is that discord fault

undone smelt
#

is discord.ApplicationContext.send_response() the same as discord.ApplicationContext.respond() ?

errant craneBOT
#

Here's the context menus example.

meager mica
#

So when getting user that clicked button do I put in button decorator interaction.user

#

Or is that person that caused button to be sent

celest lichen
#

trying to clean up my main.py by porting a load of my stuff to cogs - i'm quite new to using classes and stuff. why is my emoji_catch func being treated as undefined in the listener just below its definition?

#

ah - i think i fixed it by changing to await Emoji.emoji_catch

#

please forgive my spaghetti code lol

prisma flicker
meager mica
#

Idk what you mean

celest lichen
#

anyone know why i'm getting this ??

#

tried changing it to an f-string like this

#

now i get this instead

prisma flicker
#

Why would you put interaction.user in the decorator

meager mica
#

i meant in the function below the decorater

#

but it seems to work now

gleaming falcon
#

I remember seeing a screenshot where you could pass multiple values to an argument directly into a slash command. Anyone know if that's an actual thing, or mockup/future functionality? Couldn't find any examples that used it

e.g. /mycmd opt1: A, B and both A and B were accessible in a list or something.

prisma flicker
#

I really want that but for mentions

cyan quail
#

or alternatively because this is such a popular request people were happily making mockups already

#

it might have also been them just using a string option since you can still technically mention and such in those, then parse it yourself after

gleaming falcon
#

The screenshot was an example where two autocomplete options were added like you would on a tag cloud. But if it's not a real thing, then no sense trying to dig it up. heh

Would definitely be great to be able to pass multiple arguments, though. Hopefully in the future, as you said.

stuck kite
#

How can I send a pagination command to a specific channel that wasn't in the interaction or context of where the user initiated the command?

stuck kite
# dry echo channel.send() ??

hmmm not sure how to make channel.send work with pagination. This is the command I am sending await paginator.send(target=channel) Where channel is a text channel object

dry echo
#

oh i see

#

you could send a message into another channel grab the object and pass it in reference or target ig

stuck kite
rotund current
#

Quick question. I am starting to learn pyCord, but it seems that even the quickstart for slash commands is out of date, or at least the commands are not functioning as intended for me. Is this a known issue, or do I have an issue with my library install?

#

For example bot = discord.Bot() doesn't work. Looking around, I tried bot = commands.Bot, and while I can get the on_ready event to trigger, I can't seem to get any @bot.command() to function

narrow moss
#

how can I set timeout to none in an View class

vital blade
#

for non persistent views

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

and thats how u set timeout to None in a persistent view

copper dew
fervent cradle
#

hi I tried makin a reload command for cogs within a slash command but apparently it only works with prefixed commands, is there any way to use bot.reload_extension in slash commands?

nocturne canopy
#

hallo can a bot read the content of a message the user replied to with the bot's prefix? if so how?

#

it'd also be helpful if it could find and read the latest message in chat, excluding the command message. i'm trying to make a translation thingy btw

muted pulsar
muted pulsar
harsh dust
muted pulsar
muted pulsar
#

just gotta dive deep into the attribute bog to find the exact thing you're looking for

nocturne canopy
#

oh it wouldn't read it if the message above was sent by the same person, right? it could instead see if the message starts with its prefix

muted pulsar
#

i'm having problems understanding your request

#

it would be best if you wrote an example of what's happening in the chat

#
User A: bonjour
User B: /translate command on the previous message
Bot: "Hello"
#

like this

#

as long as the user B uses "reply" in his command, it should be relatively easy to find the initial message

nocturne canopy
#

pretty much. have it default to the message above if the user is not replying to another message if possible

muted pulsar
#

if he does not and you want to look for the previous message

#

then you want to take ctx.message.id

#

and do the for loop

#

and check for message.id == the previous message variable

#

and when it's true, you take the next message in the list and translate it

#

sometimes that doesn't work and you have to use textchannel.fetch_message(id)

#

if you want it to work both ways, you'd need to do an if check

#

and check if context has a reply to somebody attribute

nocturne canopy
#

yeah that'd work. the arguments taken can be changed with it too i assume. for example, if the user is not replying to a message, take a quoted text argument as the string to translate, then the source and destination languages

muted pulsar
#

the world is your oyster

bitter lotus
#

I have error like this

``` when i try run modal by select menus
Modal is runing by this code:
```await interaction.response.send_message(viev=Modalconfident())```
#

Someone know why?

nocturne canopy
#

i figured out the argument priority i want, that being the input text, output language, and input language, all being optional. though i can't wrap my head around detecting if only language arguments were passed. would it be smarter (or the only possible option) to have it skip the text if a dot or some other character is passed in its place?

dry echo
bitter lotus
bitter lotus
#

working thx

gleaming falcon
frank yew
#

What is the command to see how all the Discord.colors look in discord?

nocturne canopy
muted pulsar
#

context menu is not really slash

nocturne canopy
#

they work on mobile also, right?

muted pulsar
#
@bot.message_command(name="Translate") 
async def get_message_id(ctx, message: discord.Message): 
    await ctx.respond(translate(message.content))
#

this is boilerplate for your stuff

#

just create the translate function

nocturne canopy
#

i should've mentioned i'm using googletrans

muted pulsar
#

doesn't really matter

#

this is just boilerplate to take the message and return the result of translation upon it

#

whatever happens in the function has no bearing on the workings of this

nocturne canopy
#

so you mean putting the logic in that new function

muted pulsar
#

btw

#

if you want the translation to be visible only to the person who used the command

#

which, i assume, would ease the flow of the dialogue

#

use await ctx.respond(translate(message.content), ephemeral=True)

#

ephemeral makes the message be only visible to the person who called the command

sinful pivot
#

I'm getting "This Interaction Failed" but I actually edit the message with a new view and change the content. How could I fix this without sending another message? (I've also tried to send a new message with the view but that won't work)

full basin
#

How are you editing the message

proud pagoda
sinful pivot
proud pagoda
#

Great

#

Do you guys have any ideas on how to hide some data within a message

#

pretty much, i have a persistent view which needs to know the id of something so that it can get the data from the database when the user responds

#

Now, if the bot hasn't been rebooted yet, I can just pass the data in when making the view so it doesn't have to query the db

#

But otherwise, I need to know the unique ID so that I can get it from the db

#

So are there any ways to hide that within a message?

fervent cradle
#

I am facing into slash commands not showing up.
I Invited with the applications.command flag and the cog file works on a different bot...
hmm, anyone knows what shit has to be turned on so commands show up. I doubt that I am missing out on anything.

import discord
from discord import Option, OptionChoice
from discord.commands import slash_command
from discord.ext import commands


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

    @slash_command(guild_ids=get.config("gid"), description="Runtime Information")
    async def testv(self, ctx):
        await ctx.respond('test')


def setup(bot):
    bot.add_cog(Responsive(bot))

this is the slash command

"loaded via" via

for filename in listdir("./cogs"):
    if filename.endswith(".py"):
        bot.load_extension(f"cogs.{filename[:-3]}")
fervent cradle
proud pagoda
round rivet
#

add store=False to load_extension

fervent cradle
proud pagoda
# fervent cradle get?

You wrote this:

@slash_command(guild_ids=get.config("gid"), description="Runtime Information")
#

So where is get.config defined

fervent cradle
proud pagoda
#

Alright

#

Then add store=False to load_extension like plun said

fervent cradle
#

I added it ^

proud pagoda
proud pagoda
fervent cradle
#

JUst left it away from the example because it looks weird.

proud pagoda
#

But I would recommend just adding store=False to load_extension because it also prevents other bugs from being overlooked

fervent cradle
proud pagoda
#

Did it cause any errors to be raised?

fervent cradle
#

nope

#

Also changed guild_ids, in this case: guild_ids=[123456790]
123456790 is the server ID

proud pagoda
#

Try adding this to the Responsive class:

@commands.Cog.listener()
async def on_ready(self):
  print("Responsive cog is online")
proud pagoda
fervent cradle
#

yep it prints

Responsive cog is online

proud pagoda
#

Are you sure that you're running the command in the correct guild?

fervent cradle
#

It still doesn't appear.
I am sure I followed everything.
Invited bot with bots and application.commands and (administrator) flag.
channel allows application commands.

#

I am in only 3 guilds lmao

#

this, my server I am testing it and a different server.

proud pagoda
#

Ok

fervent cradle
#

and the guild I run it from has the bot + i checked the guild id and it equals to it.

proud pagoda
#

Try kicking and reinviting the bot to see if that does anything

proud pagoda
#

Ok

fervent cradle
#

and then i reinivited with all the necessary flags (bots, application.commands) and I gave it administrator flag.

gleaming falcon
gleaming falcon
#

The only other way I could see it working is if you saved a reference to the message/interaction internally

proud pagoda
#

Yeah, except I don't really want to do that so...

#

I think I'm just not gonna make it a persistent view

fervent cradle
#

So I guess my problem seems to be weird

#

I gave my friend the token who has a pycord bot and his slash commands appear on my bot..
Well on my site, nothing works... hmm

proud pagoda
#

That's strange

fervent cradle
#

the get also works, i am printing what its returning [9129492481]

cyan quail
prisma flicker
slender abyss
#

im trying to catch slash commands from bots but idk how to
nothing is printed on the console

slender abyss
slender abyss
#

yeah

cyan quail
#

not possible

slender abyss
#

why?

cyan quail
#

because interactions are only between the client and discord

#

they aren't broadcast to everyone

slender abyss
#

so i can get the interaction from message of the bot right as my bot is private bot

cyan quail
#

messages themselves don't contain interaction data

slender abyss
#

message.interaction?

cyan quail
#

that indeed exists, however if im not mistaken that isn't actually from the message and instead compiled elsewhere

slender abyss
#

let me try

cyan quail
#

my mistake, it is a part of the message; you could use message.interaction.data

#

but regarding command info, it will only include the command name

proud pagoda
#

Also, I realized I don't really need the view to be persistent so I just decided not to make it persistent

slender abyss
cyan quail
#

nop

slender abyss
#

oof

fervent cradle
#

hey guys! is there a specific indent to getting a channel object from a guild object? I'm using intents = discord.Intents.guilds rn

#

would await self.client.get_channel(id).send(embed=embed)

#

work

near hollow
near hollow
fervent cradle
near hollow
#

Does it error?

fervent cradle
fervent cradle
#

since its none

near hollow
#

Are you sure that id is a valid channel id?

prisma flicker
fervent cradle
fervent cradle
prisma flicker
#

I don't think there's a client.fetch_channel

near hollow
#

Hmmmm. Wouldn’t it just be relaxing get_ channel with fetch_channel ?

fervent cradle
#

does this look right

prisma flicker
#

yep

#

await on the fetch

fervent cradle
#

ah kk

meager mica
#

does pycord have modals i cant find example

prisma flicker
#

yes

errant craneBOT
#

Here's the modal dialogs example.

meager mica
#

oh dialogs

#

ty

celest lichen
#

when i register a command in a cog with @commands.command(), is that a prefixed command or a slash command? or both?

dry echo
#

prefix

fervent cradle
#

works!

#

ty guys

celest lichen
near hollow
#

@safe inlet_command()

Is just slash commands in cogs

celest lichen
#

ahhhhh

near hollow
#

Uf welp

#

You get the point lol

celest lichen
#

i'm looking at the docs for cogs - no mention made of slash commands

#

it just says "Every command is marked with the commands.command() decorator."

dry echo
errant craneBOT
#

Here's the slash cog example.

prisma flicker
#

@celest lichen try this example ^

celest lichen
#

thank you :)

proud pagoda
#

Is it possible to use buttons within ephemeral messages?

#

Cuz I keep getting an interaction failed error on Discord's end

dry echo
#

Yes you can

#

I used them

proud pagoda
#

Alright thanks for the confirmation

dry echo
proud pagoda
#

Yes please

dry echo
#

Wait a min

dry echo
# proud pagoda Yes please
@slash_command()
async def foo(self, ctx) -> discord.Embed:
    embed = discord.Embed() #your stuff
    await ctx.respond(embed=embed, view=MyClass(), ephemeral=True)

class MyClass(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=None)

    @discord.ui.button(label="Idk", style=discord.ButtonStyle.red)
    async def callback(self, button: discord.ui.Button, interaction: discord.Interaction):
        embed = discord.Embed(title=f"blabla", color=self.embed_color)
        embed.set_footer(text=f"ID: {interaction.user.id}", icon_url=interaction.user.display_avatar.url)
        embed.timestamp = datetime.now()
        await interaction.response.send_message(embed=embed, ephemeral=True)
proud pagoda
#

Ok thanks

fervent cradle
#

Anyone knows why reload_extension won't work from within a slash command

proud pagoda
#

Here's what my code looks like:

# Reload cogs manually
    @dev_commands.command(
        name="reload",
        description="Reload an extension",
    )
    async def reload(
        self,
        ctx: discord.ApplicationContext, 
        extension: discord.Option(str, "The filename of the extension to reload")
    ):
        self.bot.reload_extension(f'cogs.{extension}')
        await ctx.respond(f"Reloaded **{extension}**")
fervent cradle
#

oh no, i meant slash commands

#

not prefixed commands

proud pagoda
#

That's a slash command

#

Within a slahs command group

meager mica
#

hey sso it my first time using modals and select menus but i cant figure out options heres my options code options=[discord.SelectOption(label='Red', value='Red Team', description='You Choose red team')] but i get error Ignoring exception in view <Join_Enabled timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Join event' emoji=None row=None>: Traceback (most recent call last): File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task await item.callback(interaction) File "/home/david/Documents/GitHub/creator-lazer-tag/cogs/message.py", line 55, in confirm_callback modal=MyModal(title="Link to Minecraft") File "/home/david/Documents/GitHub/creator-lazer-tag/cogs/message.py", line 14, in __init__ super().__init__( File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 57, in __init__ self._weights = _ModalWeights(self._children) File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 260, in __init__ children = sorted(children, key=key) File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 259, in <lambda> key = lambda i: sys.maxsize if i.row is None else i.row AttributeError: 'function' object has no attribute 'row'

fervent cradle
proud pagoda
#

Yep

celest lichen
#

i have a function that i use in a couple of different listeners that checks if a message is emoji-only. it's in a cog i have for this called emoji.py. so i in my Emoji class i have my async def emoji_catch(self, msg), and then listeners for on_message and on_message_edit and stuff. when i try to call my emoji_catch function though like this: await Emoji.emoji_catch(self, message), i get an error TypeError: 'module' object is not callable??

#

am i calling the function wrong here?

#

looks like this

meager mica
#

i think

celest lichen
#

over the function itself you mean? like a decorator?

meager mica
#

yea

celest lichen
#

okay, i'll give that a try now

#

same error

#

so weird

meager mica
#

self.emoji_catch?

celest lichen
#

ohhhhhh that might be it

dry echo
#

self.emoji_chatch ..... Learn Python pls

meager mica
#

only reason i know it is cuz i learned kotlin

celest lichen
#

would you suggest i spend dozens of hours reading theory books or actually writing code

#

this is how i'm learning

#

self.emoji_catch giving me the same exception... rly weird

prisma flicker
#

name it like EmojiCog or something

celest lichen
#

ohhhhh thank you

celest lichen
#

STILL getting module object not callable... wtf

prisma flicker
#

if it's not a static method you need to use self

celest lichen
#

i added @staticmethod like dwaa suggested

#

this is what it looks like now

prisma flicker
#

then take out the self in on_message

#

and static methods don't take in self

meager mica
#

self iirc

prisma flicker
#

it's static, there is no self

#

they take in cls

celest lichen
#

wouldn't it be unable to use self.bot.db.execute though, if i'm not giving it self?

prisma flicker
#

yes

celest lichen
#

so many i don't use staticmethod lol

prisma flicker
#

either way it can't do that

celest lichen
#

*maybe

meager mica
prisma flicker
#

you can call it self but it's really cls and it won't work

prisma flicker
dry echo
#

when you use self.your_def() your dont need them too

celest lichen
#

i'm very lost lol

dry echo
#

can i use commands groups in multiple cogs?

celest lichen
#

wait, is it something wrong with stripped_msg = unidecode(msg.content)??

round rivet
#

unidecode appears to be a module

#

that you imported

celest lichen
#

yeah, i've imported it though

round rivet
#

there's probably a function in the module you're trying to use

meager mica
#

you might have to do somthing like unicode.unicode

celest lichen
#

ohhhhhh

#

i think you're right

meager mica
#

from unidecode import unidecode

celest lichen
#

*same function in another file

meager mica
#

yea

celest lichen
#

before i separated this into a cog

meager mica
celest lichen
#

it works 😭

#

everything works now ty guys for all ur help

prisma flicker
celest lichen
#

i definitely did - quite unused to classes so it takes a bit of getting used to

dry echo
#

can someone tell me why pylance underlines me most of my code red?? like whats wrong there

neat temple
#

I am trying to reload all slash commands without having to restart the bot and the following code only adds the new functions when its not a slash command, but when it is a slash command it does not load it. How can I reload all commands from inside the code? I already tried syncing

# Restarts cogs
    @commands.slash_command(description="Restart cogs")
    @isDeveloper()
    async def reload(self, ctx):
        cogs = [ext[:-3] for ext in listdir("./cogs/") if ext.endswith(".py")]

        embed = discord.Embed(color=0x3C3D41, timestamp=discord.utils.utcnow())
        embed.title = 'Reloading Cogs!'
        await ctx.respond(embed=embed, ephemeral=True)

        for cog in cogs:
            try:
                self.bot.reload_extension(f"cogs.{cog}")
                embed.add_field(name=f"Reloaded: `{cog}`", value="\uFEFF", inline=True)
                await ctx.interaction.edit_original_message(embed=embed)
            except Exception as e:
                embed.add_field(name=f"Exception ocurred: ", value=e)
                await ctx.interaction.edit_original_message(embed=embed)

        embed.title = f'Synced All Commands!'
        await ctx.interaction.edit_original_message(embed=embed)

fervent cradle
#

is there any way to have 2 sets of multiple choices on a slash command? like have 2 options with multiple choices to choose from

dim lake
#

is there a way to load n messages from a certain channel into the internal message cache on startup?

prisma flicker
prisma flicker
dim lake
prisma flicker
#

just use on_raw_reaction_add

#

or consider using buttons

dim lake
# prisma flicker just use on_raw_reaction_add

I don't want to rewrite a ton of stuff because I do things like interacting with the reaction object that on_reaction_add passes and there isn't a reaction object in the payload parameter of on_raw_reaction_add

prisma flicker
#

you don't have to rewrite anything, you can just call on_reaction_add from on_raw_reaction_add

dim lake
#

boi

prisma flicker
#

just create the reaction object and pass it

dim lake
#

is there a get reaction? because on_raw_reaction_add doesn't give it to you

prisma flicker
#

the solution is on_raw_reaction_add, trying to prefill the cache isn't going to be reliable

#

a get reaction?

fervent cradle
prisma flicker
prisma flicker
dim lake
#

the payload object only contains the emoji and the author, not the actual reaction itself

prisma flicker
#

you'd have to call remove on the message

dim lake
#

I don't want to remove the entire message, just the reaction
on_raw_reaction_add doesn't even pass the message object, only the id

prisma flicker
#

yes you would just fetch the message

#

Message has a remove_reaction method

fervent cradle
# prisma flicker can you send your code?
    @commands.slash_command(description="Sets the bots presence")
    @discord.option("status", description="Set the status of the bot", choices=["online", "idle", "dnd", "invisible"])
    @discord.option("actvity", description="Sets the activity of the bot", choices=["playing", "watching", "listening", "competing", "streaming"])
    @isDeveloper()
    async def presence(self, ctx, status: str, activity: str, name: str):
        statuses = {
            "online": discord.Status.online,
            "idle": discord.Status.idle,
            "dnd": discord.Status.dnd,
            "invisible": discord.Status.invisible
        }

        activities = {
            "playing": discord.ActivityType.playing,
            "watching": discord.ActivityType.watching,
            "listening": discord.ActivityType.listening,
            "competing": discord.ActivityType.competing,
            "streaming": discord.ActivityType.streaming
        }

        status = statuses[status]
        activity = activities[activity]

        presence = discord.Activity(name=name, type=activity, status=status)
        await self.bot.change_presence(activity=presence)
        await ctx.respond(embed=discord.Embed(title="Set presence!"), ephemeral=True)
prisma flicker
#

so maybe try that

fervent cradle
#

oh so i just import from discord import option and then just do opton and the stuff

prisma flicker
#

no

#

also you spelled activity wrong, that might be why it's not working

fervent cradle
#

oh thats it

prisma flicker
#

this is what I was talking about py async def presence(self, ctx, status: Option(str, choices=["online", "idle", "dnd", "invisible"], activity: Option(str, choices=["playing", "watching", "listening", "competing", "streaming"], name: str):

dim lake
#

@prisma flicker fetch_message can't be called without a ctx object which isn't passed into on_raw_reaction_add

prisma flicker
dim lake
prisma flicker
#

sorry, it's in channel

#

something like await bot.get_guild(guild_id).get_channel(channel_id).fetch_message(message_id)

dim lake
#

this will get the message, and it has the reactions array

await client.get_channel(payload.channel_id).fetch_message(payload.message_id)

however there's no way to determine what reaction just occurred

prisma flicker
#

how do you figure? you have the emoji, member, and message

dim lake
prisma flicker
#

don't use the reaction array

#

use the payload.emoji and payload.user_id

dim lake
#

I'm looking for a reactions object to call .remove on
is there a remove somewhere else I can call?

#

msg has a remove_reaction

prisma flicker
#

you would call remove_reaction on msg yes

dim lake
#

yea it doesn't take user_id though

prisma flicker
#

well yeah, you need to turn user_id into a user

#

it takes a discord.User not an int

dim lake
#

thanks

indigo badger
#

For some reason VS code tells me I have 4 arguments when in this code I only have three on the line

#
@Client.command()
@commands.Cooldown(1, 5, commands.BucketType.user) #This is the line
async def withdraw(ctx : commands.Context, amount: int):
  wallet, bank, maxbank = await get_balance(ctx.author)
  try:
    amount = int(amount)
  except ValueError:
    pass
  if type(amount) == str:
    if amount.lower() == "max" or amount.lower == "all":
      amount = int(bank)
  else:
    amount = int(amount)

  bank_res = await update_bank(ctx.author, -amount)
  wallet_res = await update_wallet(ctx.author, amount)
  if bank_res == 0 or wallet_res == 0:
    return await ctx.send("No account was found so one was made for you")
  
  wallet, bank, maxbank = await get_balance(ctx.author)
  em = discord.Embed(title=f"{amount} coins have been withdrew")
  em.add_field(name="New Wallet", value=wallet)
  em.add_field(name="New Bank", value=f"{bank}/{maxbank}")
  await ctx.send(embed=em)
#
@commands.Cooldown(1, 5, commands.BucketType.user)
TypeError: Cooldown.__init__() takes 3 positional arguments but 4 were given
#

Error. ^^^

#

I looked it over and can only see three there.

prisma flicker
#

should it be @commands.cooldown()?

frank yew
#

Can someone help me if I have a list in like this: ["a", "b"] and want to fill it to a certain length with the same pattern? Length 4 ["a", "b", "a", "b"] or Length 8 ["a", "b", "a", "b", "a", "b"]. I don't know how to do it

prisma flicker
#
=>>> x=['a','b']
>>> x*4
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']```
wooden zenith
#

how do i make it so i can have multiple buttons on the same command beacsue currently i have one command that is /homepage and when the command activates i have the button thats is log in but i wanna make multiple buttons instead of just one here is the code i have if anyone wants to fix and write back!

class MyView(discord.ui.View):
@discord.ui.button(label="login", style=discord.ButtonStyle.primary, emoji="")
async def button_callback(self, button, interaction):
await interaction.response.send_message("no log in yet sorry!")

@bot.slash_command()
async def homepage(ctx):
await ctx.respond("homepage", view=MyView())

prisma flicker
wooden zenith
#

sorry im kinda new to coding lol, can u explain further

prisma flicker
#

so like add another @discord.ui.button

#

and another callback

wooden zenith
#

how do i do the call ack just take async def button_callback(self, button, interaction): and replace what?

prisma flicker
#

yeah but don't name it button_callback

wooden zenith
#

okay thanks let me try this!

prisma flicker
#

I would name your first one login or login_callback

frank yew
wooden zenith
#

@discord.ui.button(label="get,code", style=discord.ButtonStyle.primary, emoji="👩🏻‍💻")
async def poop_callback(self, button, interaction):
await interaction.response.send_message("cant get code yet!")

i have that and got syntax error did i do it wrong

prisma flicker
#

what's the syntax error say

wooden zenith
prisma flicker
#

looks like your indentation is wrong

wooden zenith
#

o

#

okay

#

stil no work

#

oh wait i fixed it thank you

dim lake
#

@prisma flicker on_raw_reaction_remove passes none as the member in the payload object

#

and you can't just fetch the user apparently

        author = await client.get_user(payload.user_id)

TypeError: object User can't be used in 'await' expression

prisma flicker
#

get doesn't need await

dry echo
#

when i use this decorator, does it only affect on every user or only onto the executor?

@commands.cooldown(1, 15, commands.BucketType.user)
cyan quail
dry echo
#

so just replace cooldown with dynamic_cooldown?

cyan quail
#

not quite; the usage is a bit different

#

we should probably have an example for it

simple canopy
cyan quail
#

hm?

#

ohhhhhhhhhhhhhhh

#

i see

simple canopy
#

BucketType.user only affects the executor

cyan quail
#

^ my mistake

#

everyone will be affected by the cooldown separately

simple canopy
#

however, .guild (or its .server not sure) affects whole guild

dry echo
#

so just leave it as it is?

simple canopy
#

yea

dry echo
#

okay thanks

simple canopy
#

this should work on prefixed commands, but i didn't test it with / ones

cyan quail
#

it'll work with slash too

dry echo
#

i only use slash

cyan quail
#

all ext decorators will

wooden zenith
#

hello, does anyone here have a code that could make something like this with a box like that with words in it?

dry echo
#

pls what

wooden zenith
#

huh

dry echo
#

mean an embed??