#Basic Pycord Help (Quick Questions Only)

1 messages · Page 76 of 1

solemn idol
#

how can I disable the usage of slash commands in my bot's dms?

young bone
#

guild_only

solemn idol
#

its that simple?

young bone
#

;3

solemn idol
#

lol ty

solemn idol
#

because currently I get this (in dms)

cyan quail
#

guild_only will make it not show at all in DMs

green hinge
#

If I make a change to the code and then run this command, the change is not reloaded so I still have to restart the bot completely. Why is this?

@bot.command()
@commands.is_owner()
async def reload(ctx, cog):
    try:
        bot.reload_extension(f'cogs.{cog}')
        await ctx.send(f"Reloaded {cog}!")
    except Exception as e:
        await ctx.send(f"An error occurred while reloading {cog}: {e}")```
copper pine
#

Hello, all the commands in my bot use @slash_command(), but I need them to also be usable with a prefix. Does anyone know how I can achieve this without having to create two separate commands?

solemn idol
tall oyster
#

Hi! Could you tell me, how to make a bot react to pressing any buttons?

copper pine
young bone
proud mason
#

just as a test

proud mason
copper pine
proud mason
#

subclass bridge.Bot

#

wait hold on

#

why do you have bot = bridge.Bot() but also have a subclass??

#

use only 1 bot instance

#

?tag client

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

bridge.Bot has all the features of the rest of the client classes

copper pine
#

i tried with bot = Bot() but i get the same error, i don't understand very well

proud mason
#

also, show the full error

copper pine
proud mason
# copper pine

did you import from discord.ext.bridge import bridge_command in the cog file?

copper pine
proud mason
#

can you show the full cog

cyan quail
#

reloading is perfectly functional above v2.2 or so

proud mason
# green hinge What do you mean exactly?

idk if you are aware, but if you unload the cog, the slash commands still work. that is until you call await bot.sync_commands()

this is because unloading the cog (somehow) doesnt remove the cmd from the internal bot cache

now i think reloading will be affected by this too. the old command wont be affected

cyan quail
#

sync isn't the issue here

proud mason
#

oh my bad

#

lol

cyan quail
#

...i think anyway; reloading doesn't need to resync or anything since it just needs to remap command objects to their IDs properly

green hinge
cyan quail
#

is this for prefix commands?

green hinge
cyan quail
#

i don't think you can reload view callbacks(?)

green hinge
#

prefix

proud mason
#

||fk i was helping thinking it was about slash cmds 💀||

proud mason
cyan quail
#

well tbf they never specified

#

but yeah, cog management is limited to commands and listeners

green hinge
proud mason
#

i think if you put the view in the same file as the cog, you might be able to do it. try this and see

#

because you can have commands in extensions without cogs, and still be able to reload them

#

so views should work like that too

cyan quail
#

probably not, the code itself never references ViewStore so the items are never updated

proud mason
#

oh yeah, the existing view wont change, but futures ones should

cyan quail
#

oh yeah ofc

green hinge
#

Is there a way to completely reload an existing cog when making an extension or adding a completely new cog to the bot without having to completely restart the bot ?

solemn idol
#

cuz this dont work

cyan quail
#

guild_only applies only to the root command, which subcommands inherit

#

(because discord doesn't actually treat subcommands as commands)

#

the same applies to stuff like nsfw and default_permissions

solemn idol
cyan quail
#

yes

solemn idol
#

ah

#

ok

copper pine
proud mason
coarse cargo
#

So i created a reload command that should reload an extension with bot.reload_extension(), and i tried to change the message the bot send as response to a command (this is located in a yml file) but it doesn't update. Any idea? Also it looks like it updates only if i change something in the cog.

#

There is like a way to force it?

copper pine
cyan quail
coarse cargo
cyan quail
#

hmm can you show the cog file code?

coarse cargo
#

whole?

cyan quail
#

well, omit any unrelated commands/functions i guess

proud mason
#

also, do you cache the contents of the yml file, or do you re-read it in the function?

solemn idol
# cyan quail yes

its painful my subcommand is pretty much a mess so uh this gonna take a while ig

cyan quail
#

it's get_commandsinfo?

coarse cargo
#

do you want to see the function maybe?

cyan quail
#

sure

#

though realistically what you've done here should work?

coarse cargo
#

yeah if i restart the bot it works

#

it updates the message in the yml file it updates it if i restart

#

but if i reload it doesnt

cyan quail
#

well i mean, it should work even with cog reloads

#

but the other function would also help

coarse cargo
#
def get_commandsinfo(command, key):
    if command and key == "prefix":
        return commands["commands_prefix"]
    elif command and key == "answer":
        return commands["answer_command"]
    else:
        return commands[command][key]
cyan quail
#

what's commands?

coarse cargo
#
with open("configuration/commands.yml", 'r', encoding="utf-8") as file:
    commands = yaml.safe_load(file)
cyan quail
#

hmmmmmmmmmmmmmmm

#

that's probably the issue, reloading has some conflicts when it comes to imports

#

if you reload a cog, if you've updated a file that it imports the updated file doesn't actually apply

coarse cargo
#

i read somewhere it was working perfectly so i thought about implementing it lol

cyan quail
#

iirc you can get around it through some hacks

proud mason
#

you could just load the yml in the cog init

coarse cargo
cyan quail
#

yeah that's the more reliable way

coarse cargo
#

i decided to it this way for don't have duplicates over the files yk

proud mason
#

hmm yea that file isnt being reloaded. so the yml isnt being read again

coarse cargo
#

i have found 2 problems in pycord in a day lool

cyan quail
#

well the method i recall finding was

proud mason
#

what i would do is, store commands as a botvar, and then add a utility function which reloads this var. personal choice however

cyan quail
#
  1. reload cog
  2. use importlib.reload to reload the imported function
  3. reload cog again
proud mason
#

sounds overkill? 👀

cyan quail
#

it's not a particularly pretty method but it works, though i recommend just restructuring your code

coarse cargo
#

so just import the yml file in the cog?

cyan quail
#

inside its __init__

#

that way, whenever you reload the cog it's guaranteed to load the new file

coarse cargo
#

gotcha

cyan quail
#

if you want to restructure, instead of all these imports py from utils.config_parser import (get_commandsinfo, get_consolelogsinfo, get_optionsinfo, get_serverinfo, get_ticketpanelinfo)you should make that into a class that implements all those functions

#

then this class' init can take the yml file

#

and then the cog will load this single class instance which you can always reference py class TicketCommands(commands.Cog): def __init__(self, bot): self.bot = bot with open(...) as file: self.data = SomeClass(yaml.safe_load(file))

solemn idol
#

How in gods name was I supposed to get on this?
this is what made my subcommand part work (guild only, so it doesnt respond in dms)
But the documentation ab it is realllllllyy bad tbh.

class logging(discord.Cog, description='Logging commands.'):
    logging = discord.SlashCommandGroup("logging", "Logging related commands", guild_only=True,
                                        default_member_permissions=discord.Permissions(manage_guild=True))```
cyan quail
#

not really? the examples already show that

solemn idol
#

Ig I am blind

errant craneBOT
#

Here's the slash cog groups example.

coarse cargo
cyan quail
#

nah not particularly

#

if you go with a class structure, then after you've got the class you can just do some basic replaces

solemn idol
coarse cargo
#

also as now i get the yaml file inside the cog i need to change the path i guess?

cyan quail
#

e.g. with my example above, get_commandsinfo becomes self.data.get_commandsinfo (though you may consider renaming the functions)

#

if you lead it with a / then the path will start from your main bot file

#

so it can remain relative

coarse cargo
#

so

#

this: configuration/commands.yml
to this: /configuration/commands.yml

cyan quail
#

actually i think it always works from main file anyway?

solemn idol
#

@cyan quail a friend of mine (which helped me find out abt it; still doesn't particulary like it... cough

cyan quail
#

at least from what my own code is doing, idk just give both a try

cyan quail
#

and all the attrs and methods are listed

#

unfortunately people are utterly incapable of reading docs, but that's their problem in the end

solemn idol
#

mkay

coarse cargo
#

anyway @cyan quail maybe can you report the thing about the relaod?

cyan quail
#

hm?

solemn idol
#

reloading cogs or what?

cyan quail
#

you could make a github issue, but the problem with imports inside a cog is that they aren't particularly easy to handle

#

the importlib trick i mentioned probably works but it isn't really a good fix

topaz rune
#

hi, sorry to disturb, I dont understand how can I moove pepoles from a channel to another, could someone explain it to me please?

solemn idol
topaz rune
#

ty buddy

copper pine
#

Hello again, i fixed the problem about @bridge_command(), but now there's a problem with the args.

young bone
#

@solemn idol here you can see it again with requests x3

young bone
solemn idol
#

like seriously usually it took like 2 seconds to load or smth idk now its just 250ms

young bone
#

ye because its also blocking the whole bot

solemn idol
#

HAHHAHA LOL

#

oh fuck XD

copper pine
young bone
solemn idol
#

wait no thats bridge

#

I am not sure if that works with bridge

solemn idol
#
async def create_embed(self, api_endpoint: str, footer_text: str):
        async with aiohttp.ClientSession() as session:
            async with session.get(api_endpoint) as response:
                content = await response.text()
                data = json.loads(content)
                em = discord.Embed(
                    title=data['title'],
                    url=data['postLink'],
                    color=em_default
                ).set_image(url=data['url']).set_footer(text=footer_text)
                return em

Which is why I am glad I did it like this

young bone
solemn idol
#

I literally didnt have to rewrite any of my other commands, just that function :P

#

@copper pine then I guess use @option decorators :P

copper pine
cyan quail
#

you might need to use BridgeOption with bridge commands

copper pine
proud mason
cyan quail
#

oh it converts Option to BridgeOption automatically

proud mason
#

yea

cyan quail
proud mason
#

i think typehinting the Option doesnt work for bridge commands blobpain

#

Because the error makes it look like the library is trying to convert the parameter to Option type, rather than str

proud mason
copper pine
white wadi
#

hi, how do i set the correct error type?

async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
    if isinstance(error, discord.ext.commands.has_role(110475336766700445)):
        await ctx.respond("You are not allowed to use this command!")
    else:
        raise error  # Here we raise other errors to ensure they aren't ignored```
cyan quail
#

no just remove exactly what i put

#

you can leave the actual description text as positional

copper pine
cyan quail
#

you did Option(str, "description")?

proud mason
white wadi
copper pine
cyan quail
#

so only prefix breaks and not slash?

copper pine
#

The solution would be not to give a description to the argument :/

young bone
#
@client.bridge_command()
@discord.option("text", description="")
async def test(ctx, text: str):

that also should work with bride commands

copper pine
#

Thank you so much

winged ravine
#

I'm a bit confused as to when to use guild.members vs guild.fetch_members()? I understand that the first is a cache, but if it is the first time it is access will it call back to the api?

#

what would be the best way to get all the members of a guild that do not have the @Guest role?

proud mason
#

iirc, fetch_members does not have role data

winged ravine
#

ah...

proud mason
#

and fetch_members is quite slow, especially with large guilds

winged ravine
#

yh i can bet (it being a direct api call for all members)

proud mason
#

use guild.get_role(id) to get the role, and then do smth like [m for m in guild.members if role not in m.roles]

winged ravine
# proud mason you could use a list comprehension

i was using a set comprehension but i didnt know the best actual method to call

{OptionChoice(name=f"@{member.name}", value=str(member.id)) async for member in guild.fetch_members() if not member.bot and guest_role not in member.roles}
cyan quail
#

if the guild is large definitely don't use fetch_members in autocomplete

winged ravine
cyan quail
#

by default more or less all your members will be cached

#

you can check this by printing len(guild.members)

proud mason
#

if you wanna get a bit technical,

when chunk_guilds_at_startup is set True (True by default) in the Bot init, and members intent is enabled, then the library requests members data for each guild during startup. this data comes from the gateway, and not the api. this data is cached.

wild cobalt
#

How can I create a new iterable when a slash command is used, to use in an autocomplete in that slash command? I want to get records from a database when the slash command is used, then present those records for the user to select one. It’s an online database so currently it’s doing a records GET with each call of the autocomplete, hardly ideal

cyan quail
proud mason
#

you could also use an LRU cache

grizzled sun
#

hi yes im stupid, how do I get interaction.response.edit_message
to actually edit the message with new text?

grizzled sun
#

thank you

fossil mulch
#

Hi guys, I'm struggling right now with TortoiseORM running on my Bot in my cogs. The init in my main.py is working but the slash command gives me some ```tortoise.exceptions.ConfigurationError: default_connection for the model <class 'src.mako.db.models.DiscordGuild'> cannot be None

wild cobalt
cyan quail
#

so if someone's typing out a full word it won't be spammed

#

but basically, lets say you have a var self.records = {}

#

in your autocomplete, you check if this has anything in it; if not, make the request and set self.records = ...

#

then you also record the current utcnow() in some other variable

#

with that current time, in your autocomplete you should also compare the current utcnow() with the previous utcnow() and see if a certain time has passed

#

e.g. via datetime.timedelta

wild cobalt
#

and self in this case is... the class instance of the slash command?

cyan quail
#

well i was speaking in a cog context

#

if you aren't using cogs it'll still work without self

wild cobalt
#

no cogs, am rank amateur

solemn idol
#

is there not even a single way to use the built in help command stuff to make a /help command...?

fervent cradle
#
        @commands.cooldown(1, 120, commands.BucketType.user)
        @option("beg_method", description="Choose your beg method", choices=["Normal beg", "Super beg", "Advanced beg"])
        @bot.slash_command(description="beg for money")
        async def beg(ctx, beg_method: str):

why is it not letting me choice and wants the user to write it themselves does not display the options

proud mason
cyan quail
proud mason
cyan quail
proud mason
fervent cradle
#

o

proud mason
#

The command decorator is to be kept at the top

solemn idol
#

its a bit overcomplicated in my opinion but at the same time it does look nice... as in the code itself... my code on the other hand is an absolute mess rn.

#

You don't want to see my moderation cog 💀

#

It works but it is not done as well as it should've been done.

young bone
#

Just create one cog for every command xd

solemn idol
dapper pasture
#

How can i close for example session when my bot is stopped, so that i wouldn't get RuntimeError: Event loop is closed Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001B5A2E2CA60>

solemn idol
atomic slate
#

Hello! I've only recently gotten into ‘pycord’. I'm frustrated with being asked by my supervisor to develop a Discord app using ‘pycord’. This application requires the user to play an uploaded video or an RTSP video stream, and the video stream frame can be obtained on the server side for reprocessing. I want to know whether some components can meet such requirements and hope to get a simple guide.

silver moat
#

what is an RTSP video stream?

dapper pasture
#

can u pls answer

silver moat
#

@dapper pasture let's make a new post. I have a feeling this will take some time.

dapper pasture
#

k

silver moat
#

@atomic slate If you mean a Discord "Stream" in a voice channel, that is currently not possible with bots.

silver moat
#

Also, Pycord is a Discord API Wrapper, meaning that it can help you view/interact with Discord. If you are looking ways to manipulate video data you might be looking for FFMPEG: https://ffmpeg.org/ or Pycord, an FFMPEG wrapper: https://pypi.org/project/pycord/.

#

You can get attachments on messages with message.attachments.

silver moat
atomic slate
#

Thanks, I need to think carefully.

cyan quail
#

(if you somehow do mean over discord's voice channels, bots can't access the video API for those so you'd be out of luck anyway)

winged ravine
patent knoll
#

Is autocomplete just so confusing or am I pissing myself because it seemed confusing af when i first looked at it

winged ravine
#

If the checks of a MessageCommand fail, will it prevent it from even showing in the apps context menu list? or will it just prevent it from executing?

patent knoll
# patent knoll Is autocomplete just so confusing or am I pissing myself because it seemed confu...

e.g. i am currently trying to get the "value" https://docs.pycord.dev/en/stable/api/application_commands.html#discord.AutocompleteContext.value
but i have no goddamn idea how since if i just do "value" it says its missing required positional arguments

#

nvm, i figured it out
The docs are REALLY bad at portraying that IMO
the value is an attribute of the interaction

uncut blaze
#

Question, tried some searches but couldn't find a similar issue. I've installed pycord, but PyCharm doesn't seem to be recognizing 'discord' as an alias for pycord.

So when I start with import discord, I get an error saying no module named discord despite pycord being installed. Any ideas?

solemn idol
#

It might be that you had discord.py before and it interferes with pycord

#

Or that the version is just extremely buggy

uncut blaze
#

So I'm not using a venv as im just testing this locally before I deploy, so please don't judge... but...

abstract_singleton==1.0.1
aiohttp==3.8.4
aiosignal==1.3.1
anyio==3.6.2
astroid==2.15.4
async-generator==1.10
async-timeout==4.0.2
asynctest==0.13.0
attrs==22.2.0
auto_gpt_plugin_template==0.0.3
autoflake==2.1.1
beautifulsoup4==4.12.2
black==23.3.0
bleach==6.0.0
blis==0.7.9
build==0.10.0
cachetools==5.3.0
catalogue==2.0.8
certifi==2022.12.7
cffi==1.15.1
cfgv==3.3.1
chardet==5.1.0
charset-normalizer==3.1.0
click==8.1.3
colorama==0.4.6
confection==0.0.4
coverage==7.2.3
cssselect==1.2.0
cymem==2.0.7
dill==0.3.6
distlib==0.3.6
distro==1.8.0
dnspython==2.3.0
docker==6.0.1
docutils==0.19
duckduckgo-search==2.8.6
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl#sha256=35365d49d389ecb19ba33119dca9ab9ff80b36fbeb063fa5d44008197fead8fa
exceptiongroup==1.1.1
ffmpeg-python==0.2.0
filelock==3.12.0
flake8==6.0.0
frozenlist==1.3.3
future==0.18.3
gitdb==4.0.10
GitPython==3.1.31
google-api-core==2.11.0
google-api-python-client==2.86.0
google-auth==2.17.3
google-auth-httplib2==0.1.0
googleapis-common-protos==1.59.0
gTTS==2.3.1
h11==0.14.0
httpcore==0.17.0
httplib2==0.22.0
httpx==0.24.0
identify==2.5.22
idna==3.4
imageio-ffmpeg==0.4.8
importlib-metadata==6.6.0
iniconfig==2.0.0
isort==5.12.0
jaraco.classes==3.2.3
Jinja2==3.1.2
jsonschema==4.17.3
keyring==23.13.1
langcodes==3.3.0
lazy-object-proxy==1.9.0
loguru==0.7.0
lxml==4.9.2
markdown-it-py==2.2.0
MarkupSafe==2.1.2
mccabe==0.7.0
mdurl==0.1.2
more-itertools==9.1.0
multidict==6.0.4
murmurhash==1.0.9
mypy-extensions==1.0.0
newsapi-python==0.2.7
nodeenv==1.7.0
numpy==1.24.2
oauthlib==3.2.2
openai==0.27.2
openapi-python-client==0.14.0
orjson==3.8.10
outcome==1.2.0
packaging==23.1
pandas==2.0.1
pathspec==0.11.1
pathy==0.10.1
Pillow==9.5.0
pinecone-client==2.2.1
pkginfo==1.9.6
platformdirs==3.2.0
playsound==1.2.2
pluggy==1.0.0
pre-commit==3.2.2
preshed==3.0.8
protobuf==4.22.3
py-cord==2.4.1
py-cpuinfo==9.0.0
pyasn1==0.5.0
pyasn1-modules==0.3.0
pycodestyle==2.10.0
pycord==0.1.1
pycparser==2.21
pydantic==1.10.7
pyflakes==3.0.1
Pygments==2.15.1
pylint==2.17.3
PyNaCl==1.5.0
pyparsing==3.0.9
pyproject_hooks==1.0.0
pyrsistent==0.19.3
PySocks==1.7.1
pytest==7.3.1
pytest-asyncio==0.21.0
pytest-benchmark==4.0.0
pytest-cov==4.0.0
pytest-integration==0.2.3
pytest-mock==3.10.0
python-dateutil==2.8.2
python-dotenv==1.0.0
pytz==2023.3
pywin32==306
pywin32-ctypes==0.2.0
PyYAML==6.0
readability-lxml==0.8.1
readme-renderer==37.3
redis==4.5.4
regex==2023.3.23
requests==2.28.2
requests-oauthlib==1.3.1
requests-toolbelt==1.0.0
rfc3986==2.0.0
rich==13.3.5
rsa==4.9
scripts==2.0
selenium==4.9.0
shellingham==1.5.0.post1
six==1.16.0
smart-open==6.3.0
smmap==5.0.0
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.4.1
spacy==3.4.4
spacy-legacy==3.0.12
spacy-loggers==1.0.4
srsly==2.4.6
stua==0.2
thinc==8.1.9
tiktoken==0.3.3
tomli==2.0.1
tomlkit==0.11.8
tqdm==4.65.0
trio==0.22.0
trio-websocket==0.10.2
tweepy==4.13.0
twine==4.0.2
typer==0.7.0
typing_extensions==4.5.0
tzdata==2023.3
uritemplate==4.1.1
urllib3==1.26.15
virtualenv==20.22.0
wasabi==0.10.1
webdriver-manager==3.8.6
webencodings==0.5.1
websocket-client==1.5.1
win32-setctime==1.1.0
wrapt==1.15.0
wsproto==1.2.0
yarl==1.8.2
youtube-dl==2021.12.17
zipp==3.15.0
#

This is from pip freeze, let me know if there's a better way to get this list 😼

solemn idol
#

pip freeze?

uncut blaze
#

Ya if you run pip freeze in cmd it will output a list of all your packages, is that not the way you'd like to see?

solemn idol
#

Idk I usually just get it using pip list

uncut blaze
#

Okok it gave the same list just in a different format, would you like that?

solemn idol
#

Nah if it's the same it works fine ig

#

So basically you have py-cord... But discord isn't there anymore which should be installed with pycord (when you install py-cord) which is strange in your case

young bone
uncut blaze
#

Okay, I've uninstalled pycord and pip installed py-cord per the documentation

#

Seeing py-cord2.4.1 but still no discord in the list, and getting the same error :/

uncut blaze
solemn idol
#

Wth

silver moat
solemn idol
silver moat
solemn idol
#

Center.

#

Checkmate?

spare juniper
#

pipe install pie cord

silver moat
# solemn idol Checkmate?

No, because after Qc6+, there’s Bb7+ blocking the check and forking your king and queen, so it is a draw by insufficient material.

spare juniper
#

Checkmate in 4

solemn idol
#

No U

spare juniper
#

Checkmate sequence lost

silver moat
#

I’ll just sacrifice my bishop for your passed pawn.

near hollow
#

Are there events for timeouts and kicks?

solemn idol
#

For when someone gets kicked?

#

There's an event for on user leave

silver moat
fervent cradle
#

can a message containing a view be updated/edited with a new view / embed?

strong bobcat
#

Please help, command pip uninstall discord.py doesnt work

candid coral
#

Can a class take 2 classes at once? Example:

class Name1(discord.ui.View):
   def __init__(self, ...)
        super().__init__(timeout=180)
        ...
        Name2()

class Name2(discord.ui.View, Name1):
    def __init__(self, ...)
        super().__init__(timeout=180, ...)
proud mason
candid coral
#

But a class originally have the discord.ui.View class, so is it possible to take the variables of two classes at once?

#

I searched the answer to this question but I didn't find it, so I decided to turn here

strong bobcat
#

Please help. i installed pycord but i still get "no module named discord" error

full basin
strong bobcat
full basin
#

Show your pip list

strong bobcat
spring hare
#

pip list

full basin
#

I said pip list

#

If you're using a host that installs the packages from requeriments.txt show it too ig

strong bobcat
full basin
#

Remove pycord. But otherwise, I don't see any issues

#

What's interaction-files?

strong bobcat
obsidian ermine
#

Oh okay that makes sense, thank you pepeLove

full basin
strong bobcat
#

I also have pycord installed from github, but what to do with the error there is "no module named discord"

full basin
#

Show me your updated file

#

@strong bobcat

#

Paste the text. Don't send the file

strong bobcat
#

I deleted folder site-packages and it work

#

But i get another error

#

Bad request. Invalid Form Body. In guild_id: Value "Ellipses" in not snowflake"

strong bobcat
strong bobcat
full basin
#

?tag instances

obtuse juncoBOT
#

dynoError No tag instances found.

full basin
#

?tag clients

obtuse juncoBOT
#

dynoError No tag clients found.

full basin
#

Smh

proud mason
#

?tag client

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

@full basin ^

#

lol

full basin
#

Tha ks lmao

tribal girder
#
Traceback (most recent call last):
  File "/home/container/cogs/utils.py", line 60, in reload
    self.bot.unload_extension(f'cogs.{extension_name}')
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 1068, in unload_extension
    self._remove_module_references(lib.__name__)
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 722, in _remove_module_references
    self.remove_cog(cog_name)
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 706, in remove_cog
    cog._eject(self)
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 592, in _eject
    bot.remove_command(command.name)
AttributeError: 'BridgeCommand' object has no attribute 'name' 

how to fix this? i want to reload a cogs using bridge_command

proud mason
#

master branch has a few changes. make sure to read the change log

#

?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

tribal girder
#

update?

proud mason
#

last line

tribal girder
#

ty

proud mason
#

np! 🙃

candid coral
#
AttributeError: 'NoneType' object has no attribute 'edit'
#

This error occurs when "on_timeout" fires after changing to the second class. on_timeout in second class doesn't see buttons, I don't understand why. If I use "on_timeout" in the first class then it fires in the second class changing to the buttons of the firts class

ripe tiger
#

why doesn't guild.members or bot.get_all_members() output all users, just the bot itself?

neon bramble
#

you probably don't have the right intents

ripe tiger
neon bramble
#

the kwarg is intents not intent

proud mason
proud mason
proud mason
ripe tiger
candid coral
proud mason
#

you code will remain the same as before

candid coral
#

Cannot find command 'git' - do you have 'git' installed and in your PATH?

#

?tag git doesn't work

#

"?tag" is not an internal or external command, operable program, or batch file.

proud mason
candid coral
obsidian wing
#

can you not use async def on_message function, and @commands.command stuff in the same file? dead

proud mason
proud mason
#

are you using @bot.event for the on message event?

obsidian wing
#

yep

#

let me make an

#

example code that wasn't working for me

#

I've changed it up now but it's a bit dodgy the way I've done it, so please hol up dead

proud mason
#

@bot.event for the message event will stop prefix commands from running
change that to @bot.listen()

obsidian wing
#

YOUR MY SAVIOUR T-T

snow widget
#

Hello, pls help me someone:
how to use on_message event in cogs?
My code now:

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

    @bot.event
    async def on_message(self, message):
        if message.content == "anything":
            await message.delete()
            await message.channel.send("Something")


def setup(bot):
    bot.add_cog(any(bot))```
young bone
coarse cargo
#

the reload command for a cog should be in the main file or can it be in cog as well?

coarse cargo
#

ok thanks for the info

young bone
#

you can have it in a cog or main file

coarse cargo
#

i don't know why i thought the command needed to be in another file and not in the cog

solemn idol
#

fun fact reload doesnt work because issues.

young bone
solemn idol
#

slash commands dont really get reloaded do they?

young bone
#

the sync command is kinda broken xd

solemn idol
#

yeah thats what I meant.

#

thus #2015 on github

young bone
#

you can edit the message

#

but not really the slash command

solemn idol
#

works on discord.py so it should work on pycord too :P

coarse cargo
#

How should i handle NotOwner, i have tried this but it doesn't work.

        try:
            self.bot.reload_extension(f'tickets.ticket_commands')
            await ctx.respond(f"{get_commandsinfo('reload_command', 'success_message')}")
        except discord.ext.commands.errors.NotOwner as error:
            await ctx.respond(f"{get_commandsinfo('reload_command', 'error_message')}")
proud mason
coarse cargo
#

yup

proud mason
proud mason
#

see that

coarse cargo
fervent cradle
#

How do I edit an embed in a newly created thread? I stored the message id of the newly created thread then tried to use .edit(), but that returned TypeError: Thread.edit() got an unexpected keyword argument 'embed'.
Code stub below:

forum_channel = bot.get_channel(CHANNEL_ID)
first_embed = discord.Embed(...)

msg = await forum_channel.create_thread(embed=first_embed)
new_embed = discord.Embed(...)

await msg.edit(embed=new_embed)
cyan quail
#

you want thread.starting_message

fervent cradle
#

Thank you!

zinc cloak
#

Is it normal for a command even with guild_ids to take time registering?

cyan quail
cyan quail
zinc cloak
cyan quail
#

using cogs?

zinc cloak
#

nope

#

should I manually sync it?

cyan quail
#

well it's meant to auto sync so chances are you're doing something wrong

#

did you override on_connect?

zinc cloak
cyan quail
#

nice

zinc cloak
#

if I override it,

#

then it won't sync?

cyan quail
#

pretty much

#

you could change @bot.event to @bot.listen()

zinc cloak
cyan quail
#

listen doesn't override

zinc cloak
fervent cradle
#

What's the best way to edit an old embed's field that is no longer in cache? It is a simple embed with only 2 fields (one inline) and a footer. I want to edit the inline field but keep the rest of the embed's content the same. I retrieved the message with the embed using .history()

edit: nvm. to_dict() and from_dict() make it easy.

cyan quail
full basin
#

does before_invoke also count for message commands?

#

or what listener gets triggered on prefixed commands

near hollow
#

Is it possible to get the duration a person is timed out for and the person who did it?

cyan quail
cyan quail
#

for who did it, you'd need to get it from audit log

near hollow
#

Alright sounds good thanks for the help!

proud mason
proud mason
#

Huh why does that not show up

#

But anyways, the event on_command gets fired for each prefix command

silver moat
fervent cradle
#

im using a modal and it asks for inputs, takes them in fine using .wait() but after submitting (which uses the values to make a channel, which happens sucessfully), the modal doesn't auto close and instead says like "something went wrong, try again later.". any obvious reasons this could be happening?

cyan quail
fervent cradle
#
            modal = Modal(
                title = "Create a Ticket",
            )
            x = InputText(label="x", placeholder="X", custom_id="xxx")
            y = InputText(label="y", placeholder="Y", custom_id="yyy")
            z = InputText(label="z", placeholder="Z", custom_id="zzz")
            
            modal.add_item(x)
            modal.add_item(y)
            modal.add_item(z)
            
            await interaction.response.send_modal(modal)
            
            await modal.wait()
        
            x = x.value
            y = y.value
            z = z.value
#

thats basically what it looks like

fervent cradle
cyan quail
#

Have you never used other items like buttons or selects?

fervent cradle
#

so this is basically like a ticket bot

cyan quail
#

Well it's the exact same structure

fervent cradle
#

you click button, this is a callback of that button

cyan quail
#

Define the callback for the modal and respond to its interaction

fervent cradle
#

kk

elfin dagger
#

i think i broke something, my on_ready event is triggering properly but my bot isn't showing as online and none of its slash commands are showing up
even worse is that if i use pycharm instead of vscode and run the code it works

#

i think it's because of something on how the code is written because the code that's in vscode is very very different from the code in pycharm because i was doing a little temporary side project and just recycled the token

cyan quail
#

What versions of pycord are you running on each?

elfin dagger
#

let me check rq

cyan quail
#

And does anything unexpected appear in console

elfin dagger
#

2.4.1 for both

elfin dagger
cyan quail
#

You 100% sure? No difference in venvs or anything?

elfin dagger
#

there's probably a lot of differences but im not entirely sure how to check

#

where my newbiness shows :(

cyan quail
#

Try printing discord.__version__ somewhere in your bot on both

elfin dagger
#

they both show 2.4.1

cyan quail
#

Are you doing anything in particular in on_ready?

elfin dagger
#

no just printing ready

cyan quail
#

Have you got anything else that runs on your bot outside of commands?

elfin dagger
#

like prefix commands?

cyan quail
#

Well anything that doesn't require manual input

elfin dagger
#

i don't think so, there's a couple functions that are called when a command is run though

cyan quail
#

Hmmm

#

Can you show your main file then?

elfin dagger
#

well there's two different ones because i recycled the token for a different temp project

cyan quail
#

If they have different features then perhaps that's the issue...?

elfin dagger
#

yeah that's what i was thinking but when i switched over from vscode it worked fine

#

all the previous commands disappeared and the new one appeared

#

but now it won't go back

#

i think resetting the token would be best here?

#

yeah i'm just gonna reset it and see if that fixes it

#

nope it is still very broken

cyan quail
#

I mean, personal opinion, just don't use vscode

elfin dagger
#

would pycharm be better?

cyan quail
#

For python it's significantly better yeah

elfin dagger
#

it was working fine with vscode until i decided to use the token in pycharm :/

cyan quail
#

You're not running both at the same time right

elfin dagger
#

no

#

what really confuses me is that it prints ready but it is clearly not ready

strong bobcat
#

Please help, i cant use discord.Interaction.response. AttributeError 'CachedSlotProperty' has no atribute 'send_message'(and 'defer)

fervent cradle
#

How to send message using webhook?

proud mason
strong bobcat
# proud mason Show the code
async def Test(ctx: discord.ApplicationContext):
            await discord.Interaction.response.send_message("Test", ephemeral=True);```
proud mason
#

Just use await ctx.respond(...)

#

Much simpler

errant craneBOT
#

Here's the slash basic example.

strong bobcat
#

Ok.Thanks!

frail canopy
#

Quick question guys.
Is there any reason that the code below is not working?
I need to run a function daily at specific time and it's not executing when the time reaches.
Keep in mind that this is in a cog.

@tasks.loop(count=None, time=datetime.time(hour=17, minute=0, second=0))
async def hello_world(self):
  print("Hello World")
frail canopy
# young bone Do you start it?

yes i did, i start it in the cog’s init. If I change to relative time, e.g. @tasks.loop(count=None, seconds=30) it works. Do I need to put in an array?

young bone
#

I mean do you have a line with "self.hello_world.start()"

frail canopy
#

My experience troubleshooting scheduled functions are telling me is timezone issue but i doubt it.

cyan quail
candid coral
#

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

#

This error appears periodically. I don't know the reason

full basin
#

You're taking too long to respond

twin flume
#

anybody have any tips on how to fix this or know what I am doing wrong? I am trying to make sure that discord.py is installed. Im on Windows.

#

maybe I should just install pycord

young bone
full basin
#

Despite the fact this is pycord support and not dpy

twin flume
#

TRUE

grizzled sun
#

Is there a good way to turn a dict into a list of discord.selectoptions for a dropdown menu?

grizzled sun
#

thanks

#

Cool

#

Good to know I'll keep searching for it then /s

cyan quail
errant craneBOT
#

discord/components.py lines 459 to 472

@classmethod
def from_dict(cls, data: SelectOptionPayload) -> SelectOption:
    try:
        emoji = PartialEmoji.from_dict(data["emoji"])
    except KeyError:
        emoji = None

    return cls(
        label=data["label"],
        value=data["value"],
        description=data.get("description"),
        emoji=emoji,
        default=data.get("default", False),
    )```
cyan quail
#

basically this is best used if you've saved your SelectOption as a dict using to_dict

grizzled sun
#

I have not

#

Basically just wanted to get all the keys from a dict and then turn them into dropdown list for the search

cyan quail
#

oh that's a bit easier

#

just some list comprehension

#

what do your dicts look like

grizzled sun
#

I'll send the first couple entries, it's just key then some matching aliases for that region

#
'Bachtalan': ['bachtalan', 'bach', 'talan'],
'Cortashar Dominion': ['cortashar dominion', 'cortashar', 'cd'],
'Dirk': ['dirk', 'drk'],
'Srath': ['divine empire of srath', 'srath', 'des', 'empire'],```
cyan quail
#

you can just iterate through easily py options = [discord.SelectOption(label="...", value="...") for x in dict]

grizzled sun
#

Oh aye, that is pretty easy

cyan quail
#

x would just be the key; both label and value are required

#

so i'd recommend you do some transform on x to normalise it

#

though

#

perhaps it'd be better to leave the same so you can get the real value back through get

grizzled sun
#

but thank you, this is a lot easier than manually editting it every time I gotta add a new entry to the dict

cyan quail
#

mhm, iteration is king

grizzled sun
#
options = [discord.SelectOption(label=region, value=region, description=f"Select {region}?") for region in TravelTime.regions]```

Works well and without issue
twin flume
young bone
#

maybe

#

maybe xd

#

We are gonna see it after the update

silver moat
#

still waiting for docs

patent knoll
#

how do i make a task that repeats every X hours with cogs

candid coral
#

In my code inside 4 different buttons there is the same part of the code, I want to put it into a function. The result of this function is to edit a message, which doesn't work:

class Name(discord.ui.View):
    def __init__(self, argument1, argument2, ...)
        super().__init__(timeout=...)
        self.variable1 = argument1
        self.variable2 = argument2
        ...

    def function(argument1, argument2, ...):
        ...
        await interaction.response.edit_message(...) # wrong

    @discord.ui.button(...):
        async def button(...):
            ...
            function(self.variable1, self.variable2, ...)```
candid coral
#

Thank you

river summit
#
client.load_extensions("cogs.misc", recursive=True, store=False)

i keep getting errors trying to do this. so shouldn't this load every cog in the misc folder or have i not understood what load_extensions does?

river summit
# young bone what is the error?

not really an error but the commands just dont load. the bot goes online and has no errors.

my directory:

└───bot
├───cogs
│ ├───misc
│ └───moderation

i've tried to wrap it in a try/except block still nothing.

young bone
#

are you sure if the cogs are loaded?

river summit
#

it appears they dont even load

#

okay fixed.

#

ty for the help

young bone
river summit
patent knoll
#

how do i properly create a slashcommandgroup using the decorator

cyan quail
patent knoll
#

or do they mean the bot.group decorator i cant use in cogs

cyan quail
#

that's just the class... a decorator never existed

#

because unlike prefix groups, a slash group can't have a callback

#

so there's no purpose

proud mason
#

||imagine docs being accurate||

cyan quail
#

true

patent knoll
#

is python stupid?

cyan quail
#

skill issue

#

you might have to do a from import

proud mason
#

try from cogs import utility 👀

#

me when i have to import stuff in cogs đŸ˜©

patent knoll
#

yea i just realized, i did cogs.utilities now
it's weird that it imports based on the bot.py path

proud mason
#

yea thats kinda intentional

solemn idol
#

That's always been like that :P

twin flume
#

Do I need to worry about fixing this error?
The bot runs fine
Error was given when I debugged the file in Visual Studio Code

twin flume
#

I did in fact read the error (???)

young bone
#

how do you define the token in the env?

twin flume
#

TOKEN =

young bone
#

TOKEN or token?

twin flume
#

the bot comes online and commands work

#

token = str(os.getenv("TOKEN"))

#

should I put this before the TOKEN line?
edit: It worked

young bone
#

Do you know basic python?

twin flume
#

I am learning

#

Reading a guide on Python and trying to implement the topics taught as I go along

young bone
#

pls learn the basic's first

twin flume
#

Alright...(?)

full basin
#

pycord is not a simple library

coarse cargo
patent knoll
spare juniper
#

haha

spare juniper
#

before you ran the bot

twin flume
#

uh

#

ty 4 the help < 3

coarse cargo
spare juniper
spare juniper
silver moat
#

just try-except it maybe?

coarse cargo
silver moat
#

well you asked to hide it

spare juniper
#

i think they meant the functoin that closes the bot does not throw the error

#

some other thing does

#

but then again squid knows more about pycord than me

frail canopy
# frail canopy Quick question guys. Is there any reason that the code below is not working? I n...

It's really weird about this. I'm using py-cord 2.4.1, and the documentation said it is new in 2.0 version. I've changed to use an array instead of single datetime and yet it's still not triggering when the clock hits 10:30 a.m. Should I use a different approach then?

class Birthday(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot
        print("Start Birthday Task")
        self.wish_birthday.start()

    @tasks.loop(time=[datetime.datetime.strptime('10:30AM', '%H:%M%p').time()])
    async def wish_birthday(self):
        print(datetime.datetime.now().strftime("%d/%m/%Y, %H:%M:%S"))
        print("HAPPY BIRTHDAY")
        
def setup(bot: Bot):
    bot.add_cog(Birthday(bot))
silver moat
#

If this doesn't work, open an issue on github

young bone
#

Is the toolkit bot broken again?

silver moat
#

@errant crane

#

I mean it's offline

cyan quail
#

time arg works fine for me on loops

#

though idk why you'd use strptime...

frail canopy
# cyan quail though idk why you'd use strptime...

I've been trying lots of things, I thought is data type issue or some sort, but i finally found the issue. The default timezone is set to UTC... I need to pass my own machine's timezone into the time object.

cyan quail
#

is it running on UTC? i assumed default was machine but i guess not

#

...though i can't remember if we fixed the timezone bug for that

frail canopy
#

I've only found that when I keep the bot running and it executes 8 hours earlier because my time is in UTC+8. So right now after setting to the correct UTC, it is working as expected. Thanks alot.

hybrid wraith
#

py-cord==2.4.1

attributeerror: 'bot' object has no attribute 'slash_command'. did you mean: 'add_command'?

Experiencing the above error on gated build for my python app.

Runs locally absolutely perfectly, fails GitHub gated build with the error above.

Requirements.txt file locally and in source control contain pycord lib.

Does anyone know how to fix this?

silver moat
#

send full traceback and your list of requirements

young bone
#

pycord or py-cord?

silver moat
hybrid wraith
#

No stack trace. Just the error above and fails gated build.

Literally just the error above, not kidding. Well it says exit code 1 as well in GitHub.

Locally it works as intended. No errors.

List of requirements I will get.

hybrid wraith
young bone
hybrid wraith
#

@silver moat

silver moat
#

These libraries conflict with py-cord:

discord==2.2.2
discord-ext-bot==1.0.1
discord-py-slash-command==4.2.1
discord.py==2.2.2
hybrid wraith
#

I see. What would the best approach be?

silver moat
#

just remove them

#

unless you require them in some way

hybrid wraith
#

I don't think I do. I will give this a shot tomorrow.

Is it the case the py-cord contains these libraries?

silver moat
hybrid wraith
#

Ah. I see. Thank you for your help 🙂

silver moat
#

yw

simple steppe
#

Hi, I'm completely new in creating discord bots. How can I use it with command for example !test?

import discord
from discord.ext.pages import Paginator, Page

my_pages = [
    Page(
        content="This is my first page. It has a list of embeds and message content.",
        embeds=[
            discord.Embed(title="My First Embed Title"),
            discord.Embed(title="My Second Embed Title"),
        ],
    ),
    Page(
        content="This is my second page. It only has message content.",
    ),
    Page(
        embeds=[
            discord.Embed(
                title="This is my third page.",
                description="It has no message content, and one embed.",
            )
        ],
    ),
]
paginator = Paginator(pages=my_pages)```
proud mason
topaz rune
#

Hi, in order to send a message on a voice channel (on it's textual place), can I just await channel.send() ir or is there a different syntax

full basin
#

.tias

winter condorBOT
drowsy fractal
#

How do I set any number of parameters for a slash command, 2 required and up to 8 optional?

coarse cargo
topaz rune
#

can someone give me the doccumentation of slash commands pls? I dont find it

#

sorry

coarse cargo
topaz rune
#

ty

proud mason
#

that thing is the description btw

#

pass it to @bot.slash_command()

topaz rune
#

ok like this:

@bot.slash_command(description="this is a test")
async def ping(ctx):
    await ctx.respond(f"Pong {ctx.author.mention}!")

?

proud mason
#

looks right

#

.tias

winter condorBOT
topaz rune
#

yeah yeah I get it, it will work, but I want to know what else ccan I put as args into bot.slash_command() except name and description please?

#
  • it's just doesn't work, like I can't use the command
proud mason
#

reload your discord client

topaz rune
#

already did bro

#

isn't an official doccumentation about slashcommands?

topaz rune
proud mason
#

you can pass almost everything thats in the attribute list, but stick to only name, description, nsfw, guild_ids and guild_only

#

other stuff has better ways to do it. like decorators for default permissions, options, localisation, cooldown etc

topaz rune
#

hm

young bone
topaz rune
#

ty

coarse cargo
topaz rune
# young bone discord.Option

File "/srv/barman/main.py", line 490, in <module>
type=discord.OptionType.STRING,
AttributeError: module 'discord' has no attribute 'OptionType'

#
aiohttp             3.8.4
aiosignal           1.3.1
async-class         0.5.0
async-timeout       4.0.2
asyncio             3.4.3
attrs               20.3.0
beautifulsoup4      4.12.2
blinker             1.4
certifi             2020.6.20
chardet             4.0.0
charset-normalizer  3.1.0
cloud-init          20.4.1
configobj           5.0.6
cryptography        3.3.2
dbus-python         1.2.16
distro-info         1.0
fail2ban            0.11.2
frozenlist          1.3.3
gyp                 0.1
httplib2            0.18.1
idna                2.10
importlib-metadata  1.6.0
Jinja2              2.11.3
jsonpatch           1.25
jsonpointer         2.0
jsonschema          3.2.0
MarkupSafe          1.1.1
more-itertools      4.2.0
multidict           6.0.4
oauthlib            3.1.0
Pillow              9.5.0
pip                 20.3.4
py-cord             2.4.1
pycurl              7.43.0.6
PyGObject           3.38.0
pyinotify           0.9.6
PyJWT               1.7.1
pyrsistent          0.15.5
PySimpleSOAP        1.16.2
python-apt          2.2.1
python-debian       0.1.39
python-debianbts    3.1.0
PyYAML              5.3.1
reportbug           7.10.3+deb11u1
requests            2.25.1
setuptools          52.0.0
six                 1.16.0
soupsieve           2.4.1
systemd-python      234
tk                  0.1.0
turtle              0.0.1
typing-extensions   4.5.0
unattended-upgrades 0.1
Unidecode           1.3.6
urllib3             1.26.5
watchdog            3.0.0
wheel               0.34.2
yarl                1.9.2
zipp                1.0.0

I dont have discord.py

young bone
topaz rune
#

still
Traceback (most recent call last):
File "/srv/barman/main.py", line 491, in <module>
type=discord.OptionType.STRING,
AttributeError: module 'discord' has no attribute 'OptionType'

patent knoll
#

for type, just type "str"

#

you can also just pass it as second positional argument
i always do Option("name", str, <kwargs>)

topaz rune
# patent knoll you can also just pass it as second positional argument i always do Option("name...

anyway,

@bot.slash_command(
    name="meme",
    description="Commande permettant d'envoyer un meme aléatoire dans le salon prévu à cet effet",
    options=[
        discord.Option(
            name="type",
            description="Type de meme",
            type=str,
            required=False,
            choices=[
                discord.OptionChoice(name="normal", value="normal"),
                discord.OptionChoice(name="noir", value="noir"),
            ],
        )
    ],
)
async def meme(ctx, type=None):
    salon_meme = await bot.fetch_channel(923316086483587088)
    salon_meme_noir = await bot.fetch_channel(923316086483587090)
    salon_console = await bot.fetch_channel(1070805582447136819)
    path_base = "/srv/barman/meme/"
    path_normal = path_base + "normal"
    path_noir = path_base + "dark"

    if ctx.channel == salon_meme or ctx.channel == salon_console:
        if type == "normal":
            doss_name = os.listdir(path_normal)[
                random.randint(0, len(os.listdir(path_normal)) - 1)
            ]
            path_meme = path_normal + "/" + str(doss_name)
            fin_meme = path_meme + "/" + str(random.choice(os.listdir(path_meme)))
            await ctx.channel.send("Ce meme provient de **" + str(doss_name) + "**")
            await ctx.channel.send(file=discord.File(fin_meme))

    elif ctx.channel == salon_meme_noir and type == "noir":
        doss_name = os.listdir(path_noir)[
            random.randint(1, len(os.listdir(path_noir)) - 1)
        ]
        path_meme = path_noir + "/" + str(doss_name)
        fin_meme = path_meme + "/" + str(random.choice(os.listdir(path_meme)))
        await salon_meme_noir.send("Ce meme provient de **" + str(doss_name) + "**")
        await salon_meme_noir.send(file=discord.File(fin_meme))

    else:
        await ctx.send(
            f"Cette commande est réservée aux channels <#{str(salon_meme.id)}> et <#{str(salon_meme_noir.id)}>",
            ephemeral=True,
        )

discord don't even show me the command when I use /

still thanks for the advice

patent knoll
#

then you're most likely doing something wrong lol

topaz rune
patent knoll
#

make sure to restart discord, sometimes it can be slow

#

you dont need to pass a name to the slash command decorator btw, it defaults to the function name anyway

#

does any other slash command you have show

topaz rune
topaz rune
patent knoll
#

i mean i personally use the option decorator

topaz rune
#

thats the only one

patent knoll
#

try not passing the name argument in the slash command decorator
if that still doesnt work, just comment the whole thing out and see if it works with an empty decorator

topaz rune
patent knoll
#

show your code

topaz rune
#
@bot.slash_command(
    name="meme",
    description="Commande permettant d'envoyer un meme aléatoire dans le salon prévu à cet effet",
    options=[
        discord.Option(
            description="Type de meme",
            type=str,
            required=False,
            choices=[
                discord.OptionChoice(name="normal", value="normal"),
                discord.OptionChoice(name="noir", value="noir"),
            ],
        )
    ],
)
patent knoll
topaz rune
#

I removed the name from options[]

#

oh

#

didnt saw it

patent knoll
#

and no, i mean THIS name

topaz rune
patent knoll
#

options always need a name

topaz rune
#

I tried like this:

doesnt work 😩

patent knoll
#

are you actually saving and restarting your bot

topaz rune
#

I am

patent knoll
#

restarted discord, too?

topaz rune
#

ctrl r

patent knoll
#

hm
well sometimes it can take a minute or two for it to actually register but that should work how you have it there

young bone
topaz rune
#

well, I just don't get it

patent knoll
young bone
patent knoll
#

i would've removed it in the function declaration, no?

topaz rune
patent knoll
#

i know its kinda duplicate but i cba to change it and it works

topaz rune
#

do you guys know this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options

patent knoll
#

well, just what it says

#

you put an option that not required before one that is

topaz rune
patent knoll
#

screenshot the code that caused that :3

topaz rune
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/debian/.local/lib/python3.9/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "/home/debian/.local/lib/python3.9/site-packages/discord/bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "/home/debian/.local/lib/python3.9/site-packages/discord/bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/http.py", line 371, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options```
patent knoll
#

well what code did you add before that happened

topaz rune
#

imma do ctrl z

patent knoll
#

wdym you dont know lol
you added some lines of code before that happened
which ones

topaz rune
#

yk what, just forget it, imma stay with normal commands, im too stupid for coding / commands

patent knoll
topaz rune
#

yeah sorry

patent knoll
#

slash commands are a lot easier than prefix commands imo

topaz rune
patent knoll
#

plus you do have a working one so you're doing something different with the one that doesnt work
just copy your working one, change the function name and see if it shows up

patent knoll
young bone
#

I also like that you can add descriptions and other stuff

topaz rune
#

any idea of this?

patent knoll
#

from discord import option

topaz rune
topaz rune
# patent knoll from discord import option

do you see an error there:

@slash_command(brief="Renvoie un meme")
@option("choix" bool, description="Renvoie un meme aléatoire", required=False, choices=["aléatoire","choisi"])

#

get it

#

forgot a ,

patent knoll
#

yea

topaz rune
#

unfortunately...

#
@slash_command(name="ratio", description="Commande permettant de 'ratio' un utilisateur")
@option("user", description="L'utilisateur Ă  ratio", required=False, type=discord.Member)
@option("raison", description="La raison du ratio", required=False)
async def ratio(ctx, user: discord.Member = None, raison: str = ""):
    """
    Commande permettant de "ratio" un user
    discord.Member : user -> utilisateur Ă  ratio
    str : raison -> raison du ratio
    """
    await ctx.defer()
    if user is None:
        mention = ctx.author.mention
    else:
        mention = user.mention

    await ctx.send(f"EH {mention}! **RATIO**! {raison}")

or

@slash_command(brief="Renvoie un meme")
@option("choix", bool, description="Renvoie un meme aléatoire", required=False, choices=["aléatoire","choisi"])
async def meme(ctx, choix = "aléatoire"):
    """
    Commande permettant d'envoyer un meme aléatoire dans le salon prévu à cet effet
    str : arg -> optionnel, l'argument pour sélectionner le type de meme aléatoire
    """
    salon_meme = await bot.fetch_channel(923316086483587088)
    salon_meme_noir = await bot.fetch_channel(923316086483587090)
    path_base = "/srv/barman/meme/"
    path_normal = path_base + "normal"
    path_noir = path_base + "dark"

    if ctx.channel == salon_meme or ctx.channel == salon_meme_noir:
        if choix == "aléatoire":
            # Créez le menu déroulant pour choisir le type de meme
            view = discord.ui.View()
            if ctx.channel == salon_meme:
                view.add_item(MemeTypeSelect("normal"))
            else:
                view.add_item(MemeTypeSelect("noir"))
            await ctx.send("Choisis le type de meme :", view=view)
        else:
            if ctx.channel == salon_meme:
                doss_name = os.listdir(path_normal)[random.randint(0,len(os.listdir(path_normal))-1)]
                path_meme = path_normal + "/" +str(doss_name)
                fin_meme = path_meme + "/" + str(random.choice( os.listdir(path_meme)))
                await ctx.channel.send("Ce meme provient de **" + str(doss_name) + "**")
                await ctx.channel.send(file=discord.File(fin_meme))
            else:
                doss_name = os.listdir(path_noir)[random.randint(1,len(os.listdir(path_noir))-1)]
                path_meme = path_noir + "/" + str(doss_name)
                fin_meme = path_meme + "/" + str(random.choice( os.listdir(path_meme)))
                await salon_meme_noir.send("Ce meme provient de **" + str(doss_name) + "**")
                await salon_meme_noir.send(file=discord.File(fin_meme))
    else:
        await ctx.respond(f"Cette commande est réservée aux channels <#{str(salon_meme.id)}> et <#{str(salon_meme_noir.id)}>")

#

all of theese doesnt work

#

even with /

#

do I need to aproove smth on the discord dev website orrr??

#

idk, sadge

simple steppe
#

Where to use persistent in Paginator code?

cyan quail
#

and they should be defined before doing bot.run

#

and i hope you didn't override on_connect

solemn idol
#

why does this not work?

#

previous_button is a button using discord.ui etc. the button itself works fine... but it doesnt directly get activated when executing this part.

#

*disabled doesn't work

#

I made it disabled = False

silver moat
silver moat
solemn idol
#

wait how exactly do you mean, under self.previous_button.enabled = True I edit it again?

solemn idol
#

how would I specify what message it edits tho

#

in the button itself I use

#

shi wrong clipboard

#

await interaction.response.edit_message(embed=definition, view=self) meant this

silver moat
#

there's only a button.disabled, not a button.enabled

solemn idol
silver moat
#

show full code maybe?

#

and also I don't think a button object is attached to the view

solemn idol
#
def update_buttons(self):
        print(f'Current page {self.page}')
        if self.page < 1:
            print('Previous button disabled :', self.page)
            self.previous_button.disabled = True
        elif self.page >= 1:
            print('Previous button enabled :', self.page)
            self.previous_button.disabled = False
        self.sort_button.label = 'Sort by Upvotes' if not self.sort_by_upvotes else 'Sort by Date'
        print(len(self.data['list']))
        if self.page < len(self.data['list']):
            self.next_button.disabled = False
        else:
            self.next_button.disabled = True
#

It's not perfect yet, I need change some more values dont those but how exactly do I edit it?

young bone
#

you dont use async def?

silver moat
young bone
#

ok

solemn idol
#

but well how would I edit the specified message?

silver moat
#

edit what specified message

solemn idol
#

I mean the button itself edits the message using await interaction.response.edit_message(embed=definition, view=self)
when pressed

#

but how would I edit the message in the update_buttons function?

silver moat
#

pass interactions or the corotine into update_buttons?

solemn idol
#

just put self.update_buttons() above await interaction.response.edit_message in the button itself 🧠

topaz rune
cyan quail
cyan quail
#

same for the 2nd command, just replace send with respond

topaz rune
#
owner_ids = set(owners)

will @commands.is_owner() still work?

#

with / commands

full basin
#

Yes

topaz rune
#

ty

simple steppe
#

can u help me with if_persistent() parametr with paginator
like where should i use it in example code

    @commands.command()
    async def pagetest_prefix(self, ctx: commands.Context):
        """Demonstrates using the paginator with a prefix-based command."""
        paginator = pages.Paginator(pages=self.get_pages(), use_default_buttons=False)
        paginator.add_button(
            pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.green)
        )
        paginator.add_button(
            pages.PaginatorButton(
                "page_indicator", style=discord.ButtonStyle.gray, disabled=True
            )
        )
        paginator.add_button(
            pages.PaginatorButton("next", style=discord.ButtonStyle.green)
        )
        await paginator.send(ctx)```

or in this but  i rather wanted to use prefix command
```py
@pagetest.command(name="custom_view")
  async def pagetest_custom_view(self, ctx: discord.ApplicationContext):
    """Demonstrates passing a custom view to the paginator."""
    view = discord.ui.View(
      discord.ui.Button(label="Test Button, Does Nothing", row=1), )
    view.add_item(
      discord.ui.Select(
        placeholder="Test Select Menu, Does Nothing",
        options=[
          discord.SelectOption(
            label="Example Option",
            value="Example Value",
            description="This menu does nothing!",
          )
        ],
      ))
    paginator = pages.Paginator(pages=self.get_pages(), custom_view=view)
    await paginator.respond(ctx.interaction, ephemeral=False)```
proud mason
#

ngl i dont think it is possible to cleanly make the paginator persistent

#

unless you have static pages

simple steppe
#

yes content of embeds is static

proud mason
#

oh then you might actually be able to do it

simple steppe
#

like i wanted to use command .roles which will show all the available roles on the server and have buttons to navigate between pages (a lot of roles)

proud mason
#

you will need to make all the components have a custom id, i think you got that covered
you will then need to build the paginator on startup. probably on ready (on ready is not the best way)

since the paginator is actually a view subclass, you can just do bot.add_view(paginator)

proud mason
#

thats not really static yk

#

cuz it needs the roles

#

what you can do is

simple steppe
#

only role names, not pings, and i wont add new roles or if so i will execute command once again

proud mason
#

is this a private bot?

simple steppe
#

yeah

proud mason
#

can you hardcode the guild id?

#

then you can just get guild using bot.get_guild(d), get the roles and build the paginator on ready

simple steppe
#

can we go dm?

proud mason
#

hmm. sure

topaz rune
#

Hi, @option doesn't work with cogs?

fossil mulch
#

sup guys

#

maybe a stoopid question, but can i reference an looped function as a normal function?

young bone
fossil mulch
woeful yew
#

What's the difference between Discord.py and Pycord?

proud mason
woeful yew
proud mason
#

in dpy you use a tree and stuff

#

in pycord, it is more like how prefix cmds are added

woeful yew
#

Humm thanks

#

Is it possible to place buttons in Pycord?

proud mason
#

yes

#

i suggest checking out the guide

#

.guide

winter condorBOT
woeful yew
#

Ohh, thanks. Looks better the dpy's guide

pallid token
#

Hey there. Just wondering how I can access the description of my application commands, given an ApplicationCommand object.

pallid token
#

Not setting the description. Accessing it from an existing ApplicationCommand object.

#

I know its an attribute of SlashCommand, but that's not as accessible to me. Would it be in __original_kwargs__?

proud mason
pallid token
#

I believe it's accessible via a SlashCommand object (which inherits from ApplicationCommand) and its handled by them, but the ApplicationCommand object doesn't have a description attribute.

#

I mean, if there's a way to get a list of the SlashCommand objects from the Bot class like there is for ApplicationCommand objects, that would make it a lot easier. Just haven't seen that.

proud mason
pallid token
#

bot.application_commands claims to return a list of ApplicationCommand objects. Unless that is wrong and it instead also returns SlashCommand objects rather than objects of their super class (ApplicationCommand), then đŸ€·â€â™‚ïž
Give me a sec to try something :)

proud mason
#

pretty sure that is just a typing thing

pallid token
#

Yeah... I think I might be able to isolate out just the SlashCommand objects if it contains them. Working on something. Thanks btw 😄 ❀

#

Yep. Can just run an isinstance() check. It contains the SlashCommand objects 🙂

proud mason
#

nice

solemn idol
#

how can I make it still defer at the beginning but then respond with an ephemeral if needed?
because defer basically always overrides the ephemeral of the ctx.respond for a slash command?

#

ping me if you respond :P

drowsy fractal
#

How do you add reactions to a response in a slash command?

cyan quail
#

the first followup has to be one or the other, i.e. what you're trying to do at the bottom there won't work

solemn idol
cyan quail
#

After that you can freely switch

solemn idol
#

yes but the below responses are basically both my first response

cyan quail
#

The only way around this would be to have another response beforehand

solemn idol
#

or typing instead of thinking?

cyan quail
#

You'd still have to have a first response though

#

I guess triggering typing after that if you want could work

solemn idol
#

I'll try it tomorrow and tell you if it worked, thanks for your help though:)

radiant harbor
#

I need to draw messages from different data collections using the "slot_number" option. I tried a if statement but I didn't get a response from it. Does anyone have a suggestion on how I can do it?

silver moat
#

we have no idea what your data looks like

solemn idol
#

I've encountered some rate limiting, after having made a /urban command using embeds and buttons, but I cannot find the cause, I start my bot and it gets rate limited but there's literally not a single timer in there so uh- ?

#

Ideas?

silver moat
#

is it your host?

solemn idol
# silver moat is it your host?

Wdym exactly? If I run my bot it gets rate limited. I have the logging feature on where it dumps info into s log file etc.

radiant harbor
solemn idol
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: Must be 1024 or fewer in length.

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

Traceback (most recent call last):
  File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/vox/sparky/./main.py", line 227, in on_application_command_error
    raise error
  File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: Must be 1024 or fewer in length.```
silver moat
solemn idol
solemn idol
#

Linux server

#

Fk wrong clipboard

#
2023-05-10 21:40:55,968:WARNING:discord.client: PyNaCl is not installed, voice will NOT be supported
2023-05-10 21:40:56,714:INFO:discord.client: logging in using static token
2023-05-10 21:40:57,072:INFO:discord.gateway: Shard ID None has sent the IDENTIFY payload.
2023-05-10 21:40:57,324:INFO:discord.gateway: Shard ID None has connected to Gateway: ["gateway-prd-us-east1-c-4m58",{">2023-05-10 21:40:59,341:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:41:59,348:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:42:59,356:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:43:59,364:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:44:59,372:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:45:59,380:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:46:59,388:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:47:59,396:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds```
silver moat
#

"check before you send" - probably some old white guy

silver moat
#

or does it just take a while

solemn idol
#

I've had it running for like 3hrs and only found out ab it now... I hope discord not blacklisting my server blobpain

solemn idol
silver moat
#

does it just take a while for on_ready to fire?

solemn idol
#

a little yes

#

The rstelimit was going for 3hrs tho so

#

so idk im quite clueless at this point

#

I shutdown my bot for now

#

But hm-

silver moat
#

if you restart your bot does it work?

solemn idol
#

I restarted it and it got rate limited again

#

I am unable to access direct code right now maybe tomorrow but as of now it's just a huge pain in the ass

#

Log says : Error
Me : Can't find Error

#

đŸ„č

silver moat
#

Do you have anything blocking?

solemn idol
#

Wdym blocking

silver moat
#

?tag blocking

obtuse juncoBOT
#

dynoError No tag blocking found.

silver moat
#

?tags block

obtuse juncoBOT
#
Tags (1)

codeblock

silver moat
#

anything that isn't async and takes a long time to execute (e.g. time.sleep)

solemn idol
#

hmmm

#

ver maybe

#

I'll try to kook at that

drowsy fractal
#

I'm trying to put slash commands in cogs and its all working but when I try to add options they don't work, so any optional parameters dont appear as optional and stuff. Here is the code I'm trying, which is in my cog in an extension file:

    @commands.slash_command(name="ntest", description="test command")
    @option(name="testparam", description="test parameter")
    async def ntest(self, ctx: discord.ApplicationContext, testparam: str):
        await ctx.respond(testparam)

is there anything obvious that I'm missing? I've been looking for a while and havent found anything

silver moat
#

options are not optional by default

#

You can add the required = False kwarg in the option decorator

drowsy fractal
#

even when I do that, it still claims its required

silver moat
#

Try the following:

  • Comment out the command, run the bot, uncomment, and rerun
  • Restart your Discord app
halcyon gorge
#

Any idea on how to make a task execute at a certain time in local timezone? I've tried

pdt = pytz.timezone('America/Los_Angeles')
pdt_datetime_tz = datetime.timezone(pdt._utcoffset)
times = [
    datetime.time(hour=16, tzinfo=pdt_datetime_tz),
    datetime.time(hour=16, minute=57, tzinfo=pdt_datetime_tz),
    datetime.time(hour=11, minute=23, second=30, tzinfo=pdt_datetime_tz)
]
   @tasks.loop(time=times)
    async def reminders(self):
      print("working")
#

doesn't seem to execute unless the datetime.timezone is in UTC even though I converted it to pdt

full basin
#

cant u just calculate the difference between utc and your timezone and then just set the hours in utc?

halcyon gorge
cyan quail
halcyon gorge
#

Thanks

cyan quail
#

allgood

#

i think pacific is -7 right now? might as well go with that

halcyon gorge
#

yea

#

I just converted Pacific to UTC and just put the UTC time in the parameter for now

cyan quail
#

theoretically you'd only have to change for DST a single time and then never again if that bill fully passes

halcyon gorge
#

hopefully

candid coral
#

How can I turn off adding a bot by a button in his profile? Help me, please

queen solstice
#

how do i create a guild specific command?

proud mason
queen solstice
#

yea

#

guild slash command

proud mason
#

pass guild_ids=[...] in the decorator

queen solstice
#

ok ty for helping

proud mason
#

np

#

(guild ids should be an int btw)

queen solstice
#

also why do i get this error in ctx.message.author.id?

NoneType has no attribute author

silver moat
#

is this in an application command (slash command, user/message command) or a text-based command?

proud mason
queen solstice
#

ohk

#

ty

solemn idol
#

@silver moat I fixed it... I found out that I had a task looping indefinite with a WhileTrue loop which constantly was trying to await something without making any change sooo.... ehheh.

simple steppe
#

is there a way to include view=MyView() inside paginator send?
When i want to do it like this

await paginator.send(ctx, view=MyView())```
error paginator.send got and unexpected keyword argument view
proud mason
#

Or do you want to replace the default buttons?

topaz rune
#

Hi, does someone have an idea of why can't I use / commands with my bot? like even if my code is right, it doesn't show when I press /

full basin
#

.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.

alpine kernel
#

If I have a data stream, what would be the best way to dispatch a command/function to handle new data in that datastream? just a task that runs every second?

#

ooo maybe listen decorator

topaz rune
cyan quail
topaz rune
#

but now I have a problem where I show the code 🙂

@commands.is_owner()
    @commands.slash_command(name="mute", description="Permet de mute un utilisateur")
    @option("user", "L'utilisateur que l'on souhaite mute",  required=True)
    @option("reason", "La raison du mute", required=False)
    async def mute(self,ctx, user, reason = 'L\'admin n\'a pas donné de raison'):
        """
        Commande permettant de mute un user
        discord.ApplicationContext : ctx -> Discord application command interaction
        discord.Mention : user -> L'utilisateur que l'on souhaite mute
        string : reason -> La raison du mute
        """
        member_role = discord.utils.get(ctx.guild.roles, name='「 🌾┆MÎŁMBÎŁR 」') # Je rĂ©cupĂšre le role Member
        mute_role = discord.utils.get(ctx.guild.roles, name='「 🔇┆Muet 」') # Je rĂ©cupĂšre le role Member
        mute_dico[user.id] = reason # J'ajoute la raison du mute dans un dico des personnnes mutes
        if mute_role in user.roles:
            # Si l'utilisateur est déjà mute
            reason = mute_dico[user.id] # Je prend la raison dans liste des mutes
            embed = discord.Embed(title='Membre déja mute',description='Ce membre est déja mute !')
            embed.add_field(name='Reason :',value=reason)
            await ctx.respond(embed=embed,delete_after=5.0)
        else:
            # Sion alors il faut mute l'utilisateur
            mention=user.mention # Je crée une mention
            mute_dico[user.id] = reason # J'ajoute la raison au dico des utilisateurs mute
            await user.add_roles(mute_role) # J'ajoute Ă  l'utilisateur le role muet
            await user.remove_roles(member_role) # Je supprime Ă  l'utilisateur le role member
            embed = discord.Embed(title='Membre mute',description='Un membre a été mute sur le discord !')
            embed.add_field(name='Il sagit de:',value=str(mention).format(mention=mention))
            embed.add_field(name='Reason :',value=reason)
            await ctx.respond(embed=embed)

Error:

Traceback (most recent call last):
  File "/srv/barman/main.py", line 22, in <module>
    import moderation
  File "/srv/barman/moderation.py", line 22, in <module>
    class moderation_class(commands.Cog):
  File "/srv/barman/moderation.py", line 256, in moderation_class
    async def mute(self,ctx, user, reason = 'L\'admin n\'a pas donné de raison'):
  File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 406, in decorator
    func.__annotations__[name] = Option(type, **kwargs)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 225, in __init__
    self.input_type = SlashCommandOptionType.from_datatype(input_type)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/enums.py", line 786, in from_datatype
    if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'

Does someone could explain what am I doing wrong here please

alpine kernel
cyan quail
# alpine kernel ah that's even better thanks

basically if you define a listener such as py @Cog.listener() async def on_some_data(self, arg1, arg2)in any cog on your bot, and your stream has access to bot, you can call it via dispatch py bot.dispatch("some_data", arg1, arg2)

alpine kernel
#

cool ty

topaz rune
cyan quail
#

e.g. user would change to user: str

#

same for reason

topaz rune
cyan quail
#

yeah that works

topaz rune
#

ok imma try

#

ty

#
Traceback (most recent call last):
  File "/srv/barman/main.py", line 22, in <module>
    import moderation
  File "/srv/barman/moderation.py", line 22, in <module>
    class moderation_class(commands.Cog):
  File "/srv/barman/moderation.py", line 256, in moderation_class
    async def mute(self,ctx, user, reason = 'L\'admin n\'a pas donné de raison'):
  File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 406, in decorator
    func.__annotations__[name] = Option(type, **kwargs)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 225, in __init__
    self.input_type = SlashCommandOptionType.from_datatype(input_type)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/enums.py", line 786, in from_datatype
    if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'
cyan quail
#

did you save

topaz rune
cyan quail
#

doesn't look like it

#

(7th line of that traceback)

topaz rune
# cyan quail doesn't look like it

I sent the wrong one mb:

Traceback (most recent call last):
  File "/srv/barman/main.py", line 22, in <module>
    import moderation
  File "/srv/barman/moderation.py", line 23, in <module>
    class moderation_class(commands.Cog):
  File "/srv/barman/moderation.py", line 257, in moderation_class
    async def mute(self, ctx, user: discord.Member, reason:str ='L\'admin n\'a pas donné de raison'):
  File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 406, in decorator
    func.__annotations__[name] = Option(type, **kwargs)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 225, in __init__
    self.input_type = SlashCommandOptionType.from_datatype(input_type)
  File "/home/debian/.local/lib/python3.9/site-packages/discord/enums.py", line 786, in from_datatype
    if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'
#

maybe that it's coming from this:
@option("user", "L'utilisateur que l'on souhaite mute", required=True)

could it?

cyan quail
#

from what i can tell that's caused this error in the past

topaz rune
# cyan quail did you perhaps import `annotations` from `future`?

nop, but I added this:
@option("user", "L'utilisateur que l'on souhaite mute", required=True, type=discord.Member)

and now it say:

Traceback (most recent call last):
  File "/srv/barman/main.py", line 22, in <module>
    import moderation
  File "/srv/barman/moderation.py", line 23, in <module>
    class moderation_class(commands.Cog):
  File "/srv/barman/moderation.py", line 255, in moderation_class
    @option("user", "L'utilisateur que l'on souhaite mute", required=True, type=discord.Member)
TypeError: option() got multiple values for argument 'type'
#

seems easier

cyan quail
#

well... you're not meant to pass type manually

coarse cargo
#

What should i use for fetch a message? As there is no bot.fetch_message()

coarse cargo
#

ty

cyan quail
topaz rune
#

but imma try

cyan quail
#

GuraShrug the only thing i know that causes it is importing annotations