#Basic Pycord Help (Quick Questions Only)

1 messages · Page 48 of 1

astral mist
#

20 min goes by

boreal dust
astral mist
#

oh

boreal dust
#

I've been using dpy+dpy-slash-command

#

with on_component

#

how do i do it now?

astral mist
#

was this it

boreal dust
astral mist
#

it didnt rlly help

finite flame
#

ayo, why is on_ready triggering, but the command isn't?

import asyncio
from hypercorn.config import Config
from hypercorn.asyncio import serve
from quart import Quart
import discord
from discord.ext.commands import Bot
import signal


loop = asyncio.new_event_loop()

intends = discord.Intents.default()
token = "token"

bot = Bot(intends=intends, command_prefix="!", loop=loop)

config = Config()
config.bind = ["localhost:8000"]

app = Quart(__name__)


@app.route("/")
async def index():
    return "Hello World"


@bot.command()
async def test(_):
    print("test")


@bot.event
async def on_ready():
    print("Bot ready")


shutdown_event = asyncio.Event()


def _signal_handler():
    shutdown_event.set()


# loop.add_signal_handler(signal.SIGTERM, _signal_handler)

try:
    bot_task = loop.create_task(bot.start(token))
    web_task = loop.create_task(serve(app, config, shutdown_trigger=shutdown_event.wait))
    loop.run_until_complete(asyncio.gather(bot_task, web_task))
except KeyboardInterrupt:
    loop.run_until_complete(bot.close())
finally:
    loop.close()
proud mason
#

async def test(_):
and you have a _ inside your cmd

#

at least name it smth shrug

#

we like to call it ctx

finite flame
finite flame
proud mason
proud mason
#

or you can use asyncio.gather

#

lets continue in #1059472193181991013

finite flame
#

yep

fast badger
#

part of my code is suddenly throwing an error saying that 'interaction object has no attribute author' when using interaction.author.id, how else can i pull the user's id?

fast badger
rare ice
#

don't cross post.

rare ice
#

that means you most likely have multiple instances of the bot

#

send your code

fervent cradle
#

this always returns None how do i fix that, the user object is returning fine but dm_channel attribute always returns None even though the dms exist with the bot

user = bot.get_user(1005734571628838953)
print(user.dm_channel)
rare ice
#

.rtfm discord.User.dm_channel

winter condorBOT
rare ice
#

you could also use .fetch_user

proud mason
full basin
#

You're not showing how you're initializing the view

copper knot
#

is pillow compatible with pycord?

young bone
copper knot
serene spindle
copper knot
#

i got it working

#

apparently pillow doesnt like file-less methods

flat merlin
#

Is it possible to send two modals to a single command?

full basin
#

No

#

You can only send one per interaction

silver moat
#

and modals cannot be chained

flat merlin
#

That basically means my bot depends on message content, it seems. 🤔

silver moat
#

modals can have many text inputs

round rivet
full basin
#

You can just respond to the modal with a button which opens the next modal lol

flat merlin
#

Five text fields isn't enough to run through the entire process, and I want it chained in a single command, for the sake of the user.

full basin
#

Thank discord

silver moat
#

if you could explain your current with message-content system, we can try to help to make it work without message-content

flat merlin
#

It loops through an array of messages, which it sends and then awaits the input of the user, basically. That was the old thing I wrote.

silver moat
#

what type of input does it wait for?

flat merlin
#

It awaits a message using the bot.wait_for function, and simply tries again if the input isn't right. The input could be an integer or just a string, that depends on where exactly in which process you are.

silver moat
#

is it like a google forms?

flat merlin
#

I think you could compare it to that, I'm not quite familiar with Google forms.

#

The goal is to guide the user through creating a character, and they need a character to play the game. The things they fill in affect the game mechanics.

silver moat
#

and there are more than 5 questions.

flat merlin
#

Yes.

silver moat
#

well, you can ask one question at the time per modal to validate the input

flat merlin
#

And if I don't want the user to use a command for each next step?

silver moat
#

send a message with a button

flat merlin
#

Could I respond to the initial message with a message with multiple buttons, where each button represents a modal?

silver moat
#

yeah

flat merlin
#

And could I only enable those buttons once the previous modal was filled in correctly? I think that should be possible. 🤔

silver moat
#

yeah

viral peak
#

what does this mean?
INFO:discord.gateway:Websocket closed with 1000, cannot reconnect.

#

happens on start then crashes

proud mason
fervent cradle
#
    async def third_button_callback(self, button, interaction):
        if "account" in interaction.data['custom_id']:
            if interaction.channel.id == TICKET_CHANNEL:
                guild = bot.get_guild(GUILD_ID)
                ticket_owner = interaction.user
                for ticket in guild.channels:
                    if str(interaction.user.id) in ticket.name:
                        embed = discord.Embed(title=f"You can only open one Ticket!", description=f"Here is your opened Ticket --> {ticket.mention}", color=0xff0000)
                        await interaction.response.send_message(embed=embed, ephemeral=True)
                        return

                open_ticket = bot.get_channel(OPEN_TICKET_LOGS)
                
                embed3 = discord.Embed(title='**Ticket Opened**', description=f"{ticket.mention} Was created!", color=config.EMBED_COLOR)

                category = bot.get_channel(CATEGORY_ID4)
                ticket_channel = await guild.create_text_channel(f"ticket-eft-accounts-{ticket_owner}", category=category,
                                                                topic=f"Ticket from {interaction.user} \nUser-ID: {interaction.user.id}")

                await ticket_channel.set_permissions(guild.get_role(TEAM_ROLE1), send_messages=True, read_messages=True, add_reactions=False,
                                                    embed_links=True, attach_files=True, read_message_history=True,
                                                    external_emojis=True)
                await ticket_channel.set_permissions(interaction.user, send_messages=True, read_messages=True, add_reactions=False,
                                                    embed_links=True, attach_files=True, read_message_history=True,
                                                    external_emojis=True)
                await ticket_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False, view_channel=False)
                embed = discord.Embed(description=f'Welcome {interaction.user.mention}!\n'
                                                   'Hello, How can we help you?',
                                                color=config.EMBED_COLOR)
                await ticket_channel.send(embed=embed, view=TicketClose())
                embed = discord.Embed(description=f'📬 Ticket was Created!', color=0xe800ff)
                await interaction.response.send_message(embed=embed, ephemeral=True)  ```

No error was thrown just not creating the ticket. button is shown and everything on the embed as it should be.
#
:/home/container$ if [[ -d .git ]] && [[ ${AUTO_UPDATE} == "1" ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip install -U --prefix .local ${PY_PACKAGES}; fi; if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/${BOT_PY_FILE}
Requirement already satisfied: py-cord in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 1)) (2.3.2)
Requirement already satisfied: aiohttp in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 2)) (3.8.3)
Requirement already satisfied: asyncio in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 3)) (3.4.3)
Requirement already satisfied: pymysql in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 4)) (1.0.2)
Requirement already satisfied: requests in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 5)) (2.28.1)
Requirement already satisfied: python-dateutil in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 6)) (2.8.2)
Requirement already satisfied: typing-extensions<5,>=4 in ./.local/lib/python3.10/site-packages (from py-cord->-r requirements.txt (line 1)) (4.4.0)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (2.1.1)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (1.8.2)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (6.0.4)
Requirement already satisfied: attrs>=17.3.0 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (22.2.0)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (4.0.2)
Requirement already satisfied: frozenlist>=1.1.1 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (1.3.3)
Requirement already satisfied: aiosignal>=1.1.2 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (1.3.1)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in ./.local/lib/python3.10/site-packages (from requests->-r requirements.txt (line 5)) (1.26.13)
Requirement already satisfied: certifi>=2017.4.17 in ./.local/lib/python3.10/site-packages (from requests->-r requirements.txt (line 5)) (2022.12.7)
Requirement already satisfied: idna<4,>=2.5 in ./.local/lib/python3.10/site-packages (from requests->-r requirements.txt (line 5)) (3.4)
Requirement already satisfied: six>=1.5 in ./.local/lib/python3.10/site-packages (from python-dateutil->-r requirements.txt (line 6)) (1.16.0)
- Elevate Manager#1601 has connected to Discord!
- Discord version: 2.3.2
- Python version: 3.10.9 (main, Dec 21 2022, 08:51:48) [GCC 10.2.1 20210110]
- Logged in as: Elevate Manager (1049914370001489981)
- Status Loaded
- Tickets Loaded
- Buttons Loaded
- Elevate Manager | Starlight#5980```
silver moat
#

@fervent cradle check if your if statements are correct.

fervent cradle
dim cape
#

With a ban how do i write a reason

full basin
#

.rtfm Member.ban

full basin
lost lodge
#

Hey guys! How can i fix this error?

code:

            embed = discord.Embed(title="Ticket claimed!",
                                  description=f"You will be supportet now by {interaction.user.mention}",
                              colour=0x2f3136)
            await interaction.response.send_message(embed=embed)
            button.disabled = True
            button.label = "claimed!"
            await interaction.response.edit_message(view=self)```

error:

discord.errors.InteractionResponded: This interaction has already been responded to before```

full basin
#

Use a followup

#

.rtfm followup.edit

winter condorBOT
#

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

full basin
#

.rtfm interaction.followup

winter condorBOT
lost lodge
full basin
#

No

#

I see you're trying to edit the original message

#

So use await interaction.original_response()

#

That returns the original response

#

Then you can edit it

lost lodge
full basin
#

Returns a message object

lost lodge
full basin
#

No

#

message = await interaction...

#

message.edit

silver moat
#
message = await interaction.original_response()
await message.edit(view=self)
subtle jay
#

Can you send multiple modals on one interaction?

silver moat
#

no

wintry cosmos
#
@discord.slash_command(description="Löscht den aktuellen Channel")
    @has_permissions(administrator=True)
    async def delchannel(self, ctx):
      await ctx.respond("Channel löschen?", ephemeral=True)
      if ctx.response == "Y":
        await ctx.channel.delete()

Hey guys, i want to reply to the bot's response with "Y" and it should delete the channel. But not with ctx.response == "Y".. do you know a function or way to do this?

woeful spindle
#

.rtfm wait_for

wintry cosmos
#

Niceee

silver moat
fringe socket
#

Can anyone see what's wrong with this code? For some reason, it always says that I am incorrect.

@bot.command(name='scramble')
async def scramble(ctx):
    # Generate a random word
    original_word = random.choice(['apple', 'banana', 'cherry', 'durian', 'elderberry', 'fig', 'grape'])

    # Scramble the chosen word
    scrambled_word = ''.join(random.sample(original_word, len(original_word)))

    # Send a message to the channel asking the user to guess the original word
    await ctx.send(f'Can you guess the original word? The scrambled word is: {scrambled_word}')

    # Wait for the user's response
    response = await bot.wait_for("message", timeout=30.0)

    # Check if the user's response is correct
    if response.content.lower() == original_word.lower():
        await ctx.respond('Correct!')
    else:
        await ctx.respond(f'Incorrect. The original word was: {original_word}')
fringe socket
#

why?

proud mason
#

Some other message might get picked up

#

Add a check for author and channel

fringe socket
#

i did that before and it didn't work

proud mason
#

.rtfm wait_for

proud mason
#

See how to do it in docs

fringe socket
#

I totally didn't get ChatGPT to fix my code because my debugger broke

proud mason
#

Also, print original word and response.content. and see what you get

proud mason
limber urchin
#

People really be trying to get spoonfed by an AI nowadays huh

fringe socket
#

and because I didn't get enough sleep 😔

limber urchin
proud mason
#

It's good for asking about coding concepts, but the code won't work. It can't differentiate between dpy and forks, and the data becomes quickly outdated

fringe socket
proud mason
#

How can you break your debugger-

limber urchin
#

That's what I'm wondering too

#

And why not try to fix that, instead of blindly writing code?

fringe socket
#

skull

#

💀 Unknown intereacitons

#

💀 I can't fucking type

woeful spindle
proud mason
#

Hot take: mobile programming sucks

#

I've tried

woeful spindle
#

my only option

silver moat
#

Sterile help channels thanks.

round rivet
#

this one's already been contaminated

copper knot
lost lodge
#
            embed = discord.Embed(title="Ticket claimed!",
                                  description=f"You will be supportet now by {interaction.user.mention}",
                              colour=0x2f3136)
            await interaction.response.send_message(embed=embed)
            button.disabled = True
            button.label = "claimed!"
            message = await interaction.original_response()
            await message.edit(view=self)```
storm hinge
#

hi everyone, i just want to know what to put in discord.Member.add_roles(...)
the docs say to put in *discord.abc.Snowflake, so i put in a discord.Object(role id here) thing.

it said unknown role. am i doing something wrong, or did i just put in the wrong role iD?

floral leaf
storm hinge
floral leaf
storm hinge
floral leaf
# storm hinge `add_role`

I checked the docs for it and I can‘t find it anymore I guess they removed it so use member.add_roles([member.guild.get_role(RoleID)])

floral leaf
# storm hinge ah thanks

It’s not the best solution, you can better use this for a cleaner design:
roles = []
roles.append(member.guild.get_role(RoleID))
await member.add_roles(roles)

storm hinge
#

ah ok

#

thanks

floral leaf
#

You‘re welcome

lost lodge
floral leaf
lost lodge
floral leaf
#

instead await interaction.original_response()

lost lodge
# floral leaf use interaction.original_message() instead
/Development/Python/TeamMLG/teammlg-discord/views/ticketView.py:135: DeprecationWarning: Interaction.original_message is deprecated since version 2.2, consider using Interaction.original_response instead.
  message12 = await interaction.original_message()```
lost lodge
#

py-cord 2.3.0

storm hinge
#
  File "/home/runner/AK17-EVA/venv/lib/python3.8/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "main.py", line 112, in button_callback
    await interaction.user.add_roles(interaction.user.guild.get_role(
  File "/home/runner/AK17-EVA/venv/lib/python3.8/site-packages/discord/member.py", line 1007, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

what is going on?

lost lodge
young bone
lost lodge
woeful spindle
dawn widget
#

I am a bit new to pycord. Is there anyway I can make the bot wait sending the audio from the mp3 file before sending the next one?

-> I used time.sleep() but that's not the best solution

young bone
#

use asyncio.sleep()

dawn widget
#

oh

#

my bad thanks

lost lodge
dusty linden
#

Does pycord not have the on_raw_member_remove event?

young bone
#

only on_member_remove

dusty linden
#

shit

floral leaf
dusty linden
#

To put it simple coolThumbsUp

floral leaf
dusty linden
young bone
rare garnet
#

how long does it take for guild commands to register once you start the bot

rare garnet
#

it doesnt work 🥹

#

i tried everything

rare garnet
#

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

#

whats this.

rare garnet
#

yeah but like where exactly

rare garnet
#

wait found it

#

nvm thanks :D

#

Application Command raised an exception: AttributeError: 'Confirm_view' object has no attribute 'children'

#

i ama go cry now

full basin
#

code...

rare garnet
#
class Confirm_view(discord.ui.View):
    def __init__(self):
        self.value = None

    @discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, emoji="✅")
    async def button_callback(self, button, interaction):
       await interaction.response.send_message("Confirming", ephemeral=True)
       self.value = True
       self.stop()

    @discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, emoji="❌")
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("Cancelling", ephemeral=True)
        self.value = False
        self.stop()
silver moat
#

full traceback

full basin
#

You're missing super().init

rare garnet
#

uh

full basin
#

You're overriding the init method

rare garnet
silver moat
full basin
#

Yed

#

Too lazy to actual type it

silver moat
#

💀

rare garnet
#

it worked :D

silver moat
rare garnet
naive pagoda
#

I have an issue with Select Menu. I want to make it so that people can select multiple times one brand they can give a point and one brand they can take the point from. The issue is that the items are kept in select_menu.values even after when nothing is selected anymore. Do you know a way of how to delete selected values from select_menu? Or refresh it? I tried disabling and enabling it, but it didn't help.

round rivet
lost lodge
#

Guys how can i import a var from a command in a cog?

silver moat
lost lodge
silver moat
#

databases?

lost lodge
#

no

#

just an embed

silver moat
#

is the embed dynamic?

lost lodge
#

no

knotty surge
#

There anyway to stop someone executing a command which is already being executed. so if I had a command which sends "Hello World" stop it from being spammed for a duration of time?

silver moat
# lost lodge no

My understanding is that you want to get an embed from somewhere to use somewhere else?

silver moat
#

Create another file somewhere (I will refer to this as utils.py) and from utils import embed

#

for both the command in the cog and the somewhere else

lost lodge
#

ok

silver moat
#

names don't have to be the same but I assume you get the idea

silver moat
#

Is it the user, the developer, a moderator, or who?

knotty surge
#

user

silver moat
#

what are you trying to stop

#

a for-loop, while-loop or something else?

#

@knotty surge ?

knotty surge
#

So to prevent

#

./make and then ./make

#

being used twice

silver moat
#

You can also add a cooldown, instead.

knotty surge
#

how would you add a cooldown?

dusty linden
#

@knotty surge
Depends on how your code works but there are cooldown command decorators.

#

You could also make a custom bucket.

#

Buckets are cool to use as you can reset them once your process is finished.

silver moat
#

buckets are very cool

knotty surge
#

Any documentation going on?

dusty linden
#

Not sure

#

@knotty surge this might help:

Simple command decorator:
@commands.cooldown(1, 5, commands.BucketType.user)

I feel like this is what you're looking for though:
cooldown = commands.CooldownMapping.from_cooldown(1, 5, commands.BucketType.member)
bucket = cooldown.get_bucket(whatever)
retry = bucket.update_rate_limit()
if retry_after:
return
bucket.reset()

#

You might also want to look at the max_concurrency decorator.

young flint
#

my presence intent doesnt work

#

member.activities is always None for some reason

#

and yes, intents.presences is True

silver moat
young flint
silver moat
#

i don't know then

proud mason
modest turtle
#

What's gonna be added in v3?

#

I pray to God let it be async multiprocessing

#

I have 4 cores at least, 4 times more requests

umbral island
#

is there a way you can get the str of a members presence? (the client's presence specifically)

umbral island
silver moat
#

are you talking about any user or just your own bot?

umbral island
#

just the client, my own bot

silver moat
#

Just a reminder, please do not use any client modifications; they are against Discord ToS.

umbral island
#

what..?

#

what do you mean by that

silver moat
umbral island
#

thank you

silver moat
umbral island
#

thanks for the warning though

silver moat
#

bot.me returns your bot as the user

umbral island
#

didnt meant to respond to that

silver moat
#

bot.me.activity returns the activity

umbral island
#

"Using applications such as BetterDiscord, Powercord, or similar is against Discord Terms of Service; it can get you banned."

responding to this ^

umbral island
umbral island
#

okay, just confused me lol seems super random

copper knot
copper knot
umbral island
silver moat
silver moat
#

are you even paying attention?

full basin
#

With a proper IDE you should be able to fix it 👍

#

That too

nova mirage
#

Hello, anyone know how to fix this error?

Fatal error in launcher: Unable to create process using '"c:\users\attle\appdata\local\programs\python\python35\python.exe" "C:\Users\attle\AppData\Local\Programs\Python\Python35\Scripts\pip.exe" install -r requirements.txt': The system cannot find the file specified.

Yes, there's a file that is called requirements.txt and I've got the latest version of pycord.

rare ice
silver moat
#

what is python35

nova mirage
#

To be honest, I would have no clue. I just installed pycord and it put whatever files it needed I guess.

limber urchin
#

You're using Python 3.5

#

PyCord requires 3.8 or higher

nova mirage
#

I do have 3.11

limber urchin
#

Sure, but you're not using it to run your bot

#

This indicates that you're running it with 3.5

nova mirage
#

How would I go by switching it to the 3.11 then?

#

Because for some reason it keeps defaulting to that version which is clearly the wrong version. I did indeed uninstall all the python things that showed up in my control panel.

spare juniper
#

i think python3.11 may work?

i know python3.10 works

limber urchin
#

3.11 does work if you use the latest version of pycord

spare juniper
nova mirage
#

Seems to be working now anyways. Thanks for the help!

fringe socket
#

Hey guys, how can I get my bot to work faster? Its average ping is about 450ms

fringe socket
#

Railway

#

Should I use a custom gateway or something?

limber urchin
#

Get a host located in the US, don't use free hosts, make sure your host has good network stats

thorny stag
#

How do I use my bot to create an emoji? Can I get an example?

thorny stag
limber urchin
limber urchin
spare juniper
#

just liek do Guild.create_custom_emoji('name', 'image')

#

its as shrimple as that

thorny stag
#

Figured it out

fringe socket
limber urchin
#

It's not like your users are connecting directly to your bot kek

fringe socket
#

ah yeah

#

anyways i cant afford paid hosting omegalul

limber urchin
#

NPCMechanicShrug then you're probably stuck with shit ping

silver moat
#

unless you are using music bots or something

umbral island
rare garnet
#

is there any quick example on slash command followup?

umbral island
umbral island
#

Guide can be better than docs sometimes

#
@discord.slash_command(description="Test.")
    async def test(
        self,
        ctx: discord.ApplicationContext,
    ):
        await ctx.defer()
        # Do stuff here
        ...

        # send the response
        await ctx.respond(...)
        
        # if you want to send another message after the ctx.respond, use channel.send
#

for slash commands, ctx.respond will respond to the deferral.

if you want to send another message after this, you must use channel.send instead of ctx.respond

limber urchin
#

You do not need to use defer unless your command takes longer than 3 seconds to execute

umbral island
north gorge
#

Is there a quick one-liner for getting all members who have a role?

humble rapids
winter condorBOT
north gorge
#

appreciate ya both

proud mason
humble rapids
#

Are all guild members cached? For example in a large guild of ~4000 people

#

(Fetching was just an assumption, I dunno the limitations)

proud mason
#

If you have the members and guild intent, it should be

#

Oh wait actually there is role members too

#

.rtfm role.members

winter condorBOT
humble rapids
#

Oh, that's useful

proud mason
#

@north gorge there you go. This is the fastest and most efficient way

humble rapids
#

I almost forgot I came here with a question of my own lol
What's a way I can allow a webhook to trigger a @bot.command?

Edit: I found this hacky feeling workaround after a bit of googling, but I don't feel comfortable with it as a permanent solution:

@bot.event
async def on_message(message: discord.Message):
    ctx = await bot.get_context(message)
    if ctx.valid and message.author.bot:
        await bot.invoke(ctx)```
north gorge
#

that's exactly what I was looking for, tyvm

proud mason
humble rapids
#

Mhmm

proud mason
humble rapids
#

The command will work for both users (through the normal @bot.command) and bots (through the on_message handler only) which works for my needs

proud mason
#

you are overriding on message. So normal @bot.command will stop working

humble rapids
#

Eh? It still works for me SoraQuestionMark

proud mason
#

.

#

Huh

rare garnet
#

commands.is_owner().predicate just wanna know whats .predicate in this?

quasi stratus
#

Hello, i'm migrating all my commands to slash commands and i would like to know if anyone could tell me how to solve this issue.
I have a command that takes 2 arguments :

  • winner of type discord.User
  • foes of type *discord.User because i have one winner but one or more foes/loosers in the game.

If i use in discord.Option and the function tuple[discord.User] i get a unique str with every foes separated by a space, how could i get a list of users with one parameter (or maybe there's a trick to give as many parameters as i want ?

misty yew
misty yew
proud mason
quasi stratus
#

But it's still limited to one value

proud mason
quasi stratus
#

np

#

Never used it, i'll check

proud mason
#

👍

quasi stratus
#

Ho !

proud mason
#

.rtfm user_select

winter condorBOT
quasi stratus
#

thanks ❤️

proud mason
#

🙃

west venture
#

hey guys

#

how do i use commands.cooldown() for different role for same command

#

i used this

@commands.cooldown(1, 43200, commands.BucketType.user(lambda u: u.top_role.name == 'Basic'))

but it doesnt works

#

.rtfm cooldown

errant craneBOT
#

Here's the cooldown example.

fervent cradle
#

hey is there a way to set default command permissions now in pycord? i heard that was released in the discord api a while ago

#

is it possible to respond to multiple clicks of a button? Ex. it sends 1 then 2 then 3 and so on?

spare juniper
#

What is 1, 2, and 3

fervent cradle
#

So you click the button it sends you 1, then you click it again it sends you 2 and so on

storm oyster
fervent cradle
modest maple
fervent cradle
#

Using interaction.response.send_message() multiple times give me an error

young bone
young bone
#

interaction gives you anything that you need

fervent cradle
#

Thank you so much

modest maple
#

how do i get a webhook message id so i can delete it later on?

west venture
errant craneBOT
#

An HTTP exception has occured: 400 HTTPException: Invalid Form Body
In data.components.0.components.0.url: Not a well formed URL.

west venture
#

@proud mason

west venture
full basin
#

Pinging random people won't help you faster

#

.tag idw

winter condorBOT
#

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

rare ice
#

Tried doing this wish jsk and it didn’t add the slash command manually, no errors.

async def f(ctx):
  await ctx.respond('foo', ephemeral=True)
a = discord.SlashCommand(name="ad", description="This", func=f)
_bot.add_application_command(a)```
proud mason
#

.rtfm bot.sync_commands

rare ice
north gorge
#

Is there some trick to getting an @ role mention to work in an embed? It looks like it renders correctly, yet it doesn't ping the role

winter condorBOT
grizzled sentinel
#

I dont think a ping works in an embed

proud mason
rare ice
#

Oh yeah it didn’t ping in an embed

north gorge
#

ah ok, that makes sense, thanks people

proud mason
#

brb

#

alr decorator uses the same stuff

proud mason
#

and then see

rare ice
#

yeah it works now, thanks

#

When does await bot.sync_commands() run when starting up the bot? does it run during on_ready?

proud mason
#

If you add the custom slash cmds before running the bot, then you don't need to call sync cmds yourself

rare ice
#

k

rare ice
#

after i use remove_application_command, do I have to re-run bot.sync_commands?

proud mason
rare ice
#

k

rare ice
#

i dont want to have to have it resync all commands since that takes longer

proud mason
#

i dont think sync commands resyncs all cmds

#

brb

proud mason
rare ice
#

bruh

#

then i have to resync all commands

#

thats going to take 4 years

#

although its quicker than it will take for my dad to come back

proud mason
#

is the custom cmd a guild cmd?

rare ice
safe stirrup
#

To clarify, is the commands module no longer necessary for slash commands? I read somewhere this was the case.

proud mason
safe stirrup
#

And the guide seems to follow that concept

proud mason
proud mason
proud mason
safe stirrup
#

Sweet. Is there really any purpose to using it anymore other than if you're sticking with prefix?

proud mason
rare ice
safe stirrup
#

time to rewrite a good portion of my bot! O: thanks

proud mason
#

or if you are brave then you can manually do stuff

rare ice
#

k

#

it still takes a long time :/

loud holly
#

Can ephemeral messages be deleted?

#

Discord supports it, however does pycord support it?

proud mason
#

yes

loud holly
# proud mason yes

Hmmm, I'm not able to delete ephemeral messages, it comes with unknown webhook

#

I tried

interaction.message.delete()

Msg: discord.InteractionMessage = await interaction.original_response()
Msg.delete()
rare ice
#

.rtfm delete_original_response

winter condorBOT
loud holly
lost lodge
#

Hello, how can i check if an option was selected or unselected in a select menu?

lost lodge
rare ice
lost lodge
#

ok

fervent cradle
#

Why ctx.user.status always return offline?

rare ice
fervent cradle
full basin
#

You don't have presence intents

fervent cradle
full basin
#

Members intents?

fervent cradle
full basin
#

Hm

#

You're definitely missing some intent

fervent cradle
#

i've got all intents

#

i use Intents.all()

silver moat
fervent cradle
#

right?

silver moat
#

I would say just fetch the user

#

or member, if in a guild

fervent cradle
silver moat
#

.rtfm user.roles

winter condorBOT
#

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

silver moat
#

.rtfm member.roles

winter condorBOT
wintry cosmos
#

What was the thing with ctx.author.avatar.url if the user has just default avatar, wasnt there a way to display both ways?

wintry cosmos
#

yes! thanks

uncut coral
#

Not sure if this is quick but seems basic, but how would I make it so my bot still listens to interactions from buttons on a message after a restart?

errant craneBOT
#

Here's the persistent example.

uncut coral
#

Thanks, fixed

fervent cradle
#

doing: ```py
avatar = member.avatar
webhook.send(str(message), username=name, avatar_url=avatar)

#

is there not a way to get the default avatar they have on?

silver moat
#

you can try using display_avatar, but that will just be a blank image.

silver moat
fervent cradle
#

why doesn't the webhook await just move on without an avatar if a None is provided???

#

this results in my code completely breaking if someone doesn't have an avatar

#

because that one await errors out, and it doesn't execute the rest of the code in the sequence

silver moat
#

you can just handle that error yourself...

fervent cradle
young bone
silver moat
young bone
#

still .url

fervent cradle
#

every time I've tried to use the url in place of just the avatar directly it breaks

#

the way I'm doing it works for everyone besides default avatars

fervent cradle
#

useful help 👍

silver moat
fervent cradle
#

or the library could just not be turbo useless and grab the default avatar image when someone with a default avatar is present

#

like discordjs does

silver moat
#

also, feel free to make a pull request on that.

fervent cradle
#

yeah I'm gonna program in python more than I have to 🤢

silver moat
#

no one is forcing you.

young bone
#

^

fervent cradle
#

display_avatar is what I needed

#

but still doesn't explain why the library simply let a None slip through when requesting the avatar directly

#

this is one of the most annoying bugs to encounter while programming

#

I for one don't do testing on accounts with default avatars

#

because I expect the library to simply function

silver moat
#

Well, Discord doesn't actually give information about that.

fervent cradle
#

This is not a discord problem this is a pycord problem

#

discordjs .avatar works perfectly every time regardless of default

silver moat
#

it will remain a pycord problem, unless someone makes a pr

fervent cradle
#

Yeah I'll spend time fixing the bug, then submit a PR just for some maintainer to come in and be like "hub bub hub we actually intended for this bug to exist"

#

you go spend time doing that

#

I'll spend my time doing not that.

silver moat
fervent cradle
#

I mean the bug doesnt matter for me I was literally doing it wrong, display avatar correctly grabs guild avatar aswell

#

But someones code might need to grab the non guild avatar at some point

#

I had some terrible check for guild_avatar == None

uncut coral
#

I can't get bot.get_guild to work, it always returns None, despite the same guild ID working in command creation

limber urchin
solemn palm
#

Hello, is there a simple way to reply to a user's slash command within the channel that only they can see?

fervent cradle
#

works perfectly in other instances

limber urchin
uncut coral
fervent cradle
limber urchin
#

and the code on the left is completely different from the right

uncut coral
#

I understood that, but I don't know what else I would use instead of guild, I couldn't find a category object, I assume this means I can't use this function for categories but I figured I could ask

limber urchin
#

That's not how you fetch categories, they are channels

uncut coral
#

oh...

#

well thank you xD

copper knot
#

question:
for a persistent view, can you have the button sent to multiple places and still work?

full basin
#

Yes

#

You can also:

#

.tag tias

winter condorBOT
north gorge
#

What's the right way to separate subcommands of a slashcommandgroup across multiple cogs? I'm guessing it's not whatever = SlashCommandGroup("thing") in every cog

quasi stratus
#

Hello, i'm trying to get a user as parameter in a slash command. Before the migration it was fine with
async def test(ctx, user : discord.User):

But now when i'm doing this with the input_type option as discord.SlashCommandType.user and by entering @aaaa#0000 i get the string representation of the user but not a user anymore.

Is there a way to get a user object instead of a string ?

#
    @commands.slash_command(
        description="Get the avatar of someone",
        options=[discord.Option(
            input_type=discord.SlashCommandOptionType.user,
            name="user",
            description="Mention of the user you want to get the avatar",
            default=None
        )]
    )
    async def avatar(self, ctx : ApplicationContext, user : discord.User):```
errant craneBOT
#

Here's the slash options example.

woeful spindle
#

@quasi stratus

quasi stratus
#

I'll check it

quasi stratus
young bone
quasi stratus
proud mason
#

But @spiral spruce had made a module for it. I forgot the name

#

Ask him

spiral spruce
#

hi there

north gorge
#

Hey 🙂

spiral spruce
#

it's called pycord-multicog

north gorge
#

thanks both of ya, will look it up. I love having everything separated out

spiral spruce
#

you should find an example here ^

north gorge
#

makes sense, I'm gonna try it out

north gorge
#

@spiral spruce Is it kosher to add the group from the bot.py so I don't have to just pick a cog to add it to initially?

spiral spruce
#

I think it would work

north gorge
#

Nice, I'll let you know

spiral spruce
#

just use add_to_group

wild cobalt
#

where can I leave what I guess is a bug fix request for 2.3.2?

wild cobalt
#

in forums, applied_tags doesn't update when tags are changed

#

there's a help post about it #1049550251012403271

north gorge
#

Awesome, I'm all set. Had to put the bot.create_group right after loading cogs in __main__, then the apply_multicog(bot) right before bot.sync_commands() in on_connect

#

I suspect more dummies like me will run into this, so for CTRL + F posterity, if it won't load you probably accidentally installed pycord the random python module having to do with image processing

proud mason
quasi stratus
proud mason
quasi stratus
proud mason
full basin
#

Or typehinting it

proud mason
#

decorator is preferred over typehinting

quasi stratus
#

Okay i'll try later

rare garnet
#

why isnt there a fetch_message like there are other fetch methods?

proud mason
#

.rtfm fetch_message

proud mason
#

It's on channel

rare garnet
#

ohhh

#

makes sense

#

tysm!!!

proud mason
#

Yea lol

#

No worries

sleek haven
quasi stratus
sleek haven
#
    async def interaction_check(self, interaction) -> bool:
        if interaction.user != self.ctx.author:
            await interaction.response.send_message("Hey! You cant use that!", ephemeral=True)   
            print("cant")
            return False 
        else:
            print("u can")
            return True``` i have this now in a class but there is a error
full basin
#

You never defined a self.ctx

sleek haven
#

how

#

nvm

quasi stratus
#

Is it possible to override the int maximum length in a slash command ?
i want to pass an id to a command but it doesn't work because the value is too big.
I could use a string parameter and then convert it but i prefer trying to get a straight int

quasi stratus
#

Welp, let's use a string 🥲

north gorge
# spiral spruce just use add_to_group

Is there any issue with having the cogs in a separate file like bot.py/cogs/game.py? I get the group created via bot.create_group but the sub-commands with the decorator do not register to it. I'm using the pycord.multicog.Bot method and the decorator.

spiral spruce
knotty void
#

How can I get the message properties of the respond message of my bot
so when i await ctx.respond(my message) that i can edit it further in the future

silver moat
fervent cradle
#

Why accent_color always return None

lost lodge
#

Hello, why does my code not work?

        @commands.Cog.listener()
        async def on_command_error(self, ctx, error):
            if isinstance(error, commands.MissingRequiredArgument):
                embed = discord.Embed(title="Missing required argument!",
                                      description="Please pass all required arguments!",
                                      colour=0x2f3136)
                embed = add_footer(embed)
                await ctx.send(embed=embed)```
proud mason
#

.idw

winter condorBOT
#

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

lost lodge
#

wait

lost lodge
#

better?

rare ice
#

You also may need to use error.original

lost lodge
rare ice
lost lodge
lost lodge
rare ice
#

Are you using slash commands or prefixed commands?

lost lodge
rare ice
#

Slash commands are a different error handler

lost lodge
#

ah

rare ice
#

A slash command’s error handler is on_application_command_error

lost lodge
#

but it doesn't work and i used the prefixed one's

rare ice
lost lodge
# rare ice print the error, and send it to me
Ignoring exception in command log:
Traceback (most recent call last):
  File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 942, in invoke
    await self.prepare(ctx)
  File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 872, in prepare
    await self._parse_arguments(ctx)
  File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 774, in _parse_arguments
    transformed = await self.transform(ctx, param)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 601, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.```
rare ice
#

do you even have the cog loaded where the handler is?

#

send me your whole cog

#

where the error handler is

lost lodge
lost lodge
rare ice
#

try this
if isinstance(error.original, commands.MissingRequiredArgument):

silver moat
#

why 17 ifs and no elif?

rare ice
#

^

#

that too

lost lodge
lost lodge
#

I will tell you if it works after that

north gorge
spiral spruce
#

That's interesting but I'll need the whole traceback

marble obsidian
#

How can i make a dropdown selector as an argument in a slash command

errant craneBOT
#

Here's the slash options example.

silver moat
#

@marble obsidian ^

marble obsidian
lethal valve
#

Hey so ctx.author gets the author name but i also want their discrim so it comes out like this: AUTHOR#XXXX
how do I do this?

lethal valve
#

Alright thanks

#

Update: so I'm trying to send the results of str(ctx.author) to a telegram bot to post the results but it only posts the username & not the discrim

#

What's the reason behind this

silver moat
lethal valve
#

No luck bruh

proud mason
#

show how you are doing it

#

could telegram be hiding stuff after # ?

lethal valve
#

Idk im gonna do some testing with another method of getting the name#id

proud mason
#

also dont use requests, use aiohttp.

lethal valve
#

and see if it's hiding it]

proud mason
proud mason
winter condorBOT
#

Tag not found.

proud mason
#

bruh

#

?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/>

proud mason
lethal valve
#

Yea telegram is just

#

Hiding everything atfer #

proud mason
#

if there something like this in telegram?

lethal valve
#

Dont think so let me see

proud mason
#

alr

lethal valve
#

dont think so

frank shale
#

Heyall,

The image in this embed is not showing up. Am I doing something wrong here?

silver moat
#

like

test_embed = Embed(title='hi')
test_embed.set_image(url='https://static.upland.me/avatars/exclusive/DbCooper.svg')
#

atm test_embed is a TypeVar

#

because that is what set_image returns

frank shale
#

Chaining methods is encouraged in the docs

silver moat
#

Embed isn't a method

#

it's a constructor

frank shale
silver moat
frank shale
#

Nvm found the issue

#

Discord doesnt support .svg files

silver moat
#

it kinda does

frank shale
frank shale
silver moat
#

svg test

frank shale
#

For me it is ^^ anyway thanks

silver moat
#

see svgs work, but not exactly in the way you want to.

frank shale
#

Uhm so it should work..

frank shale
silver moat
#

share current code?

frank shale
# silver moat share current code?

Its its:

    async def on_ready(self):
        img_png = 'https://static.upland.me/legits/nflpa/seasons/3/19/10412/essential/20/thumbnailImage.png'
        img_svg = 'https://static.upland.me/avatars/exclusive/DbCooper.svg'
        test_embed = Embed(title='hi')
        test_embed.set_image(url=img_svg)

        ctx = await self.fetch_user(self.OWNER_ID)
        await ctx.send(embed=test_embed)

The png does show up but the svg doesnt

silver moat
#

for discord

#

I don't think it looks like an image

frank shale
#

ohh, so I can't just dump the url

#

Like i do for a png

silver moat
#

I don't think svgs are possible

#

maybe if you convert them to bytes?

frank shale
#

And what to do with the bytes?

#

Maybe convert to png and then upload it to somewhere..

proud mason
#

and then use a local file url on the embed

#

?tag localfile

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)```
frank shale
#

Lol, that's going to be some extra hours of work ^^

undone falcon
#

Can you do a slash commands that only appear in specific servers ?

proud mason
proud mason
proud mason
frank shale
proud mason
#

also you should use BytesIO instead of actual files for temp files. it is more efficient

frank shale
honest spoke
wintry cosmos
#

I just red that you can send messages to any user with a bot. The only way to dont get the messages is to block it. But when i try to send a message to a specific user (which obviously disabled DM's from not-friends) it fails. Do you guys know any more?

honest spoke
wintry cosmos
#

Just send a custom message, with a slash command, to a user, like an answer of their feedback. But through the bot.

#

like /sendmsg user: text:

#

Works fine, but not for disabled dms

honest spoke
#

Yea if the bot can not dm the user because dms are disabled you cant do anything against it.

A has the same priviliges as a normal user.

full basin
#

If the user disabled their dms, you can't dm it

honest spoke
#

In this reagard

wintry cosmos
#

Oh okay, because i just red something in the ticketbot discord that the only way to stop getting dms from it would be to block it. But the case that someone just disabled the dms wasnt covered in their FAQ 😄

#

Thanks guys

wintry cosmos
honest spoke
#

If the dm channel is already opened you can send messages i think.
Not 100% sure tho.

wintry cosmos
#

For me its okay, i just thought there was a way around it but its not fairly neccessary

wintry cosmos
#

Any chance in getting an indent in here: ?

wintry cosmos
#

Or is there not really a decent way of formatting these kind of content ^^

#

daaayum

alpine kernel
#

noticing that there's no cog_load() functionality, is there a better place to put async initialization stuff?

proud mason
#

Sane way would be create an async func, decorate it as a task loop with count=1 and start it inside the init

alpine kernel
#

yeah I guess so

#

stuff like that always makes me feel like I'm doing something wrong but it'll work

proud mason
#

.itworks

winter condorBOT
proud mason
#

Lol

alpine kernel
proud mason
#

Just in case you want to know the fucked up way

#
import asyncio

class AsyncInit:
    async def __new__(cls, *args, **kwds):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwds)
        return obj

    async def __init__(self, a, b):
        print(a+b)


async def main():
    d = await AsyncInit(1, 2)

asyncio.run(main())
rough roseBOT
#
Evaluation Result

3

Return Code

0

proud mason
silver moat
#

or your teacher tells you to

rare ice
flat merlin
#

My modal dialogs are showing this, but the bot doesn't return an error. 🤔

#

When submitting.

proud mason
flat merlin
#

🤔

#

Not directly after the modal, but last time I tried it returned an error that the interaction had already been responded to. 🤔

wind jay
#

but i cant user followup.edit_message

flat merlin
#

I got that part to work now.

#

Thanks.

#

The next problem is using variables to store the modal's input.

#

Global variables were the only thing I found to work, but when two users use the function simultaneously, it puts both users in the same variable.

wind jay
#

how to send a modal after doing interaction.response.defer()

flat merlin
#

Sending a modal is a response to an interaction, so if you're going to send a modal through that interaction, you don't need to defer it.

#

So you could simply use interaction.response.send_modal(), I think. 🤔

wind jay
#

okay thanks

viral hazel
#

can anyone tell me why i can't import discord even if i installed it in different ways many times

limber urchin
#

?tag install

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

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

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

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

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

viral hazel
#

?tag git

obtuse juncoBOT
#

dynoError No tag git found.

ornate swan
#

how do i make a response, if my select menu takes longer than 3sec?
defer doesnt seem to work, atleast i didnt figure out how

proud mason
somber frost
#

CODE:

async def on_message(message: discord.Message):
    auctions = bot.get_channel(1060824338057666580)
    if message.channel.category == auctions:
        if message.content.isdigit():
            await message.reply("okay")
        else:
            await message.delete()```
**ERROR:**
```Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
    if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
    if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
    if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
    if message.channel.category == auctions:```
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
    if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
    if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'```
young bone
#

read the error

somber frost
#

i read it

#

but i dont understand it

#

does on_message also react on DMs?

young bone
#

ye

somber frost
#

and even if it does, i wrote into the server

#

not into the bot DM

#

can i make a check if the server was sent into the server/guild?

#

if message.guild or something

#

message.channel.guild maybe?

#

message.guild works, problem probably solved :))

#
async def on_message(message: discord.Message):
    auctions = bot.get_channel(1060824338057666580)
    marketplace = bot.get_guild(1054406907110113421)
    if message.author != bot.user.id:
        if message.guild == marketplace:
            if message.channel.category == auctions:
                if message.content.isdigit():
                    await message.reply("okay")
                else:
                    await message.delete()
#

why do the messages of my bot get deleted now?

limber urchin
#

Because message.author is not an id

#

its a member object

somber frost
#

ohhh okay

limber urchin
#

try it and see

#

and read the docs

somber frost
#

This is my JSON right now

    "auctions": [
        {
            "Akame": 250
        }
    ]
}```
#

And this is my python code

with open("auctions.json", "r") as f:
    data = json.load(f)
if int(message.content) > data['auctions'][f'{message.channel.name}']:
#

my question is, how can i access the number in the JSON (the 250)

sleek haven
#
    async def on_timeout(self):
        print("test")
        self.clear_items()``` is clearing all items right how do i do it only disables the button
somber frost
#

also, i want to access it by the name

#

("Akame")

limber urchin
#

?tag nojson

obtuse juncoBOT
#

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

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

Popular database management systems:

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

i know that

#

but i dont want to learn how to use databases in python + SQL just to store 1 string and 1 number

#

at some point i definetly will learn a database system

limber urchin
#

If you don't want to learn, you're not gonna go very far

somber frost
#

learn such a big thing just for storing 2 things

#

thats not worth it. i can just do it in json if its such a small thing

limber urchin
#

That's a pretty bad excuse for using a bad practice, but ok

somber frost
#

i understand what you mean and i will learn a db system, probably sqlite

#

but i built my whole bot on json rn and its really just a small piece of data that i wanna store

limber urchin
#

Your question is also very basic python

somber frost
#

so i think i would like to complete it with json for now

somber frost
#

indexing in json files

limber urchin
somber frost
#

but i dont understand why my code doesnt work + i dont know if i index "Akame" if if then takes the value of Akame

#

so it takes 250

#

or if it takes the string "Akame"

proud mason
#

so you cant do data['auctions']['Akame']

bold notch
#

Is it possible to update a Image or Thumbnail in an Embed a few seconds after it was sent?

limber urchin
#

Edit the message with an embed containing the same content but a new image or thumbnail

flat merlin
flat merlin
#

And access variables passed to the functions if I separate it. 🤔

frank shale
# proud mason also you should use BytesIO instead of actual files for temp files. it is more e...

Hey Om, I've it finished for the most part.

How to add a BytesIO file like object for a picture to an embed?

It works when you use a .png file from the disk, as is done in the commented line: # f = discord.File('C:\\Users\\path_to_file\\output.png', filename='output.png').
However, using a BytesIO file like object is giving me some trouble. Giving the png_file.name = 'output.png' is not sufficient enough to load the image into discord. Am I missing something here?

async def on_ready(self):
    import io
    from svglib.svglib import svg2rlg
    from reportlab.graphics import renderPM
    svg_str = "" 
    svg_bytes = io.StringIO(svg_str)
    png_file = io.BytesIO()
    renderPM.drawToFile(svg2rlg(svg_bytes), png_file, fmt='PNG')
    png_file.name = 'output.png'
    # f = discord.File('C:\\Users\\path_to_file\\output.png', filename='output.png')
    f = discord.File(png_file, filename='output.png')
    e = discord.Embed(title='hi')
    e.set_image(url="attachment://output.png")
    ctx = await self.fetch_user(self.OWNER_ID)
    await ctx.send(file=f, embed=e)
west venture
#

im getting an error which dont makes sense||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||https://ask-your-mom.big-pp.club/🥬🍢🥏🧜

I wasted more than 6.98 KB for you to see this

06/01/2023 at 18:41

frank shale
#

What is the use of using the current cursor location in the discord.File? Has it a special usecase? Like, normally you would want to read the whole file from 0

# file.py ln92
        if isinstance(fp, io.IOBase):
            if not (fp.seekable() and fp.readable()):
                raise ValueError(f"File buffer {fp!r} must be seekable and readable")
            self.fp = fp
            self._original_pos = fp.tell()
            self._owner = False
limber urchin
west venture
#

;P

limber urchin
clever thistle
#

How can I get Members (instead of Users) when querying reactions inside message_command? Do I need some permission (Intent)?

flat merlin
#

Is ctx.author not a member object by default, if the command is used in a server?

#

A DM channel does not have member objects.

#

Otherwise you can get members by the ID, but I don't know if that's the most efficient way.

gleaming falcon
flat merlin
#

You may need intents to get members.

gleaming falcon
#

Review your code, compare it to other examples. You didn’t post any relevant info, so hard to get any more specific than that

west venture
#

@bot.slash_command(name="bot")
async def bot(ctx):
    em = discord.Embed(title="Discord Bot Development", description=":bot_discord18: Need a **custom bot** to enhance your server? we can create a **bot tailored** to your specific needs.\n\n  :slayer_SantaGiftBox:1060910216876666970>**WE OFFER**\n\n> :tickets: One-time purchase\n> you'll receive lifetime **free servicing** + **free maintenance**, and **24/7 online** support\n> :discorddv:  No **hidden fees or ongoing** costs - just **top-quality** service at an affordable price.\n\n**_STARTING PRICE_**: ||$7||\n\n **__Accepted payment methods:__**\n:Paypal40: :Crypto: :slayer_SantaGiftBox:\nSimply open a `ticket` in the ticket channel to get started. We'll work with you to design and implement the perfect bot for your server.", color=discord.Color.orange())
    em.set_footer(text="• Xlereaon Services")
    button = Button(label="Create Ticket here", url="https://discord.com/channels/1050739616216518726/1055758151040905227", emoji="https://discord.com/channels/1050739616216518726/1055758151040905227")
    view = View()
    view.add_item(button)
    ctx.channel.send(embed=em, view=view)

bot.run(c.TOKEN)
gleaming falcon
#

Well first off, you should rename your def bot. You can have the command name bot, as you’ve already defined it. But remove the ambiguation

west venture
wintry cosmos
#

Is it possible to see the dms a bot get? Or do I have it to do like send the content a user send to the bot in a specific channel or also DM to a specific user?

#


In my case I have a auto reply for users dming the bot like: noreply@bot - can’t read it. Which is probably not correct bc I could store/display them somewhere else?

west venture
full basin
#

You must await it

woeful spindle
#

u can access the content with message.content

knotty surge
#

I am getting this error file parameter must be File

I am sending a ZIp FIle

woeful spindle
#

iirc it takes a discord.File

#

.rtfm discord.File

knotty surge
#

Ah I forgot, made each file inside a discord file but not the zip thanks

#

Getting this now discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not ZipFile

clever thistle
proud pagoda
#

Can embed thumbnails be gifs?

full basin
#

irrc they can

young bone
proud pagoda
#

Ok thanks

knotty surge
#

Hey does anyone know why Discord.File is removing ^ from my file name?

silver moat
knotty surge
knotty surge
# silver moat show your code?
              temp = "_" + faction.lower() + "_" + str(change_name).replace(" ", "") + "_" + item

                os.makedirs(os.path.join(temp))

                # Moves into Folder
                shutil.move(filename_start + ".png", os.path.join(temp))
                shutil.move(filename_start + ".png" + ".json", os.path.join(temp))
            # Rename ytd Path
                file_directory_prep = str(r"mp_{gender}_freemode_01-{type}_diff_{value}_{letter}_uni")

                os.rename(temp + ".ytd", file_directory_prep.format(gender="m", type=item_base['type'], value=item_base['value'], letter="[A-Z]" + ".ytd"))

                # Move Folder and ytd
                shutil.move(temp, os.path.join("sent/", temp))

                shutil.move(file_directory_prep.format(gender="m", type=item_base['type'], value=item_base['value'], letter="[A-Z]" + ".ytd"),
                                                       os.path.join("sent/",
                                                                    file_directory_prep.format(gender="m", type=item_base['type'], value=item_base['value'], letter="[A-Z]" + ".ytd")))
#

Or if possible I am wanting to just send a zip file but getting this error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not ZipFile

boreal dust
#

.rtfm on_voice_channel

winter condorBOT
#

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

boreal dust
#

hm

#

.rtfm voice_channel

boreal dust
#

.rtfm join

boreal dust
#

.rtfm on_

limber urchin
boreal dust
limber urchin
boreal dust
#

any ides?

boreal dust
limber urchin
#

.rtfm on_voice_state_update

boreal dust
#

oh thanks

limber urchin
#

There

#

now stop clogging the channel with commands

boreal dust
#

yeah yeah

alpine kernel
#

any ideas on if it's possible to allow a user to chat in a channel, but not allow them to see any chat history, previous or ongoing?

#

doesnt look possible looking at permissions but just wanted to check

boreal dust
limber urchin
#

That will still show any messages sent while looking at the channel

boreal dust
#

Then it's not possible.

alpine kernel
#

yeah, looks more possible just to use dms for what I want

unreal shoal
#

.rtfm button()

winter condorBOT
#

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

young bone
unreal shoal
#

@discord.ui.button(label="verify", style=discord.ButtonStyle.link, url="https://youtube.com")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: button() got an unexpected keyword argument 'url'

uh i dont understand why i am getting a error

unreal shoal
# young bone Can you show the pip list?

aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
certifi==2022.12.7
charset-normalizer==2.1.1
discord==2.1.0
discord.py==2.1.0
ffmpeg-python==0.2.0
frozenlist==1.3.3
future==0.18.2
idna==3.4
imageio-ffmpeg==0.4.7
multidict==6.0.4
numpy==1.24.1
peppercorn==0.6
py-cord==2.3.2
requests==2.28.1
sampleproject==3.0.0
urllib3==1.26.13
yarl==1.8.2

young bone
#

uninstall ```py
discord==2.1.0
discord.py==2.1.0
py-cord==2.3.2

and reinstall py-cord
unreal shoal
#

okok

unreal shoal
#

and my new pip list is this:

aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
certifi==2022.12.7
charset-normalizer==2.1.1
ffmpeg-python==0.2.0
frozenlist==1.3.3
future==0.18.2
idna==3.4
imageio-ffmpeg==0.4.7
multidict==6.0.4
numpy==1.24.1
peppercorn==0.6
py-cord==2.3.2
requests==2.28.1
sampleproject==3.0.0
urllib3==1.26.13
yarl==1.8.2

young bone
#

did you restart the IDE?

unreal shoal
proud mason
errant craneBOT
#

Here's the link example.

unreal shoal
frank shale
#

Unfortunately, the cairosvg didnt work for me, but svglib does do the job somewhat

#

Thnx for the tipx

dense tide
#

I'm not sure if this is the right channel for this but I have a question. I would like to edit a message that has been sent by it, but I don't know how I should do that because the only references I found were using ctx(Applicationcontext).send(), but I have to use ctx.respond() otherwise you get a exception that the Bot didn't respond even though it sent a message. (Bearbeitet)

young bone
silver moat
#

await ctx.interaction.original_response() would return the message you responded with

dense tide
#

thanks all of you

dry echo
#

why is my bot.users empty when the bot is on a server with some users?

silver moat
dry echo
boreal abyss
#
@bot.event
async def on_message(message):
    # Check if the auto-check feature is enabled for this server
    cursor.execute('''
        SELECT enabled FROM auto_check WHERE server_id=?
    ''', (str(message.guild.id),))
    result = cursor.fetchone()

    # Use the SentimentIntensityAnalyzer to analyze the sentiment of the message
    sid = SentimentIntensityAnalyzer()
    sentiment = sid.polarity_scores(message.content)
    toxicity = sentiment['compound']
    drama = sentiment['neg']
    if message.author.id == "1057048030920061048":
            return
    if result and result[0] == 1:
        # Check if the toxicity or drama score is above a certain threshold
        if toxicity < -0.4 or drama > 0.4:
            await message.channel.send("Detected a potentially toxic or dramatic message. This is your warning. Please stop! Thanks!")
        else:
            await message.channel.send(f"Neutral {message.content}")

No errors, the bot just reads its messages onlyWHY?
Intents are given in code.
Intents are given in dhasboard

silver moat
silver moat
boreal abyss
#

intents = discord.Intents(messages=True, guilds=True)
bot = commands.Bot(commands_prefix="!", intents=intents)

silver moat
boreal abyss
#

so i do
intents = discord.Intents(messages=True, guilds=True, message_content=True)

dry echo
silver moat
silver moat
#

right, but for the bot, the guild doesn't have any members

#

because you don't have members intent

young bone
silver moat
young bone
#

k

#

I just use all(), I know its not the best but I dont know which one I need

woeful spindle
#

same doggokek

unreal shoal
#

how to delete interaction response python

#

msg = await interaction.response.send_message(view=verify())

silver moat
dry echo
#

is there an easy way to get the same guilds the bot and a specific user is in?

silver moat
#

.rtfm mutual_guild

winter condorBOT
silver moat
#

@dry echo ^

dry echo
dry echo
#

is it possible to get the color? because user.color gives me 0 and accent_colour None

full basin
#

That's the banner

#

Not the color

dry echo
#

i have no banner?

full basin
#

No

#

You can't get a default banner

dry echo
#

i just mean I have no banner because i dont have nitro...because of that this color shows up. but how can i fetch it?

silver moat
bold notch
#

How do you delete an attachment file in an embed?

await ctx.respond(file=file, embed=embed)

I want to keep the embed but delete the file

woeful spindle
full basin
#

Just pass file=None

woeful spindle
#

the embed stays?