#Basic Pycord Help

1 messages ¡ Page 22 of 1

shell radish
#

?tag gif_avatar

limber wagonBOT
#

How to upload an animated avatar for your bot

To use and upload an animated avatar you can run the following snippet as standalone script:

import discord
import asyncio

# Intents to enable certain events
intents = discord.Intents.all()

# Create a Discord client instance with intents
client = discord.Client(intents=intents)

# Event to handle bot's initialization
@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

    # Upload animated avatar
    try:
        with open('yourpicture.gif', 'rb') as avatar:
            await client.user.edit(avatar=avatar.read())
        print('Animated avatar uploaded successfully!')
    except Exception as e:
        print('Failed to upload animated avatar:', e)

# Run the bot
client.run("YOUR_TOKEN")

That should be all, have fun!

torpid cosmos
#

Why is asyncio imported?

hallow copper
shell radish
frail ocean
#

Is there a way to check if a member is timeouted?

frail ocean
#

What is the max time to timeout a member?

little cobalt
#

1 month? But Im not sure about it

torpid cosmos
frail basin
frail ocean
#

Ok

lapis dock
#

Dev portal did not support it for at least a little bit

grizzled loom
#

What's the max. amount of characters one can hand over to ctx.respond?

shell radish
grizzled loom
#

That's awsome! Less adjustments needed in my project 🙃
Thank you Great Squid

grizzled loom
sage tendon
#

weird

#

i think you get 2000 for an embed as well tho

lapis dock
#

It's just my opinion but user experience wise I don't want 4000 characters, especially if I am on mobile.

terse arrow
#

There any way to check a user for a certain tag such as Moderator to allow them to use certain commands? E.g.

Moderator tries to use a / command which allows them to use it
Random Discord Member tries to use / command (I want to either not show up to them or check their roles to see if they are a Moderator then send an await back to them with a message)

lapis dock
#

You should join d.py server if you use d.py

smoky ivy
#

I will

#

Thank you

lapis dock
terse arrow
lapis dock
#

In server setting an admin can allow and disallow roles and users to use commands. Q

terse arrow
lapis dock
#

You can use Member.roles

#

.rtfm Member.Roles

sly karmaBOT
lapis dock
terse arrow
#

Ta

terse arrow
#

I've got a new issue with a pinging a role

        admin_role_id = 1212135665811193906  # Replace with the ID of your admin role
        admin_role = interaction.guild.get_role(admin_role_id)
        if admin_role:
            try:
                await interaction.followup.send(f"<@&{admin_role.id}>, please check this ticket!")
            except discord.errors.HTTPException:
                await interaction.followup.send(
                    "Failed to ping the admin role. Make sure the bot has the necessary permissions.")
        else:
            await interaction.followup.send("Admin role not found!")
#

For some reason, its not pinging my admin_role, any assistance would be grand

frail ocean
#
    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        print('1')```

Shouldnt it print 1 if i update my presence to spotify
lofty parcel
#

.rtfm allowedMentions

lofty parcel
frail ocean
lofty parcel
frail ocean
#

I have all intents on

#

intents=discord.Intents.all()

lofty parcel
#

Youre using on_member_update

#

That event doesnt trigger presences or status changes

#

on_presence_update does

#

Read. The. Docs.

frail ocean
#

Okay. Chatgpt wrote me this

#

Sorry

sage tendon
#

zamn

onyx sentinel
#

guys i forgot the library i have to install in order to make discord.commands work, when i run the code i get this error:

Traceback (most recent call last):
  File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\main.py", line 3, in <module>
    from discord.commands import Option, OptionChoice
ModuleNotFoundError: No module named 'discord.commands'
lapis dock
#

its discord.ext.commands

onyx sentinel
#

ahh ty

hallow copper
#

it’s honestly impressive

rancid arrow
#

Prompt engineer DaniGlasses

onyx sentinel
#

guys what is wrong with my code

import discord
from discord.ext import commands
from discord.ext.commands import Bot, Context
from discord.ui import View
from discord.ui.button import Button
from discord.ui.select import Select
from discord.ui.modal import Modal

intents = discord.Intents.default()
intents.members = True

class PersistentViewBot(commands.Bot):
    def __init__(self):
        super().__init__()
        self.persistent_views_added = False

    async def on_ready(self):
        await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"Pycord 2.4.1"))
        print(f"Logged in as {self.user} (ID: {self.user.id})")
        print("------")

bot = PersistentViewBot()

# ------------------------------------------------------

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

    await ctx.respond("Hello world")


# ------------------------------------------------------

bot.run("")

it gives me this error

Traceback (most recent call last):
  File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\main.py", line 23, in <module>
    bot = PersistentViewBot()
          ^^^^^^^^^^^^^^^^^^^
  File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\main.py", line 15, in __init__
    super().__init__()
TypeError: BotBase.__init__() missing 1 required positional argument: 'command_prefix'
#

i dont want to have a prefix

#

i want my bot to be 100% operated by slash commands

edgy nest
#

then use discord.Bot

shell radish
#

use discord.Bot instead of commands.Bot

onyx sentinel
#

oh ok

shell radish
#

?tag client

limber wagonBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
onyx sentinel
#

now it says discord has no attribute Bot 😭

shell radish
#

python version?

onyx sentinel
#

3.12.1

shell radish
onyx sentinel
#

pycord

hallow copper
#

are you sure?

shell radish
#

pip list (or equivalent on your machine) and show output

onyx sentinel
#

ye

#

i think im having a conflict by both of them be installed

#

oh

shell radish
#

that would be an issue

onyx sentinel
#

i uninstalled discord.py then the terminal is saying that there is no module named discord

shell radish
#

re-install py-cord

#

by uninstalling and installing

onyx sentinel
#

ok

#

my code is yellow

#

wth

#

still getting the same error

shell radish
#

restart vsc

onyx sentinel
#

nothing changed

shell radish
#

is the correct version of python selected?

onyx sentinel
#

ye

shell radish
#

can you do pip list (or equivalent on your machine) and show output

onyx sentinel
#

0.1.1 💀

shell radish
#

py-cord not pycord

onyx sentinel
#

i cant download a specific version for some reason

onyx sentinel
#

when i download py-cord it gives me this error

shell radish
#

?tag install

limber wagonBOT
#

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

shell radish
#

use the master branch

onyx sentinel
#

k

#

?tag git

limber wagonBOT
onyx sentinel
#

hold on

#

not working bro

shell radish
#

what isn't working

onyx sentinel
#

at 2a

shell radish
#

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

#

that was the only thing I wanted you to do

onyx sentinel
#

ah

#

aint working

lapis dock
#

Do this master is broken atm
pip install -U git+https://github.com/Pycord-Development/pycord@fc7b1042c4a9a942b9996dfe96f56aac059e179c

onyx sentinel
#
  ERROR: Error [WinError 2] O sistema nĂŁo pode encontrar o arquivo especificado while executing command git version
ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH?
shell radish
onyx sentinel
#

i just put it on path tho

lofty parcel
onyx sentinel
#

back then it worked just fine

#

does it have something to do with the fact i got a new pc?

lapis dock
#

yeah, only master works with python3.12 right now and the current master is broken unless you go back a few commits, which requires git

onyx sentinel
#

ahhhh

onyx sentinel
#

windows 11 tho

#

im noticing its bad already

edgy nest
#

tf is broken on master

lapis dock
onyx sentinel
#

im downgrading rn

edgy nest
#

just dont use __future__ annotations

#

and you won't have a problem

lofty parcel
#

He do be a problem solver

shell radish
edgy nest
#

well it aint broken if you don't use them

#

just sayin

lapis dock
edgy nest
floral ice
#

for some reason ephemeral does nothing, idk why

#

another thing, .defer(invisible=True) also doesnt work for me

little cobalt
limber wagonBOT
#

dynoError No tag ephermeral found.

little cobalt
#

?tag ephemeral

limber wagonBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

e.g.

await ctx.respond("Imagine a message!", ephemeral = True)

await interaction.response.send_message("Imagine a message!", ephemeral = True)
grizzled loom
#

Guys, I can't make up my mind. I have 3 versions for a simple check. All 3 do the same and work. Which one would you pick and why?

        if isinstance(ctx.channel, discord.channel.DMChannel):
            return await ctx.respond(f"{await get_dm_text()}")
        if not ctx.guild:
            return await ctx.respond(f"{await get_dm_text()}")
        if ctx.guild is None:
            return await ctx.respond(f"{await get_dm_text()}")
frail ocean
vital bramble
frail basin
lapis dock
little cobalt
#

Or if its at the ctx you also have to add it to both

#

@floral ice ^^

floral ice
#

i fixed it ty

vital bramble
#

pycord does not currently support setting the status of a voice channel does it?

vital bramble
#

What is the purpose of a stage instance? Can't I just use the channel?

vital bramble
#

thx, do you know how I can make the bot able to speak in a stage channel?

sage tendon
#

do stage channels even have an attached textchat

#

oh, yea

#

well, the 2.4 release doesnt support it

#

but the latest github version does

vital bramble
#

no not write, speak

sage tendon
#

oh

lilac yoke
#

Hi guys,how can i make my command is called once and works everytime,in my code it sends from 'chat.json' just when i type !chat again

sage tendon
#

what are you even trying to do and what is the issue

lilac yoke
#

im trying to send a data to my discord channel from chat.json when i type !chat

sage tendon
#

also i dont get where you are expecting an httpexception other than .send(), and then you are just sending again

lilac yoke
#

.json changes everytime,sometimes its empty

sage tendon
#

then fix the part of your code that edits the json

lilac yoke
#

i fixed it already

little cobalt
#

do you know how to use a json?

lilac yoke
#

i just want to make my command called once and works everytime

sage tendon
#

what does that even mean

#

"works everytime"

lilac yoke
sage tendon
#

yea, well, you are overwriting the json every time like that

lilac yoke
little cobalt
#

message is a string and not a dict or list

sage tendon
lofty parcel
#

That doesn't look like pycord

lilac yoke
#

its not

sage tendon
lofty parcel
# lilac yoke its not

So you're asking in a library you don't use support server for help with other library?

#

Which isn't even related to the library itself

lilac yoke
#

its related

hallow copper
#

damnnnn

sage tendon
#

does your bot use py-cord?

lofty parcel
#

Writing json files isn't related to a library

sage tendon
#

oh, yea

hallow copper
#

what a smart thing to do

sage tendon
#

that too lol

little cobalt
hallow copper
#

prolly just new at life in general

sage tendon
lilac yoke
#

it fixed

#

i just wanted a tip about pycord

#

not about json or something

lofty parcel
#

You're not using py-cord...

hallow copper
#

hey my js bot isn’t working can you help me pls?

lilac yoke
#

pycord

hallow copper
#

nuh uh

hallow copper
little cobalt
#

xd

hallow copper
#

js.js

lofty parcel
little cobalt
#

rs.js

lilac yoke
#

next time try to help

lilac yoke
#

its from another file

#

not from main

hallow copper
#

it could be pycord, they just rly don’t know what they’re doing

sage tendon
#

ah so you use pycord in one file and discord.py in another file

#

gotcha

lofty parcel
#

Lmfao

lilac yoke
#

you are a funny guy aren't you ?

sage tendon
#

i mean

hallow copper
#

yis

sage tendon
#

if you logically process your statements

#

thats what comes from it

hallow copper
#

is lala active?

#

i think this would be a good time for her to show up

sage tendon
#

you say you use pycord
while saying that the non-pycord code comes from another file
so logic predicts that your main.py uses py-cord and your other files, for some reason, use discord.py

lilac yoke
#

i just asked

#

a simple thing

hallow copper
#

i-

lilac yoke
#

about pycord

hallow copper
#

ion even think you understand what you’re doing

sage tendon
#

literally this isnt about understanding my guy

#

if you dont use pycord this is not for you

hallow copper
#

where is mommy-

#

is it safe to ping her?

lofty parcel
lilac yoke
#

I am

#

using

hallow copper
#

then you’re doing it very wrong

sage tendon
#

but why do you have code that isn't pycord

lilac yoke
#

if u look the first one

#

u will see

sage tendon
#

you already said that

#

so how does using discord.py in one file and pycord in another file work?

hallow copper
#

many times

sage tendon
#

hint, it does not

sage tendon
#

dude i dont know, but it aint from pycord is it

lofty parcel
#

It aint

hallow copper
#

maybe that’s the problem

lofty parcel
#

.rtfm Bot.on

hallow copper
#

maybe that’s why it’s not working

lilac yoke
#

this

#

is not

#

from a discord thing

#

the first ss is

hallow copper
#

when why tf did you send it here

sage tendon
lofty parcel
#

You're literally listening to an message event

#

To store chats

lilac yoke
#

yes i am

sage tendon
#

what would refer to with bot if not a discord bot

lofty parcel
#

And that's not how pycord handles events

lilac yoke
#

but not using discord libraries

lofty parcel
#

Oh you created your own library

#

But can't load a json file

#

Ironic

lilac yoke
#

sure

sage tendon
#

whats wrong with channel.history, or a persistent array

hallow copper
#

if you don’t want to explain your code why do you think anyone here would be able to help you?

hallow copper
#

sender

lilac yoke
#

u can understand

hallow copper
#

sended

lilac yoke
#

what i want to know

sage tendon
#

you want to know how to use json

hallow copper
#

nah, i’d rather be mean

lilac yoke
#

this is not a help channel for sure

sage tendon
#

i mean okay realistically, you wanna know how to store data across command / event invocations

learn to use json then

sage tendon
hallow copper
#

if that’s the case, why do you even show up that irrelevant code?

sage tendon
#

do you go to ford workshops to repair your ferrari?

lilac yoke
#

getting data

#

from json

sage tendon
lilac yoke
#

its not about json

hallow copper
#

i-

sage tendon
#

then what is it about?

hallow copper
#

i’m pinging lala

lilac yoke
#

its about how can i make my command work for once

#

and nonstop

lofty parcel
#

I love how he contradicts himself

hallow copper
#

@unkempt cipher

hallow copper
#

help please

sage tendon
#

You have the discord-facing part of your code figured out

Now figure the storage part out

That is neither pycord nor discord related

#

if you want it quick and dirty declare a global list and use that

#

happy?

hallow copper
#

that sounds painful

#

would work tho ig

sage tendon
#

json is painful

hallow copper
#

yeah-

lilac yoke
#

its not helpful for my thing but its an answer

sage tendon
#

list >>> json

lilac yoke
#

thanks

sage tendon
#

how is the literal solution not helpful

#

i literally said its a crude but quick way of doing it
but your entire code looks to be exactly that

lofty parcel
hallow copper
#

now that that’s sorted out, my laptops not working can you guys help?

#

this is a help channel for everything right?

sage tendon
#

yea you have discord.py installed alongside py-cord

#

skill issue, next

hallow copper
#

damn-

sage tendon
hallow copper
#

global list >

lofty parcel
#

?tag botvar

limber wagonBOT
#

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

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

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

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

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

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

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

sage tendon
#

right

#

but global is funny because my IDE says its wrong so i am rebellious by using it

hallow copper
#

i love that XD

sage tendon
#

i mean
thats really a sql question and not pycord specific

#

but really, you dont need to close it

versed root
#

ohh

versed root
versed root
maiden bloom
#

I want to begin sharding but currently use a SQLite database mounted to a docker compose container where the bot runs and I'm assuming I would run into file locking issues if I were to run two instances of the bot connected to the same database. My plan is to migrate to MariaDB that way I can have multiple DB connections without issues.

My question is: how are commands/events handled with auto sharding? If I have two instances of commands.AutoShardedBot running the same code, what happens when a command is executed? Do both instances pick it up or does only one instance pick it up and run with it? Same question with events - if one is triggered and the listener for the event is on both shards running the same code, do they both get triggered or only one?

glad totem
#

hey im trying to download pycord for windows but im getting an error, i found a stack overflow page that matches my error: https://stackoverflow.com/questions/74550830/error-could-not-build-wheels-for-aiohttp-which-is-required-to-install-pyprojec but this is from over a year ago is aiohttp support still in beta and how do i go about changing my aiohttp version as said in the top comment

lofty parcel
glad totem
lofty parcel
#

only the maste version (aka github version) supports 3.12

#

you either downgrade or install the master branch

#

which, afaik, it is broken rn

glossy latch
#

how can i use slash commands in cog file

rugged lodgeBOT
#

Here's the slash cog example.

glossy latch
#

is the interaction still working with slash command?

lofty parcel
#

What?

glossy latch
lofty parcel
#

They receive a discord.ApplicationContext object

glossy latch
#

ah okey thx

vital bramble
#

Anyone who is working on the audio features of pycord, please take a look at this thread: #1212491741018456134

onyx sentinel
#

guys i cant download py-cord for nothing in this world help me

#
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
#

i get this error every time

#

help pls my boss want me to use pycord

shell radish
#

are you using python 3.12?

#

If you are, please use the master branch or wait a few days until we get a release

#

You can install the master branch from

#

?tag install

limber wagonBOT
#

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

shell radish
#

the last paragraph

maiden bloom
lofty parcel
maiden bloom
# lofty parcel Why would you run two instances

I was looking for a way to troubleshoot submitting my bot’s server count to an API without taking down the bot which lead me to learn about sharding. I read in the guide it says eventually if a bot gets large enough it will have to be. My bot is at 1,900 servers so I want to start looking into how I can implement it for when I eventually have to

lofty parcel
#

commands.AutoShardedBot should handle everything related to the sharding

#

I don't have specific experience with sharding, but I'm sure it's just changing that and letting the library handle the stuff

#

Not sure if there's a guide

maiden bloom
dim raptor
#

Does anyone know why the on_timeout isnt working for me

#

the application just doesnt work

shell radish
#

only the discord.ui.View class – not discord.ui.Select – has an on_timeout method.

dim raptor
#

yeah i tried putting it there too

#

still doesnt work

loud kayak
dim raptor
#

oh i think i got the problem

#

the timeout was supposed to be inside the init

loud kayak
deft hull
#

What is the best way to store user config?

#

It's a newbie question but I want my bot to be organised

little cobalt
#

you can use a SQL database or a NOSQL database

#

I use MongoDB which is using some json format

deft hull
#

Ah I see, thanks

frail ocean
#
Task was destroyed but it is pending!

task: <Task pending name='pycord: on_message' coro=<Client._run_event() running at /usr/local/lib/python3.10/site-packages/discord/client.py:378> wait_for=<Future pending cb=[Task.task_wakeup()]>>```
i get this error almost on every restart. What i have to do
edgy nest
#

code wise, an autoshardedbot acts as a single client

maiden bloom
#

Perfect, thanks

#

What if separate shards have different code? For example, if I have an event listener on one of the two shards but not on the second shard, will it know to only trigger the event on the shard that has the listener for it?

subtle moth
#

can you even have different code for different shards

vital bramble
#

Is there a decorator for listeners in a bot subclass?

little cobalt
#

Cog.listener()

vital bramble
vital bramble
little cobalt
#

but why do you want to have it at the bot class and not in a cog?

vital bramble
#

it makes a bit more sense there and its' not really big enough to get it's own cog xD

#

actually...

#

yeah a cog makes sense lol 😆

grizzled loom
steep cliff
#

Is there any error that specifies kwargs in an on_error event? only seen args so far...

fierce fable
#

is there a way to ad clickable links to embeds?

lofty parcel
fierce fable
#

well

#

a link with text

lofty parcel
#

What?

#

Links are clickable in embeds.

#

You just paste the link

subtle moth
#

The bot will also need to have embed links permission

fierce fable
lofty parcel
#

That's an hyperlink

#

Works the same way in an embed

fierce fable
#

sorry should have worded it better

#

but not in the title? thats where im trying to do it

lofty parcel
#

The title has its own attribute for that.

#

url=

fierce fable
#

alr thanks :3

long scroll
#

can I set the image of an embed to a Pillow image?

#

I have tried this

file = discord.File(fp=image_to_byte_array(image), filename="image.png")
embed.set_image(url="attachment://image.png")
await message.edit(embed=embed, file=file)
long scroll
#

ValueError: unknown file extension: from file = discord.File(fp=image_to_byte_array(image), filename="image.png")

onyx sentinel
long scroll
# lofty parcel Does it throw any error?

There was a problem with my image_to_byte_array function now I get this error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

sage tendon
#

wtf is attachment://image.png

long scroll
sage tendon
long scroll
#

I thought maybe it would work for py-cord

#

what do I do? I have a PIL image

lapis dock
#

.tag localfile

sly karmaBOT
#

Tag not found.

Did you mean...
local-file

lapis dock
#

.tag local-file

sly karmaBOT
#
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)```
lapis dock
#

Not sure if that helps, I think you were already doing that

long scroll
#

so I have to save the image then use it?

lapis dock
#

No fp takes bytes too

long scroll
#

but I can't convert a pillow image to bytes I tried byteIO, tobytes and getdata

lofty parcel
lapis dock
#

To me it looks like you are doing things right, I can't help further sorry.

long scroll
#

its ok

#

thank you

frail ocean
#

If a user has more than one activity is there a way to get them all?

long scroll
#

why do I get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message error when I try to use channel.fetch_message? I have checked the channel_id and message_id

long scroll
#

why?

frail ocean
#

message intent activated?

long scroll
#

what is message intent?

frail ocean
limber wagonBOT
#

Pycord Docs - Intents
Discord API Docs - Gateway Intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
long scroll
#

I should put this in my code and enable it in discord developer portal?

long scroll
#

ok

lofty parcel
#

Read the docs.

long scroll
# frail ocean Right

I still get the same error also pycharm tells me 'Intents' object attribute 'members' is read-only

frail ocean
long scroll
#

what part of my code?

lofty parcel
#

The part where you define your intents?...

long scroll
#
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True

intents = discord.Intents.default()

intents.members = True
intents.presences = True
intents.message_content = True

intents = discord.Intents.all()

bot = discord.Bot(intents=intents)

...

async def process_queue():
    await asyncio.sleep(5)

    while True:
        # Get the oldest entry from the database using the Database method
        entry = db.get_oldest_request()

        if entry:

            request_id, channel_id, message_id, user_id, prompt, _ = entry

            file = discord.File("image.png", filename="image.png")

            channel = bot.get_channel(channel_id)
            message = await channel.fetch_message(message_id)
            await message.edit(content=f"**{prompt}**", file=file)
    await asyncio.sleep(5)  # Check queue every 5 seconds


# Start the queue processing task
bot.loop.create_task(process_queue())

bot.run("My Token")
lofty parcel
#

You just need the message content intent

#

And why are you defining your intents three times?...

long scroll
#

sorry I will change intents to just be discord.Intents.all()

long scroll
#

inside discord developer portal?

sage tendon
#

yes

long scroll
#

ok

#

I still get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
its from message = await channel.fetch_message(message_id)

sage tendon
#

then you are most likely fetching a message that doesnt exist

#

also, why would it not be cached?

long scroll
#

I tried bot.get_message but it didn't work

sage tendon
#

same error?

long scroll
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

sage tendon
#

hm

#

are you sure you have message intents

long scroll
#

oh no sorry wrong error

sage tendon
#

and the right message ID

long scroll
sage tendon
#

well get the right one then lol

long scroll
#

sorry

#

get_message gives me this error TypeError: object NoneType can't be used in 'await' expression

sage tendon
#

hm

long scroll
#

also I'm using message = await ctx.respond() and message.id to get the message ID so I can change it later but its different from the value I get when I copy it from discord

sage tendon
#

uh yea thats not how it works

#

respond returns an interaction

#

so you need to do (ideally)
interaction = await ctx.respond()
message = interaction.message

long scroll
#

oh thank you

#

it says
AttributeError: 'NoneType' object has no attribute 'id'

round heart
#

I'm sure this is been asked before but can't find anythign definitive

I have a Message Command. Is there a way to acknowledge that interaction without writing an actual message about it?

lofty parcel
#

Not really

edgy girder
#

That just removes the interaction

long scroll
#

why does interaction.message return None?

sage tendon
#

is it an ephemeral message?

long scroll
#

there is no Dismiss message button on the message

sage tendon
#

hm

delicate scroll
#

hi im kinda losing my mind rn because the solution is probably really simple but, I have a bot set up to join voice chat, listen and transcribe audio, then if it hears its name spoken get a response from an AI and send back the response. then the response goes through edge tts and outputs an mp3. HOW can I get the bot to immediately play the mp3 file into discord voice, im completely failing on all the solutions ive seen around

lofty parcel
delicate scroll
#

yeah this is what i tried but it keeps telling me it doesnt have is_connected

lofty parcel
#

Could you show the traceback?

delicate scroll
#

ok justa sec

#

just paste it in a code block?

#
Traceback (most recent call last):
  File "M:\miniconda\envs\yui\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\nani\AppData\Roaming\Python\Python38\site-packages\discord\opus.py", line 556, in run
    self.client.recv_decoded_audio(data)
  File "C:\Users\nani\AppData\Roaming\Python\Python38\site-packages\discord\voice_client.py", line 841, in recv_decoded_audio
    self.sink.write(data.decoded_data, self.ws.ssrc_map[data.ssrc]["user_id"])
  File "m:/Desktop/YuiAI/Yui2Voice.py", line 186, in write
    global_stream_buffer.write(data=data, user=user,wtime=time.time())
  File "m:/Desktop/YuiAI/Yui2Voice.py", line 116, in write
    asyncio.run(ys)
  File "M:\miniconda\envs\yui\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "M:\miniconda\envs\yui\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "m:/Desktop/YuiAI/Yui2Voice.py", line 148, in yuispeak
    await yuiaudio()
  File "m:/Desktop/YuiAI/Yui2Voice.py", line 168, in yuiaudio
    discord.VoiceClient.play(source, source, after=None)
  File "C:\Users\nani\AppData\Roaming\Python\Python38\site-packages\discord\voice_client.py", line 657, in play
    if not self.is_connected():
AttributeError: 'str' object has no attribute 'is_connected'

this whole project is hacked together so i have no idea just how broken this really is (its more impressive that it works at all in my opinion 🙃 )

sage tendon
#

well show your code there

#

you're trying to call is_connecetd on the wrong thing

delicate scroll
#

see thats why im confused cause i dont know why its calling that either

#

using the voiceclient.play is calling for is_connected and idk if im just not using it in the wrong place or what

sage tendon
#

i mean

#

whats the line in your code that causes that

delicate scroll
#
    discord.VoiceClient.play(source, source, after=None)``` according to the traceback?
sage tendon
#

i mean you have to know that, dont ask me lmfao

#

but yea i wont be much help tbh, i have never touched voice

delicate scroll
#

yeah idk why its bringing up a connected issue either pepehands

lapis dock
lapis dock
delicate scroll
#

the only instance in my code is the line that errors at, should i be calling something else to play audio?

lapis dock
lapis dock
delicate scroll
#

Ok maybe one of you can help me this way, I have a command that can play the output audio when you do >r

is it possible to call / execute it from somewhere else in code instead of sending >r as a message in a channel

#
@bot.command()
async def r(ctx):
    voice = discord.utils.get(bot.voice_clients,guild=ctx.guild)
    audio = FFmpegPCMAudio('testshift.mp3')
    voice.play(audio)

this 'just works' as a command, can i call / execute this from somewhere in code instead of using a discord message or is it required to be from a discord message

lapis dock
delicate scroll
#

i get nothing but errors if any of the commands code is outside of a command im starting to think its either not possible or above me sobber

delicate scroll
#

i did?????????????

maiden bloom
#

Do you use pycharm and know how to set breakpoints and debug? That would solve this pretty quick

round heart
#

Is there a good way to store the current View's children (to preserve state - labels, disabled status, etc), modify those children, and then restore everything back to that? Directly modifying the View's self.children causes it to error out when it tries to update the message with the new View state

Context: I want to modify a button and disable all other controls when someone presses a 'Submit' button on a View (as it's deferred, which doesn't give the greatest UI feedback), and if there's a problem, restore it all (and I'd do separate stuff to indicate error, etc etc)

vital bramble
#

Has this question been answered? Asking myself the same question but could not find anything.

lapis dock
#

.rtfm customactivity

warm jay
#

It failed to install

#

Oh yeah, I need to use 3.11.x py

subtle moth
#

Is there a way for pycord to not automatically sync slash commands

little cobalt
little cobalt
warm jay
little cobalt
#

with pip install py-cord?

subtle moth
little cobalt
subtle moth
#

Understandable

little cobalt
#

That would be after a restart of the bot ;3

subtle moth
#

Wait

#

Guess I dont need to overwrite it

little cobalt
#

You can

warm jay
little cobalt
#

?tag install

limber wagonBOT
#

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

sage tendon
#

honestly don't use 3.12 until you really have to lol

warm jay
sage tendon
#

just uninstall 3.12?

warm jay
#

I can try that

shell radish
little cobalt
#

you can use the terminal or the package manager at PyCharm

sage tendon
#

that assumes they're using a venv

round heart
# lapis dock what kind of errors?

Not at my desk, but something about the len() of self.children which I thought was weird since I was directly setting it with data that came from self.children.copy()

shell radish
little cobalt
shell radish
shell radish
little cobalt
#

I was using it with the terminal and PyCharm was installing it at the env

#

I havent tested it on unix

#

Lemme try it at the VM

sage tendon
shell radish
#

if it doesn’t exist click Add we interpreter

warm jay
#

Let me update packages firrt

shell radish
warm jay
#

aiohttp fails to install on 3.12

sage tendon
#

you didnt read

shell radish
sage tendon
#

no, not you

round heart
#

Okay, re-asking this question now that I'm not being completely dumb - -
Is there a good way to store the current View's children (to preserve state - labels, disabled status, etc), modify those children, and then restore everything back to that?

Context: I want to modify a button and disable all other controls when someone presses a 'Submit' button on a View (as it's deferred, which doesn't give the greatest UI feedback), and if there's a problem, restore it all (and I'd do separate stuff to indicate error, etc etc)

    def save_state(self):
        self.child_state = self.children.copy()

    @discord.ui.button(row=2, label='Submit', style=discord.ButtonStyle.green)
    async def submit(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.save_state()

        button.emoji = self.spinner  # discord.Emoji instance
        button.disabled = True
        button.label = 'Submitting...'

        await interaction.edit(view=self)
        await asyncio.sleep(2)

        self.children = self.child_state
        await interaction.edit(content='Complete?', view=self)

I get the 'Complete?' text, so everything is "working", but the View does not get restored. Stepping through it, it looks like my child_state is a reference instead of the .copy() I'm clearly performing.

#

So I guess the question is ... wtf?

lapis dock
round heart
#

Unless I guess the members are by reference. This is where I get a little shaky on Python variable access.

#

Yeah, it must be. I still have my debugger paused, if I do

blah = self.children.copy()
self.children[1].label = 'asdf'
blah

I can clearly see that blah[1] is now 'asdf', where I would have expected it to be the pre-changed state. My head hurts.

lapis dock
#

Try deep copy

#

Think you have to import copy

#

The copy.deepcopy(list) or something

round heart
#

I will.. But barring that, what about self.to_components()? I guess I would have to figure out how best to pull them back into the View on restore (maybe a combination of .clear_items() and recreating the component walking from .from_message()?)

round heart
round heart
#

Hm. Running into issues with Pycord/dpy's own hydrator.
.to_components() returns a list of dicts that represent the data of each component. Then there's an internal function _component_to_item that seems like it's supposed to take that data and convert it to an Item.

Strangely, this seems to expect a class, whereas to_components returns a dict

round heart
#

I'm not sure what use that method has (which calls each Item's .to_dict()), since it doesn't seem to be used anywhere.

maiden bloom
#

While my bot is up I have jobs that are scheduled to execute at a certain time using AsyncIOScheduler. When I restart the bot, however, all these jobs need to be rescheduled and this is turning into decent amount of processing to do after the bot is ready. Does anyone have any suggestions on how I can optimize this process at all?

sullen mauve
#

How to create a ban command

#

I can't find it in docs

little cobalt
subtle moth
sullen mauve
#

you*

little cobalt
#

but at the end they both do the same

onyx sentinel
#

guys im having trouble, i want to log chat messages on console but message.content is not showing up nothing. Here is the bot event:

@bot.event
async def on_message(message):

    print(f"{message.created_at} | {message.author.name}: {message.content}")
lofty parcel
onyx sentinel
#

how do i fix that?

lofty parcel
#

?tag intents

limber wagonBOT
#

Pycord Docs - Intents
Discord API Docs - Gateway Intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
onyx sentinel
#

ty

lofty parcel
#

You only use one of those three options

#

Not all of them

#

Depends on what you need

onyx sentinel
#

ok

hallow copper
#

impressive

lofty parcel
hallow copper
lofty parcel
#

can't say it publicly.

hallow copper
#

supporter chat then?

#

if that’s still somehow too public you can dm it

sullen mauve
#

?tag cxt

limber wagonBOT
#

dynoError No tag cxt found.

sullen mauve
#

?tag context

limber wagonBOT
#

dynoError No tag context found.

hallow copper
#

?tag ctx

limber wagonBOT
#

dynoError No tag ctx found.

dense prawn
#

Someone can help I want to know how to store views like button and select menu to keep working even bot restarts??

rugged lodgeBOT
#

Here's the persistent example.

little cobalt
#

@dense prawn ^

dense prawn
sullen mauve
#

Does anyone know how I can use ctx to ban,kick, timeout a member(s)

If there is a specific guide on that it will be much appreciated thanks in advance

sage tendon
#

the docs

#

read what ctx actually refers to and go from there

sullen mauve
#

Okay

sage tendon
#

look for discord.ApplicationContext

#

that has everything you need

high pilot
#
Traceback (most recent call last):
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Dell\onedrive\desktop\demo\main.py", line 319, in button_callback1
    await interaction.response.edit_message(content=f'Are you sure you want to unlink this account? \nUsername: {self.username} \nGovernor ID: {self.govid}',view=MyView4(self.username,self.govid, self.author, 'main')) # Send a message when the button is clicked
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 979, in edit_message
    state.store_view(view, message_id)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 386, in store_view
    self._view_store.add_view(view, message_id)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 581, in add_view
    view._start_listening_from_store(self)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 425, in _start_listening_from_store
    self.__timeout_expiry = time.monotonic() + self.timeout
TypeError: unsupported operand type(s) for +: 'float' and 'str'
#

what does this mean

sage tendon
#

you cant concatenate a float and a string

#

at least not like that

high pilot
#

where did i did that i dont understand

sage tendon
#

if you wanna actually do addition, well, self.timeout appears to be a string

high pilot
sage tendon
#

did you use chatgpt to make that

high pilot
#

nope

sage tendon
#

copilot? :)

high pilot
#

nope made it myself sorry beginner

sage tendon
#

nah just wondering because of the indescriptive class name and the comment lol dw

high pilot
#

previous versions worked

sage tendon
#

2.5.0 broke it?

high pilot
#

let me check which pycord version i have

#

didnt update but the same code hosted on the real server works. i was testing new things not changed anything in this but it broke

sage tendon
#

also you are on python 3.9
I suggest updating to 3.11 if you dont have a reason not to

#

i think 3.12 might work now too since the pycord update

high pilot
#

is there a huge advntage in doing hat?

sage tendon
#

Generally, if you don't have a reason NOT to, it's always a good reason to update
Because if you don't, eventually you will be a trillion versions behind and that might cause other issues
I'll actually try 3.12 now too because i've been wanting to update for a long time but 2.4.1 didnt allow for that

high pilot
#

okay will sure do

high pilot
# high pilot

done understand yet why its taking self.timeout as a string

sage tendon
#

shouldnt be the cause of your issue though

sage tendon
high pilot
#

i had made some changes to the file but not to this view locally

#

well restarting my pc did work

sage tendon
#

lol

high pilot
#

weird

#

gotta love python *)

sage tendon
#

3.12 does work with py-cord 2.5 now btw

high pilot
#

nice whats the major update in py-cord 2.5

sage tendon
#

#library-updates

#

its a minor update though ;)

#

3.x would be a major update

#

Now i need help myself lmao

I updated to 3.12 and now jishaku says its sad, what can i do

little cobalt
#

Im still gonna stick with 3.11

#

Because anything is working with it

sage tendon
#

jishaku just needed a patch version bump

#

even tho jishaku says it only supports up to python 3.10

little cobalt
#

Im using it with 3.11 ^^

lofty parcel
#

same

#

and it works fine

sage tendon
#

yea i know

#

and it works with 3.12 too on the very latest version

#

i was just using the penultimate one

lapis dock
fresh totem
#

Morning!

@client.slash_command()
@discord.default_permissions(administrator=True)
async def news(ctx: discord.ApplicationContext, order: Option(str, 'News Snippet', choices=['1'])):
    "Post news"

How can I make commands exclusive to certain Role IDs

little cobalt
fresh totem
lapis dock
#

that is something that each individual server managers will do.
Server Settings -> Integrations -> Your Bot -> Your Command
Disallow everyone, add role to allow

sage tendon
#

Bots can do that themselves, though

lapis dock
#

they cant hide the command though.

If you want to be extra sure that nothing gets messed up you can use ext.commands.has_role. This will make the command error out if they dont have the role but it will not make it hidden

sage tendon
#

of course they can

#

If you dont have permission to use a command it doesnt show up

errant trout
#

Bots can only hide commands by permission, not by role

lapis dock
#

I meant bots cant set the allowed roles for a command. They can set a default permission only

errant trout
#

^ Only staff with manage integrations can add role/channel overrides

fresh totem
#

Okay that makes sense, I'll have it altered from the Integrations tab and implement ext.commands.has_role as well.

Thank you!

sage tendon
#

like if you set a command to a specific role in dynos dashboard it can sync that to your server

#

just tried, yep

errant trout
#

that's because larger dashboard bots such as mee6 and dyno bypass this limitation via oauth

#

the reason we generally say it isn't possible is because the average user doesn't have such a setup

sage tendon
#

hm

#

ok

frosty ocean
#

Can someone please tell me what the attribute for the Send Voice Messages permission is?

#

Because with send_voice_messages I get the error "Invalid permissions given to keyword arguments"

lapis dock
#

you are probably on an old version. Please update to pycord 2.5

frosty ocean
#

Now it works thanks

granite pier
#

is there way to use partial_messageable to send dm to user without other unnecessary API calls e.g. for getting user.dm_channel?

sage tendon
#

if you have the user or member you can just use .send

granite pier
#

nah, plain id thats why im asking

#

also i dont use cache

#

so i have to call fetch/send or just partial.send if possible

#

but to use partial i prolly have to use dm_channel.id instead of user.id

#
.get_partial_messageable(
  dm_channel_id, type=discord.ChannelType.private
)
sage tendon
#

yea I never did stuff with partial, no idea

shell radish
#

although if you already have an User object why not just user.send

granite pier
shell radish
#

and what ID is that

granite pier
#

id = int
but im not using User model as it is kind of DB task thing

shell radish
#

I mean how did you get the ID. Is the ID of an user or what

granite pier
#

yep

#

but ill probably stick to:

if task.guild_id:
    channel = self.client.get_channel(task.channel_id)
else:
    channel = self.client.get_user(
        task.user_id
    ) or await self.client.fetch_user(task.user_id)

then

shell radish
#

well, the dm channel id is different from the user id

granite pier
#

yep

#

😄

#

thats the sad thing

#

so ill have to do 2 api calls anyway

#

in cases theres no user in cache

shell radish
#

so you have to make some API request

sage tendon
#

just wondering, why do you not use cache?

granite pier
#

😄

sage tendon
#

RAM is there to be used

shell radish
granite pier
#

i mean like XX milions of members

shell radish
#

lol

sage tendon
#

man owns mee6

shell radish
sage tendon
#

lmfao

#

yea, right

granite pier
#

milions of users = not guilds

onyx sentinel
#

guys why message.content doesnt work at all

sage tendon
onyx sentinel
#

yes

sage tendon
#

in the dev portal and used in your code?

onyx sentinel
#

nah

sage tendon
#

then you don't have message content intent

onyx sentinel
#

oh

shell radish
#

can you show your bot’s definition

onyx sentinel
#

wdym definition

sage tendon
#

where you define your bot variable

onyx sentinel
#

oh

#

hold on

granite pier
# shell radish looks fine to me

I don't think there is a better option because just calling user.create_dm() will come down to the same thing (or worse altogether) ;p

shell radish
#

define= definition

onyx sentinel
#
class PersistentViewBot(discord.Bot):
    def __init__(self):
        super().__init__()
        self.persistent_views_added = False

    async def on_ready(self):
        await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"Pycord 2.5.0"))
        print(f"Logged in as {self.user} (ID: {self.user.id}) at {round(bot.latency * 1000)} ms")
        print("------")

bot = PersistentViewBot()
granite pier
shell radish
sage tendon
#

lol

granite pier
shell radish
#

messages only makes you receive message events and is included with default

onyx sentinel
#

do i put this inside the class?

sage tendon
#

yes

onyx sentinel
#

k

shell radish
onyx sentinel
#

im getting a error

sage tendon
#

show it

onyx sentinel
#
Traceback (most recent call last):
  File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\accionarBotV1.py", line 57, in <module>
    bot.run("TOKEN")
  File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 766, in run
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 745, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 709, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 646, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
sage tendon
#

read

#

the text

onyx sentinel
#

oh

#

i found it

#

why i cant generate an innvite url?

sage tendon
#

you tell us

onyx sentinel
#

it asks me for a redirect url

shell radish
#

you need to be more specific than that

onyx sentinel
#

but there is nothing on this select box

shell radish
#

what scopes did you check

lapis dock
shell radish
#

uncheck everything except bot

onyx sentinel
shell radish
onyx sentinel
#

when i uncheck messages.read the link is generated

sage tendon
#

yea

#

use it

shell radish
onyx sentinel
#

ahh

errant trout
#

(You should keep applications.commands if you want slash commands)

shell radish
sage tendon
#

there are way too many scopes btw

errant trout
#

Oh right

#

Ohwell

onyx sentinel
sage tendon
#

bot.

#

only.
bot.

onyx sentinel
shell radish
#

we would love to explain every oauth scope, but it really doesn’t matter

sage tendon
onyx sentinel
#

how

shell radish
#

it’s under the bot tab

sage tendon
#

read?

onyx sentinel
#

which one do i check

sage tendon
#

message content

shell radish
#

scroll down until you see message content intent

onyx sentinel
#

cant find it

sage tendon
#

screenshot

onyx sentinel
sage tendon
#

not there notlikethis

onyx sentinel
sage tendon
#

dude
the bot tab

onyx sentinel
#

oh ok

sage tendon
granite pier
#

so I think that there is no need for this altogether

onyx sentinel
#

oh ok

shell radish
#

reading is hard

onyx sentinel
#

i think i found it

shell radish
#

it’s a switch

onyx sentinel
sage tendon
#

yes

onyx sentinel
#

ty

granite pier
#

so there was better option lol

sage tendon
#

Is there a way to make an empty message with only an embed actually ping someone?

sage tendon
#

no

#

I need multiple mentions

#

and it comes from a slash command

shell radish
#

yeah there’s the invis messages thing so “no” content, but I wouldn’t do that because it’s like exploiting

sage tendon
#

yea I was hoping there was some way to either make embed pings ping, or mention people via an argument ig

errant trout
shell radish
#

it sounds like he wants the message background to be highlighted

sage tendon
#

that too if possible

maiden bloom
#

Is there a list of breaking changes for v2.5?

sage tendon
#

it's a minor version

deft kestrel
#

hey

sage tendon
#

it has no breaking changes

deft kestrel
#
@bot.slash_command(name='leave', description='leaves a server')
async def leave(ctx, guild_id):
    try:
        if ctx.author.id == 1097367679028953199:
            guild = bot.get_guild(guild_id)
            if guild is not None:
                await guild.leave()
                print(f'Left guild {guild.name} upon command from {ctx.author}')
                await ctx.send(f'Left guild {guild.name}')
            else:
                await ctx.send("Guild not found.")
        else:
            embed = discord.Embed(color=colorfail, description="You are unauthorized to use this command")
            await ctx.respond(embed=embed, ephemeral=True)
    except:
        embed = discord.Embed(color=colorfail, description="Unable to leave that server")
        await ctx.respond(embed=embed, ephemeral=True) ```

Is there a documentation on how to make a guild leaver
#

cause I don't think this is right

maiden bloom
sage tendon
sage tendon
shell radish
#

just ping them

maiden bloom
#

Oh idk what that means lol

sage tendon
#

time to educate yourself on something mildly important in online software

sage tendon
maiden bloom
#

I’m currently in the bathroom at a dentist office, but yes I will 😂

deft kestrel
#

so

#

I put a guild id the bot is in

#

and then it returns guild not found

sage tendon
#

yea you can't get a guild you aren't in

#

so use get_or_fetch from discord.utils

#

i think that supports guilds

#

but i think you can just fetch if you dont use it a billion times a minute

fresh totem
#

I'm trying to fetch all the members with a specific role:

guild = client.get_guild(814824676240654376)
role = guild.get_role(9897619211291233)
print(role.members)

Result:

[<Member id=814555443812368404 name='iampacificator' global_name='PACIFICATOR 🔮' bot=False nick=None guild=<Guild id=814824676240654376 name='MiServidor' shard_id=0 chunked=False member_count=38>>]

But it only manages to fetch me, despite 7-8 other members having the same role. Bot has administrator perm

#

I would like it to fetch all members with the role, what am I missing?

loud kayak
#

then show me what it says

fresh totem
# loud kayak have the bot print `guild.members`

guild.members 👇

[<Member id=999202880345079929 name='Elon Test Bot' discriminator='9914' bot=True nick=None guild=<Guild id=814824676240654376 name='MiServidor' shard_id=0 chunked=False member_count=38>>, <Member id=814555443812368404 name='iampacificator' global_name='PACIFICATOR 🔮' bot=False nick=None guild=<Guild id=814824676240654376 name='MiServidor' shard_id=0 chunked=False member_count=38>>]

It's unable to print all the members, only the user (myself) and the bot itself (Elon Test Bot)

granite pier
errant trout
#

(i was wrong)

granite pier
#

yep

#

😛

errant trout
#

mixed up with fetch_guild

#

but yeah just enable member intent

granite pier
loud kayak
#

thats why members aren't showing up

frail ocean
#

Is there a way to set a image in a streaming activity

frail ocean
#

?tag animated avatar

limber wagonBOT
#

dynoError No tag animated found.

frail ocean
#

?tag animated_avatar

limber wagonBOT
#

dynoError No tag animated_avatar found.

frail ocean
#

?tag avatar

limber wagonBOT
#

dynoError No tag avatar found.

frail ocean
#

?tags

limber wagonBOT
#
Tags (117)

yt-tutorials, youtube, xy, wavelink, virtualembed, usernames, usercmd, update, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, this, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, slashblog, rie, restartcmd, requests, replit-install, replit, removeall, pythonversion, pythonserver, python, practices, pp, pomelo, persistant_view, paste, partial_objects, oracle, option, oop, om, official, objects, notpycord, norepl, nojson, nohelp, nohello, no_status, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, logging, localfile, learnpython, json, intents, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, git, gif_avatar, getalpha, get_x, get-help, gather, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, cmd-limits, closing, client, chatgpt, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, 429

frail ocean
#

?tag search avatar

limber wagonBOT
#

dynoError No tag search found.

#
Tags (1)

gif_avatar

frail ocean
#

?tag gif_avatar

limber wagonBOT
#

How to upload an animated avatar for your bot

To use and upload an animated avatar you can run the following snippet as standalone script:

import discord

# Create a Discord client instance
client = discord.Client(intents=intents)

# Event to handle bot's initialization
@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

    # Upload animated avatar
    try:
        with open('yourpicture.gif', 'rb') as avatar:
            await client.user.edit(avatar=avatar.read())
        print('Animated avatar uploaded successfully!')
    except Exception as e:
        print('Failed to upload animated avatar:', e)

# Run the bot
client.run("YOUR_TOKEN")

That should be all, have fun!

hazy turret
#

With autocomplete, can I also transfer a second value in the background to the transferred value with which I can continue to work?

matching_users = [user.email for user in user_datas if user.email.lower().startswith(ctx.value.lower())]
return matching_users 

@slash_command(name="update_user", description="Update Userdata")
@option(
     "email",
     description="E-Mail",
     autocomplete=user_data_email_autocomplete,
     required=False,
 )
 async def update_user_data(self, ctx: discord.ApplicationContext):
     #Here I would like to continue working with the ID from the e-mail database

So I could, for example, also transfer an ID for each e-mail from a user, which I can then use in the callback?

vital bramble
#

There should be name and value... Don't know if pycord actually lets you use both.

errant trout
#

it does

errant trout
#

name is purely visual, while value is the string recieved in the command

hazy turret
errant trout
#

yes

#

(just remember that autocomplete isn't enforced, always validate the value)

hazy turret
# errant trout yes

Like that ?

matching_users = [OptionChoice(name=user.email, value=str(user.id)) for user in user_datas if user.email.lower().startswith(ctx.value.lower())]
return matching_users 
errant trout
#

yeah perfect

hazy turret
errant trout
#

unlike choices which you are forced to choose from, autocomplete results are optional; users can enter any value

#

so for example, in your command callback you should verify that the userid you recieve actually exists

vital bramble
#

aren't autocomplete just dynamic choices?

errant trout
#

almost, but again they aren't enforced

hazy turret
errant trout
#

yes

hazy turret
#

Then I could simply check in my function whether a value is specified or not?
Because then the user can't specify it manually?

errant trout
#

yes, you have to enforce it within your command

#

using optionchoice you only recieve value as a str, so in your case just check if the user id exists

hazy turret
errant trout
#

no, you only get the value as a string

#

you just type email directly

hazy turret
errant trout
#

mhm

hazy turret
# errant trout mhm
matching_users = [user.email for user in user_datas if user.email.lower().startswith(ctx.value.lower())]
return matching_users 

@slash_command(name="update_user", description="Update Userdata")
@option(
     "email",
     description="E-Mail",
     autocomplete=user_data_email_autocomplete,
     required=False,
 )
 async def update_user_data(self, ctx: discord.ApplicationContext, email: str):
     email_value = email #This is the user id ?
errant trout
#

that's right but you don't really need to do that

hazy turret
#

Yes, I can work directly with email, but I did it this way for clarification 🙂

#

Thank you very much!

round heart
#

Is there a quick way to determine whether a user is new (would have that little leaf icon)?

lofty parcel
#

Member.joined_at?

round heart
#

Wouldn't that just show when they joined the server, not Discord?
Was just hoping there was a fetchable flag

lofty parcel
#

Not new discord users

graceful swift
#

Hi, any recommendation to run a Selenium function evading the rest of the bot functions to stop?

lofty parcel
#

asyncio.run

#

Or a task

#

Depends on what your function does

graceful swift
#

Basically fills forms and scraps data

#

asyncio.run could be the answer tho

#

Let me give it a try

lofty parcel
#

Or using bot.loop

#

I think both are technically the same?

fresh totem
fresh totem
elfin quarry
#

Hello, can someone please try and test on_stage_instance_delete on their end and see if it triggers when ending the stage? I'm on pycord 2.5.0 and it seems that it is not working. on_stage_instance_create works just fine btw. I just want to know if it is an issue on my end or library's end.

frail ocean
#

Can someone tell me how I can fill a dropdown menu with all server members

little cobalt
frail ocean
#

Do you have an example

little cobalt
#

you create a view class and a select menu at the class with ```py
@discord.ui.user_select()

onyx sentinel
#

guys help me pls: i've noticed that Option and OptionChoice doesnt work anymore, can someone help me using an alternative method?

@bot.slash_command()
async def test(ctx, member : Option(discord.Member, description="Select a member", required=True)):
# ...
onyx sentinel
#

importing Option and OptionChoice

#

i gave a bad example my bad

errant trout
#

you get an error?

onyx sentinel
#

yes

#
Traceback (most recent call last):
  File "d:\Users\Davi\Desktop\programas\codes\python\pycord\botteste\main.py", line 10, in <module>
    from discord.ext.commands import Option, OptionChoice
ImportError: cannot import name 'Option' from 'discord.ext.commands' (C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\__init__.py)
#

i think something changed due to updates

little cobalt
#

use discord or discord.commands and not from ext.commands

onyx sentinel
#

oh

#

ok

#

ty it worked

grizzled loom
#

How can I supress all warnings for an aiomysql INSERT IGNORE statement?

subtle moth
subtle moth
low solar
#

nvm i fixed it alr

grizzled loom
oblique sable
#

hey guys any way of havng a ctx command in pycord, that also works if the bot is pinged?

#

heard there is an argument to pass when you are creatnig the bot instance, but dont remember what it was

little cobalt
oblique sable
#

thank you: that was it

frail ocean
errant trout
# frail ocean Is this also possible in a command not a class

you can use views without classes, it just gets really messy py view = View() select = Select(type=...) async def callback(interaction): ... select.callback = callback view.add_item(select)this in itself doesn't look *that* bad, but it looks horrible if your code is any longer and need to do extensive stuff

#

i'd recommend the subclassing route for better overall code, but the above works if you're a maniac basically

#

(i say this as someone who extensively used this method years ago and now shys away from touching the related cog)

low solar
#

hello so basically i made a ticket bot that creates a transcript in my bot directory, but when i try to send it

file_path = f'./{interaction.channel.name}.txt'
await interaction.user.send(file=discord.File(file_path))```
it sends a blank txt file
torpid cosmos
low solar
#

it has info inside of it

torpid cosmos
#

show directory structure?

low solar
#

my other command can read through the json file so it should work with sending the txt

torpid cosmos
#

are they both in the same file?

low solar
#

no

#

different cogs

torpid cosmos
#

alright, thanks. And what about the code that writes to the file?

low solar
#
class CloseTicket(discord.ui.View):
    @discord.ui.button(label="Close Ticket!",style=discord.ButtonStyle.primary, emoji="❌")
    async def button_callback(self, button, interaction):
        filename = f"{interaction.channel.name}.txt"
        with open(filename, "w") as file:
            async for to_be_transcripted in interaction.channel.history(limit=None):
                file.write(f"{to_be_transcripted.created_at} - {to_be_transcripted.author.display_name}: {to_be_transcripted.clean_content}\n")    
                file_path = f'./{interaction.channel.name}.txt'
                await interaction.user.send(file=discord.File(file_path))
                await interaction.channel.delete()```
thats the entire closing ticket/creating transcript code
torpid cosmos
#

try removing the ./ from file_path

#

It looks like you're sending the file in your for loop. So, every message that's processed would send a new file to the user. Try it with two messages. You'll get two files

low solar
#
file_path = f'{interaction.channel.name}.txt'```
nan kb
torpid cosmos
#

Make sure you send the file to the user outside of the with block

#

that makes sure the file is written to and closed

#

Also, you may want to open the file in a mode instead; every time you call write when it's openend in w mode, i believe it overwrites all of the file contents

low solar
#

i tried fixing it for the past 1h or so

torpid cosmos
#

no problem, glad I could help

urban zealot
#

For some reason, it's making it so that every time I switch to another option inside the select menu, it goes back to the default as the selected option which is general. I don't remember this ever happening before but I also can't remember how to fix it

oblique sable
#

hey, quick question as i keep having errors with interactions
i am trying to delete an interaction, and i have this error

return await self.interaction.delete_original_response(delay=delay)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 552, in delete_original_response
await func
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 222, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 381, in invoke
await injected(ctx)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token

when doing await interaction.delete()

is there like a delay or something?

#

i didnt really seem to find anything on this error code, if someone has some documentation about it please send it to me 🙏

shell radish
#

why are you deleting an interaction?

oblique sable
#

i want to make it stop working for the user

#

actually found this message, i think this is the problem

#

this error only happens when the interaction is after 15 minutes

#

is there any way to "renew" it?

sage tendon
#

in views?

oblique sable
#

yes, because i have a "panel", and when the user clicks on something sometimes it sends ephemeral messages, seems that when its on a view for more than 15 minutes, it also gets this error

#

50027

sage tendon
#

set a longer timeout

oblique sable
#

i set it to None

sage tendon
#

hm