#Basic Pycord Help (Quick Questions Only)

1 messages Β· Page 38 of 1

plush meadow
#

the way i approached this when I began writing the bot is fundamentally garbage. I'm just curious if anyone can give me their opinion on if this is even worth doing

limber urchin
#

Like said, it's your code, if you think it needs a re-write then it probably does

plush meadow
#

well I don't know, that's the thing

limber urchin
#

It's impossible to say, because we didn't write the code and we most likely won't either.

plush meadow
#

damn, this sucks. i've really done it to myself

#

my brain tells me i should be able to just convert these into cogs but when I look at the docs I feel like passing out

#

would it be advisable to make a separate cog for each command? that's more or less what I have going on here

hollow brook
#

so if I have mute, kick, ban, and warn commands, I'd most likely put those four in a cog named moderation

plush meadow
#

okay, makes sense

#

before i jump in the deep end here, what exactly is preventing me from simply putting a decorator above all my functions to label them as commands?

hollow brook
#

Show us one of your commands.

#

just the first line or so

plush meadow
#

that's what I sent here, kinda

#

that's how every command works at the moment

hollow brook
#

so it looks like each command is parsing the command message itself?

plush meadow
#

here's a full example for more context

#
import discord
import helper

errors = {}

################ Module Start ################


async def main(client, message, args):
    if len(args) == 0 or args[0] == 'help':
        await message.channel.send(embed=helper.generate_help_embed(client, metadata))
        return

    await message.delete()
    await message.channel.send(' '.join(args))


################ Module End ################

metadata = {
    'emoji': ':speech_balloon:',
    'name': 'Say',
    'description': 'Make the bot say something.',
    'aliases': ['say'],
    'permission_level': 'Member',
    'syntax': '!say <message>',
    'subcommands': [],
    'usage_examples': ['!say Hello World!'],
    'function': main
}
#

very simple one

hollow brook
#

A command in Pycord looks like this:

@discord.command
async def my_command(ctx, arg1, arg2):
plush meadow
#

right

hollow brook
#

the command handler does everything that you're currently doing individually

plush meadow
#

my pickle comes in the fact that I'm working across many files. I've tried passing the context myself but I haven't managed to make it work

hollow brook
#

helps a ton, and will definitely help cut down your codebase

plush meadow
plush meadow
#

yup

hollow brook
#

I'd suggest learning how its command handlers work, and then rewriting your bot. Instead of having all of this mumbo jumbo, it'd all be nice an organized

plush meadow
#

i'd love to rewrite it if it didn't have so many moving parts

#

i feel that it is possible to just tweak each command one at a time and register them as commands as I go, but I simply cannot get the commands to register because I'm passing the incorrect client context

#

if my bot is initialized like so:

client = discord.Bot(intents=discord.Intents.all(), command_prefix='!')

importing client within my modules should let me register the commands, no?

limber urchin
#

My suggestion would be to completely start over and copy/paste the parts you want to actually use. Trying to rewrite something that is already messy will take 10 times longer

lyric viper
#

Hey, I've started getting errors on startup since updating to v2.3.1 (from v2.3.0). When I add cogs to a bot instance, it throws this error:

AttributeError: 'Bot' object has no attribute '_bridge_commands'. Did you mean: 'bridge_commands'?
#

I setup my bot object like this:

    bot = bridge.Bot(command_prefix=commands.when_mentioned_or("$"), intents=intents)
silver moat
#

show full error

lyric viper
#
Traceback (most recent call last):
  File "C:\Users\Nicholas\Documents\GitHub\TitanBot\TitanBot.py", line 53, in <module>
    bot.add_cog(quotes_module)
  File "C:\Users\Nicholas\Documents\GitHub\TitanBot\venv\Lib\site-packages\discord\cog.py", line 656, in add_cog
    cog = cog._inject(self)
          ^^^^^^^^^^^^^^^^^
  File "C:\Users\Nicholas\Documents\GitHub\TitanBot\venv\Lib\site-packages\discord\cog.py", line 545, in _inject
    bot._bridge_commands.append(command)
    ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute '_bridge_commands'. Did you mean: 'bridge_commands'?
hollow brook
#

it tells you what's wrong right there

lyric viper
#

Unless I'm understanding it incorrectly, the issue is inside cog.py, where it should use bridge_commands instead of _bridge_commands. But since this is part of the library itself I don't know how I'm supposed to make it use bridge_commands

hollow brook
#

ooh i see

limber urchin
#

What version of pycord are you using?

hollow brook
#

2.3.1

lyric viper
#

Yes

#

The changelog says 2.3.1 was supposed to fix this issue but with AutoShardedBot, so I wonder if there was a regression somewhere for the regular Bot class

harsh canyon
harsh canyon
#

hadnt checked if that had fixed it or not

#

so ig not

distant abyss
#

is Thread.applied_tags working yet? it just returns an empty list for me

lyric viper
#

So I tried swapping Bot with AutoShardedBot just to see if it would work, and interestingly it fails, which is exactly what v2.3.1 was supposed to fix. I'm going to try reinstalling pycord in case it's just some jank with my virtualenv

distant abyss
#

I have

intents = discord.Intents.default()
intents.members = True
intents.guilds = True
silver moat
#

Are you doing this in a slash command?

distant abyss
#

yup

silver moat
#

or rather, how do you access applied_tags

orchid kernel
#

Not a large amount of data, it's basically just two strings (or one actually since I'm supposed to store headers):

headers = {
    'Client-ID' : client_ID,
    'Authorization' :  "Bearer " + access_token
    }

But thanks, the global variable was the simpler solution, it works as intented now 😁: (simple boolean that acknowledge auth or not)

distant abyss
#

I can just move to a forum post

orchid kernel
#

I am not comfortable with classes (never created or used one for my bot) nor databases, so I would not know how to proceed and use them

#

So, so far, I'm glad the global variable did the trick πŸ˜…

silver moat
limber urchin
#

Read rule 1 in #help-rules

orchid kernel
#

I think I manage basic Python enough to have a bot and a few slash commands/modules running without using classes (or at least, build one). When looking at the Python tutorial from w3 for instance (great website imo) I basically know everything except for classes that I never had to use so far πŸ€·β€β™‚οΈ

orchid kernel
lyric viper
limber urchin
#

To be clear:

When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.

We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.

limber urchin
lyric viper
#

I can do that. I'll start building a minimal reproduction sample

#

Looks like that PR didn't actually fix it πŸ˜†

#

Oh nevermind, I clicked the wrong run config in Pycharm πŸ’€

lyric viper
#

Alright, I've got a minimal reproduceable sample. Seems like the issue only arises when adding commands inside of cogs:

import discord
from discord.ext import bridge, commands
from discord.ext.bridge import bot


class SampleCog(commands.Cog):

    @bot.bridge_command()
    async def test(self, ctx):
        await ctx.respond("test")


intents = discord.Intents.all()
bridge_bot = bridge.Bot(command_prefix=commands.when_mentioned_or("!"), intents=intents)

bridge_bot.add_cog(SampleCog())
bridge_bot.run("token")
#

I'll get to work on a bug report

full basin
lyric viper
#

Well, it's worked ever since I started the bot with discord.py πŸ˜†

#

I didn't know that it worked in a different manner

full basin
#

But this is py-cord chief

lyric viper
#

I know, when i migrated to py-cord I didn't have to rewrite the code

#

It worked as-is so I assumed that was the way to do it

#

I've had my cogs setup like this for around 9 months. What's the proper way to set them up then?

errant craneBOT
#

Here's the slash cog example.

lyric viper
#

I don't see any differences aside from the command decorator and the comment at the bottom saying the bot instance should be in a separate file

#

In my actual bot I have these in separate files, I just put it all in one so that I could make a minimal reproduction sample

silver moat
lyric viper
#

Alright, I moved them into separate files and can still reproduce the error. Is the example code otherwise fine? If so I can go ahead and post the issue

lyric viper
#

πŸ‘

fervent cradle
#

Hi, I'm currently using commands.Bot for my bot. If I switch to discord.Bot, will things like ext.tasks still work?

fervent cradle
#

okay, thanks!

silver moat
#

discord.ext.tasks works independently of discord

fervent cradle
#

How do I add a response after a slash command is used?

round rivet
strange lynx
#

I'm having trouble setting a large list for autocomplete

#

It's a list of country names

#
@bot.slash_command(guild_ids=[813967937038974997], name='shipping', description='Calculate shipping costs on sugargoo for your specified country & weight')
async def shipping(ctx,
                country: Option(
                    str,
                    name="country",
                    description="Country you are shipping to",
                    autocomplete=countries
                    ),
                weight: Option(
                    int,
                    name="weight",
                    description="Weight of parcel in grams"
                ),
                width: Option(
                    int,
                    name="width",
                    description="Parcel width",
                    default=15
                ),
               length: Option(
                   int,
                   name="length",
                   description="Parcel width",
                   default=15
               ),
               height: Option(
                   int,
                   name="height",
                   description="Parcel width",
                   default=15
               )):
#

autocomplete=countries

#

countries is a list of every country name

#
Traceback (most recent call last):
  File "C:\Users\elich\PycharmProjects\sugargoobot4\venv\lib\site-packages\discord\bot.py", line 856, in callback
    return await command.invoke_autocomplete_callback(ctx)
  File "C:\Users\elich\PycharmProjects\sugargoobot4\venv\lib\site-packages\discord\commands\core.py", line 996, in invoke_autocomplete_callback
    if len(inspect.signature(option.autocomplete).parameters) == 2:
  File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 3118, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2867, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2242, in _signature_from_callable
    raise TypeError('{!r} is not a callable object'.format(obj))
TypeError: ['Albania', 'Algeria', 'Andorra', 'Angola', 'Anguill... (this goes on but message length limit)] is not a callable object
#

it works fine when I return the exact same list from a coroutine

raw gust
#

as far as i know autocomplete has to be a corountine

cobalt tangle
#

can I use @bridge.has_permissions in slash commands?

cobalt tangle
tender seal
#

How do I put an options menu in a slash command (discord.ext.commands.slash_command)?

fringe socket
#

Anybody know the coro for setting a slowmode?

steel wedge
#

why does this not work?

@bot.command()
async def test(ctx):

    guild = ctx.guild
    user = "647146794366795797"
    role = guild.get_role(1047120025166827562)
    await user.add_roles(role)```
#

i tried get_user but its not a thing

steel wedge
#

yes

#

it errors saying that class str cannot be use with add role

young bone
#

eh

#

your user is a str at the moment

#

do you know basic python?

steel wedge
#

yes

#

int also does not work

young bone
#

but you know how to get a user?

steel wedge
#

kinda

#

i dont know to set a user

#

but i can call from other places

young bone
#

user = bot.get_member(id)

steel wedge
#

thats what have done

#

now and it says User' object has no attribute 'add_roles'

#

so this would be right
user = bot.get_user(647146794366795797)

#

so this would also work
await user.add_roles(role)

#

but it doesnt

young bone
#

still get_member not get_user

steel wedge
#

bot' object has no attribute 'get_member'

#

old version of pycord?

young bone
#

also do you use py-cord or dpy?

steel wedge
#

cause it auto fills get_user

#

i think pycord

#

altho i am using a online idle

young bone
#

which one?

steel wedge
#

replit

young bone
#

?tag replit

obtuse juncoBOT
cobalt tangle
#

All of a sudden, now my bot isnt working because none of my bot scripts can import functions from other files

#

from mod import successEmbed

#

in cc.py

#

and ModuleNotFound is being raised

young bone
#

cogs.module

cobalt tangle
#

why though

cobalt tangle
steel wedge
#

i love replit

#

errored while installing

#

imma just use vs

#

thanks for your help anyway

young bone
cobalt tangle
#

also how do I import a file which is outside a folder without manually giving the path

steel wedge
cobalt tangle
#

cuz the path may change due to me running it locally and on a vps

steel wedge
#

why does vs just say discord is not defined

#

after i ran this
py -3 -m pip install -U py-cord

young bone
#

pip show py-cord

steel wedge
#

its erroring on this ```import discord
from discord.ext import commands

intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
bot.remove_command('help')```

#

saying commands is not defined

#

nvm fixed it

#

it was cuase i had both installed

full basin
fervent cradle
#

Is it possible to hide a slash command from anyone except me?
I know guild_ids exist and that I could set it to my own server, but I want to check if there's another method, especially one that involves me using that command in DMs.

amber shale
#

is there any way to delete thread after some time?

mild osprey
#

anybody know whats wrong with this? (something to do with the callback) ```py
async def kick(ctx, member: discord.Member, *, reason=None):
view = View()
if reason==None:
reason=" no reason provided"
yeskickbutton = button(label = "yes",ButtonStyle = discord.ButtonStyle.green, emoji = 'βœ…')
nokickbutton = button(label = 'no', ButtonStyle = discord.ButtonStyle.red, emoji = '❌')

async def yeskickcallback(interaction):
    interaction.guild.kick(member)
    interaction.response.send_message(f' just banned {member.mention} for {reason}!')


yeskickbutton.callback = yeskickcallback

async def nokickcallback(interaction):
    interaction.response.send_message(f'alright, i wont ban {member.mention}!')

nokickbutton.callback = nokickcallback
view.add_item(yeskickbutton)
view.add_item(nokcikbutton)

await ctx.send(f'are you sure you want to kick {member.mention}?', view=view)```
plush meadow
#

what's the error

mild osprey
#

ima pull it up

plush meadow
#

and use py when you do the triple ticks so people can see the syntax highlighting

mild osprey
#

how

silver moat
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
mild osprey
#

oh ok

plush meadow
#

how tf do you escape backticks, i couldn't figure out how to make them show up

mild osprey
#

ty

mild osprey
plush meadow
#

i wish i could help you but i'm also here for a question

mild osprey
#

ok

plush meadow
#

oh wait

mild osprey
#

?

plush meadow
#

yeskickbutton is only defined if there is no reason

mild osprey
#

ok

#

oh im dumb

plush meadow
#

if i understand what you're trying to do, you want those defined regardless (i think)

fervent cradle
#

It's \` to escape them

mild osprey
#

ik

plush meadow
fervent cradle
#

Gotta do it after each one

plush meadow
#

````

#

that's embarrassing, thank you

fervent cradle
#

Np haha

plush meadow
#

whenever someone gets the opportunity, I am trying to utilize extensions to register my commands to the main script. Within my command additem.py, where the main function is additem(), I have written a setup like so:

def setup(client):
    client.add_command(additem)
    print("Loaded command: additem")

My code looks congruent to the examples as far as I can tell, but nonetheless I get the error

TypeError: The command passed must be a subclass of Command
plush meadow
#

been wrestling with this for 30 minutes just to notice it now

mild osprey
plush meadow
glossy tusk
#

is "discord.on_unknown_application_command" only for slash commands?

glossy tusk
#

I can not call this event

#

what's wrong

#
@commands.Cog.listener()
    async def on_application_command(context:discord.ApplicationContext):
        await context.channel.send("L")
#

or

glossy tusk
#

ohhhhhh my god

glossy tusk
#

LOL

#

thx

fervent cradle
#

Is there anyway to make a fully public bot with website configuration with Pycord?

young bone
fervent cradle
cerulean shell
#

Hi, is it possible to add a "fancy" name to a @user_command? I've seen it is some bots. For example a command with name="check_user" would like nicer with a facny name "Check User". Is it possible with PyCord?

atomic wolf
#

How do I check if a user with a specific role is in a voice channel?

hallow blaze
fiery tiger
#

Hey, i've got a question. How can i check when the guild emoji name changes, Looking thruthe docs on_guild_emojis_update will only get called once a emoji is created/deleted

full basin
#

Because it returned None

#

I dunno sql /shrug

limber urchin
#

There probably isn't a record in your table with that user id

plush meadow
#

are you able to create user_command with a bridge bot? I can't seem to find any documentation on it, although the docs state that it should inherit all the features of a regular bot

#

@bridge.user_command is a no go, so there must be something I'm missing

cyan quail
plush meadow
#

oh really? that's embarrassing

#

i appreciate the help, thank you

mild monolith
#

Hello! I have a quick question

What I need it to do is when the user selects 2 of the choices it will send out a GIF that matches the 2 things that were selected. I tried looking on the DOCS but couldn't find anything or I'm not looking hard enough ( EX: The user clicks Red and Blue = Sends a GIF, User Selects Blue and Green = Sends a GIF )


class mix(discord.ui.View):
    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "Choose a potion", # the placeholder text that will be displayed if nothing is selected
        min_values = 2, # the minimum number of values that must be selected by the users
        max_values = 2, # the maximum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="🟑",
                description=""
            ),
            discord.SelectOption(
                label="🟒",
                description=""
            ),
            discord.SelectOption(
                label="🧊",
                description=""
            ),
            discord.SelectOption(
                label="πŸ”΄",
                description=""
            ),
            discord.SelectOption(
                label="πŸ”΅",
                description=""
            ),
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")```
#
async def button(ctx):
    embed=discord.Embed(title=f"Choose Wisely!", description="",color=0x660066)
    embed.set_image(url="https://media.discordapp.net/attachments/999932873077424128/1047271785298657310/unknown.png?width=459&height=586")
    await ctx.respond(embed=embed, view=mix()) # Send a message with our View class that contains the button```
#

This is what I have so far

limber urchin
#

Can't you just check if two options has been selected? Through the length of select.values?

mild monolith
#

I'm not sure I understand

#

oh wait

#

So would it have to be a different callback for combination or how would I get it to select the 2 values and send the gif matching its combination

limber urchin
#

In your callback, check if two options have been selected, then just make if statements for the different combinations

loud robin
#

okay let me try

mild monolith
#

It now gives this error

#
        selection = self.values[0]
        if selection == "🟑" "🟒":
            await interaction.response.send_message("https://media.discordapp.net/attachments/957163963588681788/957164412807036928/yg.gif")
        elif selection == "🟑" "🧊":
            await interaction.response.send_message("https://media.discordapp.net/attachments/957163963588681788/957166502258286592/yc.gif")
#
lse>, <SelectOption label='🧊' value='🧊' description='' emoji=None default=False>, <SelectOption la  bel='πŸ”΄' value='πŸ”΄' description='' emoji=None
 default=False>, <SelectOption label='πŸ”΅' value='πŸ”΅' description='' emoji=None default=False>] disabled=False>:
Traceback (most recent call last):
  File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 396, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\13129\Desktop\Python Bot\Slash.py", line 59, in select_callback
    selection = self.values[0]
AttributeError: 'mix' object has no attribute 'values'```
limber urchin
#

Why are you doing self.values and not select.values?

loud robin
#

Sorry, I thought it would be that because I saw self on the documentation. I’ll fix it

limber urchin
#

Why are you responding from two different accounts?

loud robin
#

This is my main and the other is on my labtop

#

labtop runs the code and has the test/dummy account haha

#

@limber urchin I changed it to selection = select.values[0]

It gives no error in the terminal but says the interaction failed

limber urchin
#

And why are you only getting one of the selected values?

loud robin
#

Does the 0 have to be 2?

limber urchin
#

Do you know basic Python?

loud robin
#

It allows me to select the two colors

loud robin
limber urchin
#

Read rule 1 in #help-rules

loud robin
#

Yikes

#

Uhm my bad

loud robin
# limber urchin Read rule 1 in <#881891840746475570>

Not sure if I'm still allowed to ask for help but I'm dumb... I knew what it was but was just acting before thinking. 0, 1, 2, 3 - I changed it to 1 as that takes 2 of the choices and it still gives me the interaction failed with no console error

limber urchin
#

?

loud robin
#

Wrong reply

limber urchin
#

Why would changing it to 1 make it take 2 of the options?

loud robin
#

Doesn't the numbering go by (0, 1, 2, 3, ETC.)? I changed it to the number 2 and it told me it was out of range but when I brought it back to 1 it worked again

limber urchin
#

Like I said, read rule 1 in #help-rules

loud robin
#

I read it

limber urchin
#

That is not how Python works

#

you clearly do not know Python well enough to be making a bot yet

loud robin
#

Thats kinda disrespectful ..

limber urchin
#

It is not

loud robin
#

I have to learn/start somewhere

young bone
limber urchin
#

And a bot is not the right place to start

#

or learn

#

That's like learning to draw by painting the mona lisa

loud robin
#

Making a discord bot isn't that advanced

limber urchin
#

It is obviously too advanced for you right now

young bone
#

Python is not hard to learn but without the basics you will have many problems

loud robin
#

Welp I'll try and figure it out. Thanks for the help

fervent cradle
#

Is there anyway to make a fully public bot with website configuration with Pycord?

limber urchin
#

Why would it not be possible?

fervent cradle
limber urchin
#

What do you need help with?

fervent cradle
#

alot lol

#

some1 told me flask/django and HTML and CSS, this true?

limber urchin
#

I mean yeah, to make a website you're obviously going to need HTML and CSS

#

And then you need a web server to make requests to

fervent cradle
#

the only thing I rlly need help with is just getting the config from the website to the bot

limber urchin
#

Well you'd need to set up OAuth2 on your website to allow users to log in through Discord. Then you need to run a web server parallel to your bot that handles requests and applies configurations made on the website to a database.

fervent cradle
#

okay thx

silver moat
limber urchin
silver moat
#

edit learnpython

limber urchin
#

Done

fringe socket
fringe socket
#

ty

plush meadow
#

apologies guys, i keep coming back with odd questions

#

I've passed my BridgeApplicationContext to another file as ctx. As far as I can tell, there's no way to get the client id from this, correct?

#

ctx.user.id returns the id of the user who called the command (which is peculiar since ctx.author.id returns the same)

silver moat
plush meadow
#

sorry, the bot instance

#

my question should have been more clear

silver moat
#
plush meadow
#

i was traversing the docs for about 15 minutes and i swear i got lost in a maze

#

let me give this a go

#

that did the trick, i appreciate it

silver moat
#

yw

wheat stirrup
#

how do i add buttons to an embed?

silver moat
#

This is a misconception. Messages can have content, embeds, components, attachments, etc. They are all fields of a message. They are not mutually exclusive. Short answer, add it like normal

wheat stirrup
#

ohhh okay cool i thought there needed to be some special embed.add_button() or something. Thank you!

long torrent
#

How do I get the invite used by someone when they join?

#

Can't seem to figure it out from the documentation.

limber urchin
#

Why are you mixing discord.Option and Option?

north gorge
#

Can you mention a channel in an embed? <#somenumbers> doesn't seem to work

lyric parrot
#

i noticed that the reason for the purge method does not show up in the audit log, but it should works as there a reason parameter

cobalt tangle
#

My commands arent loading in this specific cog:

#
class cc(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    pyx = discord.SlashCommandGroup(name="pyx", description="PyX Server only commands", guild_ids=[933959481891622933])
    @pyx.command(description="DM an user")
    @commands.has_permissions(manage_guild=True)
    async def dm(self, ctx, msg: Option(str, "Message to convey"), color: Option(choices=["Green", "Red", "Yellow"]), member: Option(discord.Member, "Member to convey to")):
        if color == "Green":
            color = discord.Color.brand_green()
        elif color == "Red":
            color = discord.Color.brand_red()
        elif color == "Yellow":
            color = discord.Color.yellow()
        else:
            color = discord.Color.dark_orange()
        embed = discord.Embed(title="DM", description=f"```{msg}```", color=color)
        embed.add_field(name="Sent by:", value=f"{ctx.author}")
        embed.set_footer(text=f"Sent by {ctx.guild} | Hope you have a good day!", icon_url=ctx.guild.icon.url)
        try:
            await member.send(embed=embed)
        except:
            await ctx.respond("Member has DM's disabled", ephemeral=True)
        embed = await successEmbed("Sent DM with no issues!")
        await ctx.respond(embed=embed)

def setup(bot):
    bot.add_cog(cc(bot))
cobalt tangle
#

I replaced a command but the old cmd is still there, but doesnt function ofc

barren garnet
#

yo
can we use @commands.cooldown decorator for bridge commands?

barren garnet
cobalt tangle
#

bz there are two types of has_permissions

#

one is internal, the commands one, the other is default_permissions

cobalt tangle
#

it works for me

barren garnet
barren garnet
cobalt tangle
#

um wat

#

why

barren garnet
#

name="cc"

cobalt tangle
#

why? name is for my group name

#

it doesnt relate to cog name???

barren garnet
#

ah wait

cobalt tangle
#

cc = custom commands

barren garnet
cobalt tangle
#

so i had a previous /pyx verify cmd

naive pagoda
#

I have a question:
Can I seta slash command for admin only by default? -> If the bot joins new server, several commands would have admin only permissions by default.

cobalt tangle
#

but i replaced it with dm

naive pagoda
cobalt tangle
cobalt tangle
cobalt tangle
naive pagoda
cobalt tangle
naive pagoda
cobalt tangle
barren garnet
#

i tried to bulk register , so

#

Β―_(ツ)_/Β―

cobalt tangle
#

bot's up for like 48 hours

#

no ratelimit cuz i have logging enabled

naive pagoda
barren garnet
cobalt tangle
barren garnet
naive pagoda
cobalt tangle
#

pycord 2.3 is full of bugs

cobalt tangle
#

rude pycord

barren garnet
barren garnet
cyan quail
#

No that hasn't been a thing for a while

cobalt tangle
cyan quail
#

Global commands register instantly now

cobalt tangle
#

please

barren garnet
#

i took a break from developing 6 months ago lol

cyan quail
#

What is it

barren garnet
oblique river
limber urchin
#

pycord 2.3 is not beta

barren garnet
#

wait
is pycord 2.3 stable?

cobalt tangle
#

stay up to date lol

cyan quail
#

2.3 isn't particularly buggy? If I'm not mistaken it's one of the more reliable releases

barren garnet
#

bruh im lagging behind

cyan quail
#

But hm

cobalt tangle
naive pagoda
#

you have 2.3.0 or 2.3.1?

cyan quail
#

So you have slash commands in other cogs that load?

barren garnet
oblique river
#

I did not mean the 2.3 that the 2.3 is stable I know but if you want to use the beta then do not do that if you have no idea

barren garnet
cyan quail
#

And you're 1000% sure the cog actually loads

cyan quail
cobalt tangle
#

only that cog is having issues, logging is enabled, no ratelimiting, cog is loaded cuz i printed every loaded cog

#

cog cc was there

cyan quail
#

So let's say you print something in the cog's init as well

cobalt tangle
#
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')
        print(f"Loaded cog {filename[:-3]}")
limber urchin
#

In the cogs init function, not where you load the cog

cyan quail
#

Yeah but just in case, below self.bot = bot add a print

#

^^

cobalt tangle
#

ok sure

#

its loaded

barren garnet
cyan quail
#

Or alternatively, just print bot.cogs from some command

cobalt tangle
#

it printed it

cyan quail
#

Fair enough

limber urchin
#

What if you add your guild_ids to your command decorator as well? Not just the group?

barren garnet
cyan quail
#

Do you use guild_ids for all your other commands?

cobalt tangle
barren garnet
naive pagoda
cyan quail
limber urchin
limber urchin
cobalt tangle
#

only the cmds in CC cog are supposed to be guild-only

cyan quail
#

Then how about remove guild_ids entirely?

#

Ah isee

cobalt tangle
#

CC= Custom Commands

#

dm is a custom command only for my server cuz yes

cyan quail
#

So theoretically if you moved these commands to an existing cog, they would load?

cobalt tangle
#

I dont know

cyan quail
#

Could you perhaps try

cobalt tangle
#

lemme try

#

ok it doesnt load

#

ig the issue is with the group

#

@cyan quail

naive pagoda
#

what about moving this outside of the class? coz its not pyx, but self.pyx in this case
pyx = discord.SlashCommandGroup(name="pyx", description="PyX Server only commands", guild_ids=[933959481891622933])

cyan quail
#

No that's fine

#

It needs to be in the class

cobalt tangle
cyan quail
#

I'm on mobile so I can't see quite correctly but uh

#

Is that has_permissions decorator indented?

cobalt tangle
#

even if, that would raise an error if not lol

cyan quail
cobalt tangle
cyan quail
#

Well currently you're on pyx.command

#

I'm suggesting to try without the group

cobalt tangle
#

ill try commands.slash_command

#

wait

cyan quail
#

Yeah same thing

cobalt tangle
#

it loads

#

uh

cyan quail
#

Interesting

cobalt tangle
#

but my previous cmd in PyX isnt being removed

cyan quail
#

I don't think groups are broken on 2.3 though?

cobalt tangle
#

and the id is correct

cyan quail
#

Odd

cobalt tangle
cyan quail
#

Can you try reinstall 2.3

cobalt tangle
#

Already did

cyan quail
#

Iirc there weren't any changes

limber urchin
cobalt tangle
#

idk

#

imma just create a new instance of a group and see if that works

cyan quail
#

You're 100% sure another pyx group doesn't exist right

cobalt tangle
#

can we have - in group names?

cyan quail
#

I don't think so? If I'm not mistaken it's limited to underscores

cyan quail
#

But I think there's an internal check for that

limber urchin
#

Just use the search feature in VS Code to find duplicate names

cobalt tangle
#

a new instance of a group fixed it @cyan quail

#

the old cmd is also gone now

cyan quail
#

Nice

#

Should be ctrl shift f

limber urchin
#

My guess would be the huge magnifying glass that says "Search"

barren garnet
cyan quail
barren garnet
#

bruh is this even a thing

cyan quail
#

How even

barren garnet
#

why :pepecry:

cyan quail
#

That's your issue I guess

limber urchin
#

How did you manage to do that?

barren garnet
limber urchin
#

It says right there

cyan quail
#

^

limber urchin
#

Read the error

barren garnet
#

ah yes

cyan quail
#

You shouldn't sync/restart that often

#

If you're using cogs, you can reload them to update the command callbacks

barren garnet
barren garnet
cyan quail
#

Well yeah to initially register them

limber urchin
#

Not 200 times

cyan quail
#

Like the name, description, options etc

#

But after that if you're only updating the command's function/logic, you only have to reload the cog

barren garnet
barren garnet
cyan quail
#

That being said I'm pretty sure you can sync without restarting the bot but that's the one thing that hasn't been fixed for a while

cobalt tangle
cyan quail
#

Well that also used to be broken but it should be fine on 2.2 and above

cobalt tangle
#

@barren garnetr u overriding on_connect

cyan quail
#

Well his issue is that he can't sync at all for the rest of the day

#

Can't do much about that

barren garnet
cobalt tangle
#

could be bz of overriding on_connect

cyan quail
#

You'd have to do it again

cobalt tangle
cyan quail
#

Bruh you literally said no earlier wyd

cobalt tangle
#

show ur on_connect please

barren garnet
cobalt tangle
#

hm?

barren garnet
cobalt tangle
#

@cyan quail i dont know abt what start() does but maybe its causing issues

cobalt tangle
barren garnet
cobalt tangle
#

code then

#

send ur few commands

#

one of them*

cyan quail
#

Please don't use 2.0

#

Just update to 2.3

barren garnet
#

200 cmds aint easy

cobalt tangle
#

@cyan quail sorry for ping but,
is there a way for implementing both default_permissions and has_permissions into one for commands.Bot for commands that use SlashCommandGroup (if this even matters)

cyan quail
# cobalt tangle <@242367619431268353> sorry for ping but, is there a way for implementing both `...
#

check decorators will work on individual subcommands, however note that default_permissions only works for the entire group; it can't apply to individual subcommands.

cobalt tangle
#

I mean the cmd is inside a group

#

I want a way to have both the default_perms and internal check in one decor

cyan quail
#

don't think that's a thing

#

and again, the default_permissions decorator doesn't work on subcommands in the first place

cobalt tangle
#

does bridge.has_permissions apply both the checks?

cyan quail
#

maybe? not sure

atomic wolf
#

How do I check if a role in a server exists?

full basin
#

Getting the role will return None if doesn't exist or not found

atomic wolf
#

ty

fervent cradle
#

How do i remove a option or edit one from a select menu? i can only find select.append but im looking for something like select.remove

atomic wolf
#

How do I change the color of a role that I created:

await guild.create_role(name="Jail", colour=discord.Colour(000000), permissions=discord.Permissions
                                    (permissions=0))
fervent cradle
#

after 0x add a hex code

atomic wolf
#

ty

lost lodge
#

how can i check if a message is a system message?

young bone
fervent cradle
#

thats not a api reference

fervent cradle
lost lodge
novel oak
#

How to fix that

young bone
obtuse juncoBOT
novel oak
tender seal
#

he still doesn't

#

show the menu

#

I'm using commands.Bot

#

don't do that

#

where are you saving the response for requests.get()?

#

oh

#

you're not trying to do that nvm

#

or are you

#

is the url in a string

fervent cradle
#

Hi, I'm new to Pycord (and bot development in general), and was just going through Pycord Guide. I needed some help regarding my ENV file where my token is.

tender seal
#

yeah so string

fervent cradle
tender seal
#

what are you trying to do with the command

tender seal
#

m

#

any error?

fervent cradle
#

The error I'm encountering is a TypeError, the token has to be in string format and even when I converted it to str type, it's still returning me that error. May I send you the code snippet?

young bone
#

why do you use requests?

tender seal
#

without the ()

#

obviously

#

and then at the bottom

#

bot.run(_token)

#

'bot' being your bot variable

young bone
#

aiohttp

#

?tag aiohttp

obtuse juncoBOT
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)

discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json%27') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author'])β€Š

For more help, see aiohttp's documentation: <http://aiohttp.readthedocs.io/en/stable/>

fervent cradle
# tender seal bot.run(_token)

Alright, I'll try doing that. I was converting my token to string type using this:

import dotenv
dotenv.load_dotenv()
token = str(os.getenv("TOKEN"))
#

It didn't work though, for some unknown reason.

young bone
#

you have to do it at your own...

tender seal
#

yeah

fervent cradle
#

Wait, I think I figured it out.

#

Alright, the TypeError is fixed but I came across another error.

#

discord.errors.LoginFailure: Improper token has been passed.

young bone
fervent cradle
#

Could anyone help me with this?
I regenerated my token and tried with the new one, but that didn't work.

fervent cradle
fervent cradle
tender seal
#

hi guys

#

how do I send a message in multiple channels at once

oblique river
#

how do i check again if the embed url is valid or not

tender seal
#

explain

oblique river
#

embed.set_image()

lost lodge
#

how can i listen for member bans or kicks?

proud mason
#

And unban

#

.rtfm discord.on_member_ban

winter condorBOT
#

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

proud mason
#

Fk this bot sadcatthumbsup

lost lodge
proud mason
lost lodge
hallow blaze
# lost lodge and kicks?

Apparently its a limitation that there isn't a kick event, you can try using discord.on_member_remove, and fetch the audit log perhaps under that.

proud mason
lost lodge
proud mason
#

Persistent views?

lost lodge
#

bot.add_view(View())

proud mason
#

Custom id on dropdown + None timeout on the view + adding the view as persistent view

#

Do all that and should be persistent

lost lodge
#

yes

proud mason
#

Yes

lost lodge
#

but remember: It have to be in a class

copper knot
#
Traceback (most recent call last):
  File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 738, in sync_commands
    app_cmds = await self.register_commands(
  File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 531, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
  File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py", line 360, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
proud mason
copper knot
#

hold on

proud mason
#

?tag missing_access

obtuse juncoBOT
copper knot
#

i fixed it, still getting the error

#

and this is my private bot, not my public one

proud mason
proud mason
copper knot
#

oh wait

#

i blame the other dev

#

im good now

proud mason
#

Lmao

#

πŸ‘

atomic wolf
#
check = cursor.find({"$and": {"guild_id": guild_id, "_id": author_id}})

(Pymongo) Does anyone know what the check returns if it doesn't exist? (Ik this isn't related to pycord)

fervent cradle
#

if it doesnt relate to pycord

#

dont post it

oblique river
#

How do I do that if it is not a url then it sends an error message
In embeds.0.image.url: Scheme "test" is not supported. Scheme must be one of ('http', 'https')

gleaming falcon
#

Python question. What's the best way to combine an f-string with a formattable token?

blah = 'asdf'
mystring = f"a={blah}&b={}" 

This doesn't work because of course the {} is being evaluated at string creation. But I also cannot escape the braces. Looks like "old-style" % works.

mystring = f"a={blah}&b=%s"
# ...
myurl = mystring % 'jkl'

Is that the best way?

oblique river
#

mystring = f"a={blah}&b=%s" + "jkl" Maybe this should work

gleaming falcon
#

Well I don't want to hardcode the addition; the string represented by "mystring" is a long querystring. I was trying to break up some aspects of it into f-string variables to increase readibility/reduce the length, but I need to combine it with the ability to apply dynamic data to the variable (Updated last example to reduce ambiguity)

fervent cradle
#

How do i make the select menu show the selected option? it just goes to back to the empty placeholder every interaction

    @discord.ui.select( 
        row=0,
        min_values = 1, 
        max_values = 1, 
        options = [ 
            discord.SelectOption(
                label="Counts",
                emoji="πŸ”’"
            ),
            discord.SelectOption(
                label="s",
                emoji="πŸ”₯"
            ),
        ]
    )
    async def select_callback(self, select: discord.ui.Select, interaction: discord.Interaction):
        await interaction.response.edit_message(content=select.values, view=self)```
oblique river
#

try this

oblique river
# fervent cradle How do i make the select menu show the selected option? it just goes to back to ...

Here is a example

class Dropdown(discord.ui.Select):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_
        options = [
            discord.SelectOption(
                label="Red", description="Your favourite colour is red", emoji="πŸŸ₯"
            ),
            discord.SelectOption(
                label="Green", description="Your favourite colour is green", emoji="🟩"
            ),
            discord.SelectOption(
                label="Blue", description="Your favourite colour is blue", emoji="🟦"
            ),
        ]

        super().__init__(
            placeholder="Choose your favourite colour...",
            min_values=1,
            max_values=1,
            options=options,
)

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message(
            f"Your favourite colour is {self.values[0]}")


class DropdownView(discord.ui.View):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_
        super().__init__()
        self.add_item(Dropdown(self.bot))

bot = discord.Bot(debug_guilds=[...])

@bot.slash_command()
async def colour(ctx: discord.ApplicationContext):
    """Sends a message with our dropdown that contains colour options."""
    view = DropdownView(bot)
    await ctx.respond("Pick your favourite colour:", view=view)```
fervent cradle
#

oh ok, so i need to seperate each select menu?

#

i will try this danke

gleaming falcon
fervent cradle
#

Max_val

#

max_value =

#
            placeholder="Choose your favourite colour...",
            min_values=1,
            max_values=1,
            options=options,
)```
fervent cradle
oblique river
#

What do you mean do you have to resend the message every time after selecting the roles?

oblique river
fervent cradle
oblique river
#

do await interaction.response.defer()

#

and remove await interaction.response.send_message(f"Your favourite colour is {self.values[0]}")

fervent cradle
#

what will that do

oblique river
#

This will not answer the interaction

#

Because with edit_message it changes the message

fervent cradle
#

so just await interaction.response.defer(DropdownView(self.bot))

oblique river
#

Normally it is just await interaction.response.defer() but you also can try await interaction.response.defer(DropdownView(self.bot))

fervent cradle
#

ah ok

oblique river
#

Let me know if it worked

fervent cradle
#

but now it gives This interaction has already been responded to before i mean the select menu is showing the item now

#

which is good, but now i cant edit the message hah

#
        await interaction.response.defer()
        await interaction.response.edit_message(content = f"Your favourite colour is {self.values[0]}", view=Dropdown(self.bot))```
#

should i do interaction.followup.edit_message()? or smth

oblique river
fervent cradle
#

i want to change the embed

#

like the text

#

the content

#

i want to

  1. select a option from the menu
  2. it shows up
  3. Content changes in the message
oblique river
# fervent cradle

That means you want only "a" to be there when he changes the message

fervent cradle
#

like lets say for example:
it starts with "hello"
and i click "bye" option
then it changes to "bye"

#

thats what i'd like

oblique river
fervent cradle
#

Thanks i appreciate it

oblique river
#
class Dropdown(discord.ui.Select):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_
        options = [
            discord.SelectOption(
                label="Hello 2", description="Your favourite colour is red", emoji="πŸŸ₯"
            ),
            discord.SelectOption(
                label="Bye", description="Your favourite colour is green", emoji="🟩"
            ),
            discord.SelectOption(
                label="Bye 2", description="Your favourite colour is blue", emoji="🟦"
            ),
        ]

        super().__init__(
            placeholder="Choose your favourite colour...",
            min_values=1,
            max_values=1,
            options=options,
)

    async def callback(self, interaction: discord.Interaction):
        if self.select.values[0] == "Hello 2":
            await interaction.response.edit_message(f"{self.values[0]}")
        elif self.select.values[0] == "Bye":
            await interaction.response.edit_message(f"{self.values[1]}")
        elif self.select.values[0] == "Bye 2":
            await interaction.response.edit_message(f"{self.values[2]}")

class DropdownView(discord.ui.View):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_
        super().__init__()
        self.add_item(Dropdown(self.bot))

bot = discord.Bot(debug_guilds=[...])

@bot.slash_command()
async def colour(ctx: discord.ApplicationContext):
    view = DropdownView(bot)
    await ctx.respond("Hello", view=view)``` try this
fervent cradle
#

Error
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given

#

it needs string, and a view=

oblique river
#

ups sorry i made a mistake

proud mason
#

I'm pretty sure that solution is unrelated to the question amd won't solve it

young bone
#

content=""

oblique river
fervent cradle
#

TypeError: Dropdown.callback() missing 1 required positional argument: 'interaction'

#
@bot.command()
async def gtn(ctx):
    await ctx.respond('Enter a number between 1 and 10.')
    guess = await bot.wait_for('message', check = lambda message: message.author == ctx.author)
    if (guess.content == '7'):
        await ctx.send(f'You guessed it!')

    else:
        await ctx.send(f'No, try again.')

Spent the last one hour trying to figure out why the heck isn't this working. I just started learning Pycord (and bot development) btw.

The bot responds with the else block when the if block returns false, just like it should. However, when the if block does return true, the bot still prints the else block. Why is that?

#

put guess.content in str()

oblique river
#
        if self.select.values[0] == "Hello 2":
            await interaction.response.edit_message(f"Hello 2")
        elif self.select.values[0] == "Bye":
            await interaction.response.edit_message(f"Bye")
        elif self.select.values[0] == "Bye 2":
            await interaction.response.edit_message(f"Bye 2")
fervent cradle
#

it needs a (content=f"{self.values[0]}", view=SOMETHING)

#

because then it doesnt know where to edit

oblique river
fervent cradle
fervent cradle
#

Why though.

#

idk man

#

try str()

#

I did, it worked (God knows why or how).

#

Thank you for the help, I genuinely appreciate it.

#

no problem

fervent cradle
#

same error

#

TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given

oblique river
#

How many colors can you take 1 ?

oblique river
#

I am so lost

fervent cradle
#

bro

#

InteractionResponse.edit_message() is a function

#

is needs 2 inputs

oblique river
#
        if self.select.values[0] == "Hello 2":
            await interaction.response.edit_message(content="Hello 2")
        elif self.select.values[0] == "Bye":
            await interaction.response.edit_message(content="Bye")
        elif self.select.values[0] == "Bye 2":
            await interaction.response.edit_message(content="Bye 2")``` try this
fervent cradle
#

1 string aka "hello" or smth, and another which is view= to know where to edit

fervent cradle
oblique river
#

content not text

#

sorry

#

if not work use edit_original_message

oblique river
fervent cradle
#

TypeError: Dropdown.callback() missing 1 required positional argument: 'interaction' BRUHHHHHHHHHHHH

#

what is this lmao

oblique river
#

Do you use edit_original_message

fervent cradle
#

await interaction.edit_original_message(f"ok")

#

yes

fervent cradle
#

βœ…

#

im just gonna go to sleep

oblique river
#

try await interaction.edit_original_message(content="ok")

fervent cradle
#

ok last test

oblique river
#

you forget something

fervent cradle
#

same error

oblique river
#

response

fervent cradle
#

no

oblique river
#

interaction.response

fervent cradle
#

its interaction.edit_original_message

oblique river
#

hmmm

fervent cradle
#

says so in api reference anyways gn thanks for trying

oblique river
#

await interaction.edit_original_message(content="Test", view=DropdownView(self.bot))

fiery tiger
#

So on_webhooks_update has just channel as parameter, How can i tell if the before name is not the same as the after name?

limber urchin
#

What do you mean by "the button"?

#

You can create a view and an instance of a button and add it to the view

#

icl?

#
    async def example(ctx, ...):
        my_view = discord.ui.View(...)
        my_button = discord.ui.Button(...)
        ...
        my_view.add_item(my_button)
        await ctx.respond(view=my_view)
twilit valley
#

Hey, is there a way to list who dmed my bot by any chance

full basin
#

Bot should have some opened dms attribute

#

.rtfm discord.Bot

twilit valley
#

.rtfm discord.Bot

twilit valley
#

hmm cant seem to find it

limber urchin
#

Did you try reading the docs on the website?

umbral island
#

Looking for some help with using custom emojis. I've never had luck using them. I've read docs that state that the bot needs to send in :AHYES~3:883745918128635904 format but discord seems to automatically remove the ID while it sends making it only send the name of the emoji. Any solutions?

@discord.slash_command()
    async def test(
        self,
        ctx: discord.ApplicationContext,
        emoji_name: discord.Option(str, description="The Emoji You Want To Test")
    ):
        print(f"Emoji Name: {emoji_name}")
        await ctx.channel.send(f"Here is the emoji: {emoji_name}")
        await ctx.respond("Sent...", ephemerel=True)
limber urchin
#

It's <:AHYES~3:883745918128635904>

umbral island
#

ive tried that as well, no luck

#

all it sends is the name

limber urchin
#

Then your bot isn't in a server with the emoji, or doesn't have permissions to use external emojis

umbral island
#

that is a specific permission??
it has admin, and is in the guild the emoji was created in.

limber urchin
umbral island
#

ahh got it. Emojis are annoying.

#

there were two emojis that looked the same but in 2 diff guilds. One the bot was in and one it was not. FalseFacePalmLaugh my brain needs a break

twilit valley
# limber urchin Did you try reading the docs on the website?

I did, can't seem to find anything. However, apparently user has an attribute dm_channel which should return NONE if no dm channel is made with them

but running the code

    @bot.command()
    async def getservers(self, ctx):  
        activeusers = self.client.users
        for user in activeusers:
            if user.dm_channel is None:
                continue
            else:
                print(f"User {user} has dm with you")

doesn't work (it should return me and it doesn't)

limber urchin
twilit valley
#

I did read the docs, I came across that, and I tried

    @bot.command()
    async def getservers(self, ctx): 
        dms = self.client.private_channels
        print(dms)
        for content in dms:
            print(content)```

output:

[]

twilit valley
silver moat
twilit valley
#

or does it only return ones where the bot initiated the dm channel

twilit valley
#

I did, it returns nothing, even though I dmed the bot before I used it

north gorge
#

Can a slash command re-call the same function without separating it out into some kind of helper function? I want to add a "play again" button at the end of a blackjack game without doing a bunch of refactoring

wild socket
#

discord.EMoji doesn't work in option type in slash commands.

wild socket
north gorge
#

ah that's a good idea

limber urchin
wild socket
#

because, there are people who have raised this issue in github, however Dorukyum responded saying to use discord.Emoji. Therefore, i believe that it is a valid option type however, its just not working or broken

limber urchin
wild socket
#

alright.

tender seal
#

how do I send a message in a bunch of channels at once

#

I'll have a list of the channel IDs

#

and probably in a for loop I'd have to do something

#

and I don't know what that something is

#

I have somewhat of an idea but

#

I'll probably need your help

errant craneBOT
#

Here's the send example.

#
Tag Search | send
#

Item not found.

tender seal
#

how do I use this bot lol

#

ok I found a guide I'll try following it

proud mason
#

.rtfm bot.get_partial_messagable

winter condorBOT
#

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

proud mason
#

Ugh

#

.rtfm bot.get_partial

proud mason
#

Yeah that

#

Wrong spelling πŸ’€

#

Pass the discord and text channel type

#

If you have a lot of channels then you might want to move away from using a for loop

#

It needs some asyncio knowledge tho

#

Create coroutines for the channel ids using list comprehension and then use asyncio.gather

proud mason
tender seal
#

btw this is a spam ping bot

#

as you can clearly see it works lol

tender seal
#

What's the DM equivalent for on_message()?

fervent cradle
#

Hi, I needed some help. So, I've been trying the following method to run my bot using it's token in the ENV file:

import dotenv
dotenv.load_dotenv()
token = str(os.getenv("TOKEN"))

After this, I've created some basic commands. At the bottom, I've said:

bot.run(token)
#

This doesn't work for some reason, I triple-checked if I had defined the token file in the same directory as my script and if it was given under quotations (in the ENV file). What could be the possible reasons for this happening?

tender seal
fervent cradle
#

None

tender seal
#

none

#

send the env file (with the token removed ofc)

#

or just copy and paste

fervent cradle
tender seal
#

yeah same

fervent cradle
tender seal
#

I'll try that

tender seal
#

are you on linux?

fervent cradle
#

Although it's not very secure.

tender seal
#

probably not

fervent cradle
#

No, Windows.

tender seal
#

open powershell,
then run

pip list | Findstr dotenv
fervent cradle
tender seal
#

I mean yeah

#

but nvm that

fervent cradle
#

Under quotations is my token of course, lol

fervent cradle
tender seal
#

tell me what shows up

#

btw if you have dotenv and python-dotenv do

#

pip uninstall dotenv
pip uninstall python-dotenv
pip install python-dotenv

fervent cradle
#

python-dotenv 0.21.0

tender seal
#

ok so you have python-dotenv only?

fervent cradle
#

This showed up on running pip list | Findstr dotenv

tender seal
#

try reinstalling

fervent cradle
#

Alright

tender seal
#

it

proud mason
fervent cradle
proud mason
tender seal
proud mason
tender seal
#

that could be the problem?

proud mason
#

Mostly

tender seal
#

env files don't like spaces?

#

lol I didn't know..

#

sorry if you've uninstalled python-dotenv already.

proud mason
#

Lol tias

proud mason
# tender seal k

You can use the asyncio.gather method and it would be much faster

fervent cradle
# fervent cradle Perhaps

On saying pip uninstall dotenv, it skipped it since "it was not installed". And on running pip uninstall python-dotenv, it did what it was supposed to.

fervent cradle
#

(Gotta reinstall python-dotenv)

fervent cradle
#

I tried printing the token. Here's the output:
None

tender seal
#

what's the DM equivalent of on_message()?

#

sorry for ping

#

I wanna listen for messages in a dm channel.

fervent cradle
#
dotenv.load_dotenv('token.env')
token = str(os.getenv("TOKEN"))

Here basically instead of 'token.env' (which is what the file is called), I was mentioning the entire path of the ENV file despite of it being in the same directory as my script.

proud mason
tender seal
cold hamlet
#

How do I get an attachment in a slash command option? x: discord.File? x: discord.Attachment?

cold hamlet
#

cheers

cobalt tangle
#

How would I make all my commands guild-only

young bone
cobalt tangle
#

Not adding the decorating to each and every one

#

I have no idea how to do this rip

#

in a recommended and safe way

young bone
cobalt tangle
young bone
cobalt tangle
#

That's my question here...

young bone
#

you still have to add it to each command

#

and vs code can do it for you

oblique river
#
if value := self.children[0].value:
            if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
                await interaction.response.send_message(content="Url Invalid")
                return
        else:
            embed.set_image(url=self.children[0].value)```it does not send my embed image
weak marlin
#

2 of my commands aren't registering wtf

#

there's no reason that I can think of as to why they aren't registering

#

they just.. aren't popping up in the slash commands list

cobalt tangle
#

Send the code of the cmd that's not registering

#

AND are you overriding on_connect

weak marlin
# cobalt tangle Send the code of the cmd that's not registering

I made the top one to check if it was an issue with the thread_count command

@client.command(description="test command")
async def test(ctx):
    await ctx.respond("Test complete!")

@client.command(description="Returns the ammount of threads there are; may take a while.")
async def thread_count(ctx, channel : discord.ForumChannel):

    total_threads = 0
    if channel.id == 1046978593059778661:

        for thread in channel.threads:

            await asyncio.sleep(0.5)
            total_threads = total_threads + 1
        await ctx.respond("There are " + total_threads + "in the forums channel.")
#

but neither register

cobalt tangle
#

@weak marlin discord.Bot I assume?

weak marlin
#

mhm

cobalt tangle
#

If you create another cmd, does it register?

weak marlin
#

hold on

#

no it doesn't

cobalt tangle
#

Hm

weak marlin
#

does discord have a uhh

#

a thing called secrets

cobalt tangle
#

Maybe check the integrations tab in server settings, that's what discord gives u

weak marlin
#

sure

cobalt tangle
young bone
#

async for thread
.
.

weak marlin
cobalt tangle
#

Do you have a on_connect function

young bone
weak marlin
#
Traceback (most recent call last):
  File "C:\Users\tsuyo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\tsuyo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\tsuyo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'async for' requires an object with __aiter__ method, got list
cobalt tangle
weak marlin
cobalt tangle
#

No

weak marlin
#

well then I don't

cobalt tangle
#

Hm

#

@weak marlin Try getting all the application cmds and printing it

weak marlin
#

think I found the problem

#

apparently I can't name a file "secrets"

#

that and

#
await ctx.respond("There are " + total_threads + "in the forums channel.")

had to change this to:

await ctx.respond(f"There are {total_threads} in the forum(s) channel.")
#

yeah it worked

#

oop need to remove those brackets

cobalt tangle
#

I don't know what you mean by file named secret but okay

weak marlin
cobalt tangle
#

Oh

weak marlin
#

I have a file named secrets that I import stuff from

cobalt tangle
#

Ohhhh

weak marlin
#

discord has a module named secrets or sum like that

#

ty for the help tho

steel wedge
#

how do you remove all roles a user has?

young bone
steel wedge
#

yes

#

i just cant rembers the sytax for it

#

i thought it was this await member.edit(roles=[])

#

but it wasnt

young bone
#

remove_roles()

steel wedge
#

is it just member.remove_roles()

#

i swear i tried that

young bone
#

with one by one?

steel wedge
#

yeah

#

for i in member.roles:

#

member.remove_roles(i)

limber urchin
#

it's a coroutine

oblique river
#
if value := self.children[0].value:
            if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
                await interaction.response.send_message(content="Url Invalid")
                return
        else:
            embed.set_image(url=self.children[0].value)```it does not send my embed image
limber urchin
#

You're not sending the embed at all

oblique river
#

clear but it is not the whole code

limber urchin
#

Then show the whole code

oblique river
#
class MyModal(Modal):
    def __init__(self, ...):
        self.add_item(InputText(...)

    async def callback(self, inter: discord.Interaction):
      ...
      if value := self.children[0].value:
            if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
                await interaction.response.send_message(content="Url Invalid")
                return
        else:
            embed.set_image(url=self.children[0].value)
      ...```this is the biggest part of the code but it is about the `self.children[0].value`
limber urchin
#

And what is self.children[0].value?

oblique river
#

self.add_item(InputText(...)

limber urchin
#

And how do you know the URL is an image?

oblique river
#
        if value := self.children[0].value:
            if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
                await interaction.response.send_message(content="Url Invalid")
                return
        else:
            embed.set_image(url=self.children[0].value)
```Well this is a Text Input the user can then write a link or not that is up to the user but if it is wrong an error should occur which is what happens with the code here but if the user enters a correct link the image is not sent at all just the embed title and description
limber urchin
#

That regex only checks for a valid URL, you still don't know if the URL points to an image or not

oblique river
#

Oh and how do I do that ?

limber urchin
#

Dunno, I don't know how to write regex

oblique river
#

But what I don't understand is if the URL is already checked I don't understand why I have to insert if it is an image or not

#

with this r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"

limber urchin
#

So what if the user enters https://www.google.com

#

do you think that will show an image?

oblique river
#

No

#

πŸ˜…

limber urchin
#

But it will pass your regex

#

because it's a valid URL

oblique river
#

and how do i check now if it is a picture or not and how do i insert that in the code like this

limber urchin
#

I told you, I don't know

#

look it up on google

oblique river
#

^(?:\w|\s|\d){1,19}\.(?:jpg|jpeg|png|gif|bmp|webp)$ ?

#

i will try

cobalt tangle
#

For statement is a waste of time

oblique river
# limber urchin look it up on google
def is_url_image(image_url):
   image_formats = ("image/png", "image/jpeg", "image/jpg")
   r = requests.head(image_url)
   if r.headers["content-type"] in image_formats:
      return True
   return False``` is it possible to put that in my code
#
        if value := self.children[0].value:
            if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
                await interaction.response.send_message(content="Url Invalid")
                return
        else:
            embed.set_image(url=self.children[0].value)```
cobalt tangle
#

It's highly recommended like so

limber urchin
#

?tag requests

obtuse juncoBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

fervent cradle
#

np

foggy hemlock
#

I am getting AttributeError: 'Select' object has no attribute 'select_type' whenever using a channel select

#

the select is being sent normally, just can't be used

full basin
#

Py-cord version?

foggy hemlock
#

2.3.1

#

python 3.10.8

#

code```py
class View1(discord.ui.View):
def init(self):
super().init(timeout=None)

@discord.ui.select(select_type=discord.ComponentType.channel_select, placeholder="channels", channel_types=[discord.ChannelType.text], custom_id="channels_select", min_values=0, max_values=5)
async def callback(self, select: List[discord.TextChannel], interaction: discord.Interaction) -> None:
    print(select)
    await interaction.response.send_message("channels saved: \n" + "\n".join([c.id for c in select]))
graceful mason
#

yo guys is this valid python code?

a = dict.get("asd") or 0```
foggy hemlock
#

yes, but you can do a = dict.get("asd", 0)

graceful mason
#

ah, nice thanks

steel wedge
#

ctx.guild.default_role is everyone but is the one for nitro booster?

errant craneBOT
#

discord/ui/select.py line 66

class Select(Item[V]):```