#Basic Pycord Help (Quick Questions Only)

1 messages · Page 70 of 1

fervent thunder
#

!create_embed is the command

distant roost
#

This is probably an error that happends very often but why did i get the error function bot.load_extension was never awaited? When i change my code from bot.load_extension o await bot.load_extension it says await outside function? That doesn’t really makes sense for me

distant roost
#

Basically if i write bot.load_extension() without await in my code the error is courutine bot.load_extension() was never awaited and if i do it with await it says await outside function.
And sorry for my englisch i really don’t know how courutine is spelled i hope you can understand it

silver moat
fervent thunder
#

?

#

.

young bone
fervent thunder
#

bro im about to shoot myself, stop asking that question.

young bone
#

lol

fervent thunder
#

bro i've been trying to do this for weeks

#

please just help me idk what to do

distant roost
young bone
fervent thunder
young bone
# fervent thunder

you are not responding to the buttons and why do you use "/" as a prefix for prefix commands?

fervent thunder
#

oops

#

meant to be !

fervent thunder
#

how do i make it respond to the buttons

young bone
#

use response?

silver moat
young bone
#

^

fervent thunder
#

bro

#

i'll try

young bone
distant roost
#

What should i deinstall? And i didn’t import any of these i just imported pycord

young bone
distant roost
#

Ok sec

silver moat
#
pip uninstall discord.py discord py-cord -y
pip install py-cord
distant roost
#

It works now thank you both

full basin
#

Can I edit a specific follow up?
Like prompt = await interaction.followup.send()
and then await prompt.edit()
or is my IDE tricking me about it not being possible?

fervent cradle
#

Hello Guys Quick Question how can i put my easy~pil coded picture in a embed like how do i get the url

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

am i right?

fervent cradle
#

where is the image gonna be send in then

#

output or discord

#

ohhhh

#

the path is the place where the picture is located

silver moat
#

good

fervent cradle
#

i tought it is gonna be saved there

#

i made an code easy-pil but how do i make a easy-pil co´de to a picture

rare ice
#

that's not Pycord related.

fervent cradle
#

what

#

oh

#

my bad

full basin
silver moat
#

what is this called (in terms of web dev)?

rare ice
#

Great question tho

full basin
#

It's a meta element

silver moat
silver moat
rare ice
#

Does anyone know if a custom commands handler where you can create custom commands that even supports arguments? Kind of like Carl’s typescript.

sand niche
#

If I have snowflakes of channels I want to delete, can I just do:

channel = discord.abc.GuildChannel(id)
await channel.delete()

?

sand niche
#

dumb question. sorry. I am tired lol.

#

Thanks as always squidy. 😄

proud mason
#

Btw that is dpy. Not py-cord

proud mason
proud mason
proud mason
mental maple
#

Can pycord wait for message?

limber urchin
#

.rtfm wait_for

mental maple
#

Arl tried but it doesnt wait

#

And ran the next line

#

Bot perm is administrator

proud mason
mental maple
#
try:
        amount = await bot.wait_for("message", timeout=20) # 30 seconds to reply
    except asyncio.TimeoutError:
        await ctx.respond("Pertanyaan tidak dijawab, Ulangi!")```
#

that try have indent

#

All intents

proud mason
#

hm

mental maple
#

Which one wrongs

proud mason
#

you didnt use checks

mental maple
#

It do need?

#

Ok

proud mason
#

you bot could be getting messages from any server, any channel, any user

#

i suggest using a check for ctx.author and ctx.channel

#

.rtfm wait_for

mental maple
#

Im makin message command

proud mason
#

that has an example

proud mason
mental maple
#

Ye ikr, thx

proud mason
#

you could use modals yk

mental maple
#

Huh?

#

Wait even i use check it auto run next line again

#

😑

proud mason
#

oof blobpain

mental maple
#

Bruhhhh

proud mason
#

what check did you use?

#

also, try printing amount

#

see what you get

mental maple
#

Just an easy check that return message content

#

BRUHHH it do read

#

It read the bot message

#

:l

#

It read itself like bruh

limber urchin
#

That's why you need a check

mental maple
#

Oh okie, so i need to check its a bot or nah

#

Many things changed.

limber urchin
#

That depends on what conditions you want to wait for. You might also need to check if it's the right channel, if it's the right member sending the message, if it's in the right server.

mental maple
#

Uh how to check?

#

if message.author == ctx.author?

limber urchin
#

.tias

winter condorBOT
mental maple
#

Yep

mental maple
#

How to use 💰 in embed footer?

#

Tried text="<moneybag>"

limber urchin
#

You can't use Discord emojis in the footer. It has to be a unicode character

proud mason
#

you can get the unicode emoji version if you put a \ before emoji and send it

#

copy paste that

#

eg send \💰 to get \💰

#

\💰

#

will work

magic pendant
#

I can't send a keyboard interrupt to stop the bot process. Is this a new thing with pycord?

proud mason
#

change that to except Exception:

#

Because a bare except: will suppress a KeyboardInterrupt

#

but KeyboardInterrupt is not a subclass of the base Exception class

proud mason
magic pendant
#

Nope i don't, but I think I've discovered the function that's causing it. This below:

# main.py

bot.loop.create_task(DatabaseAdapter().ainit())
    async def ainit(self):
        self.reports_conn = await aiosqlite.connect(self.reports_db)
        async with self.reports_conn.execute("SELECT id FROM report") as cur:
            self._all_records_ids = await cur.fetchall()

        self.infractions_conn = await aiosqlite.connect(self.infractions_db)```
#

I don't see a reason why that would suppress keyboard interrupt though

proud mason
#

hmm yea i dont see it either

#

try adding a print statement to see till where the code is being run. or use a debugger

magic pendant
#
Exception handler is loaded
Help.cog is loaded
Infractions.cog is loaded
IO.cog is loaded
Reports.cog is loaded
Setting up DB connections.
DB connections set.

+-------------------------+
| Prototype is on standby |
+-------------------------+```
#
    async def ainit(self):
        print("Setting up DB connections.")
        self.reports_conn = await aiosqlite.connect(self.reports_db)
        async with self.reports_conn.execute("SELECT id FROM report") as cur:
            self._all_records_ids = await cur.fetchall()

        self.infractions_conn = await aiosqlite.connect(self.infractions_db)
        print("DB connections set.")```
#

function definitely finishes executing

proud mason
#

hmm

#

and how do you run the bot? bot.run() ?

magic pendant
#

load_dotenv()
TOKEN = getenv("TOKEN")
bot.run(TOKEN)
magic pendant
#

Oh I see

#
Database setup <Connection(Thread-2, started 20580)> and <Connection(Thread-3, started 14204)> []```
#

the connections are in different threads for some reason

#

is there a function I could implement that gets invoked before the bot shuts down? (think I need to .close() the connections)

#

Also isn't aiosqlite supposed to be single threaded?

proud mason
#

you would need to subclass bot

#

and override the init

#

so smth like this

async def close(self):
    # stuff
    await super().close()
proud mason
magic pendant
proud mason
#

yes

proud mason
magic pendant
#

    async def ainit(self, bot):
        if self.reports_conn is None:
            self.reports_conn = await aiosqlite.connect(self.reports_db, loop=bot.loop)
        async with self.reports_conn.execute("SELECT id FROM report") as cur:
            self._all_records_ids = await cur.fetchall()

        if self.infractions_conn is None:
            self.infractions_conn = await aiosqlite.connect(self.infractions_db, loop=bot.loop)
        print(f"Database setup {self.reports_conn} and {self.infractions_conn}.")```
#

set it to this ^

#

still seems to be threaded 😮‍💨

#

Is it possible to set an ApplicationCommand visibility to only owner?

young bone
#

You could do Administrator but that would be kinda for the Owner of the Server

#

And you didn't say for which Owner

magic pendant
#

Ohh

#

My bad, i meant the bot owner (this is a restart command)

proud mason
magic pendant
#

I've never had this problem previously with aiosqlite

#

which is very peculiar

worldly schooner
#

add reaction problem:

Yes the bot have the perms to react
Andreas got reacted perfectly fine
Luc was supposed to get the same reaction but it prompted this error instead

Any clues as to what could be causing this?

young bone
worldly schooner
#

oh wait

worldly schooner
young bone
#

does the bot has the permissions to add emojis?

worldly schooner
#

it got admin perms

#

ok apparently he blocked the bot, so thats why it prompted this reaction blocked

magic pendant
young bone
magic pendant
ornate current
#

i have stored

"hello" : "🪙"

in a json and it return weird characters when i access them.
it returns - 🪙

magic pendant
worldly schooner
#

is there a guide to export a log file from the bot upon a command?

#

like I want the bot to send the file logs.log after the command ~~log

young bone
#

and how

magic pendant
#

alright, thanks eitherways 👍

#

Is there a component just to display large text (not input) for modals?

round rivet
#

nope

round rivet
sand niche
#

So... I just ran into a weird issue. I am getting an exception for an unknown interaction when sending a reply, but the line it tags does reply...

#

python error messages make no sense.

sand niche
#
if guild is not None:
  await interaction.response.send_message(content="This guild has already been registered.", ephemeral=True)
  return
```The code.
young bone
#

do you use that in a button/menu/modal or slash command?

sand niche
#

thats literally the first line in a slash_command. dont think its relevant.

#

also the guild var isnt a discord.Guild. its a model.

#

but it always returns none or a model

young bone
sand niche
#

thats the only other line there is.

#

pycord

young bone
#

ok

#

pls use ctx.respond for slash commands

errant craneBOT
#

Here's the slash basic example.

sand niche
#

wow. thats why. thank you! 🙂

#

Right, and uh, the example doesn't show it, but does the slash decorator also allow you to specify permissions for the command or descriptions for the autocomplete?

young bone
distant roost
#

Does someone know how i can use these timestamps fpor my bot? (i mean these: <t:8639998955999:R>)

sand niche
sand niche
young bone
sand niche
errant craneBOT
#

Here's the slash perms example.

sand niche
sand niche
#

Look, you are being awfully rude about this. Stop telling me to rtfm when the manual is clearly lacking. I'm asking for a pretty basic thing: Do I need to just check for a role in the command itself, or can I can use the decorator to simplify things?

First, you linked me to pycord guide. Which did not have the answer I asked for. Then you told me "oh, its like the (legacy) prefixed commands. Okay, so I check that page on pycord guide. Nope. Then, instead of replying that it was an example only on github for some reason, you use a bot command which still didnt answer me.

I'm not stupid. Stop treating me like it in a help channel.

#

It is no big deal if I have to check. I just wanted to know if there was a better way that wasnt clearly documented. :/

young bone
#

for prefix commands it would be commands.has_permissions and for slash commands discord.default_permissions what would hide the slash command from users

#

but Im not sure if you still can see them and if they are 100% working like the commands.has_permissions one

sand niche
#

right but thats only default permissions it appears. I'm trying to check for a custom role. So like, restricting access by roleid.

young bone
#

for that you could do "if else" or has_role

sand niche
#

again, I know how to check in function. point was if there was a shortcut in the decorator similar to permissions, description, name, etc.

#

clearly there isnt. so nevermind.

young bone
#

at the slash command one?

#

I think I am also a little confused x3

#

I have way to much open at the same time

mossy holly
#

Hi guys, is it possible to edit a message (via interaction.response.edit_message from a slash command) so it contains a Paginator ? I do with Paginator.respond for now but it sends another message, I would like it to be edited in the original response

Thanks 😄

obtuse cairn
#

I'm current trying to move a role (custom_role) until it's above another role (bottom_divider) with this code:

while custom_role <= bottom_divider:
    print(True, custom_role.position)
    await custom_role.edit(position=custom_role.position+1)

This is the output:

True 1
True 1
True 1
...

Why is this happening and how can I fix it?

#

Or, are there any ways of consistently setting a role's position to be right above another role?
await custom_role.edit(position=bottom_divider.position) does not work consistently: the role is sometimes placed a few roles below bottom_divider

mossy holly
obtuse cairn
#

Nope, my bot's highest role is above both roles

mossy holly
#

hmm sorry in that case i can't help :/ (never used this ^^)

obtuse cairn
#

alr, appreciate your help anyways

mossy holly
obtuse cairn
#

from the documentation

mossy holly
#

yeah just saw while looking so nvm u are right

solemn idol
winter condorBOT
proud mason
#

the paginator isnt implemented the best way it should have been

#

||whatever happened to @rare ice improving it 💀 ||

mossy holly
#

Ok ok thanks, that’s what I thought, it’s not considered a view so we can’t just pass it into edit_message, I’ll just delete the old response then (it’ll be a little ugly since it’ll respond to a deleted message but meh it’ll do)

proud mason
#

paginator is actually a subclass of discord.ui.View

mossy holly
proud mason
#

oh fuck wait

#

.rtfm paginator.edit

winter condorBOT
proud mason
#

💀

#

that exists

mossy holly
#

Wtf wait a sec lmao

proud mason
#

so sorry lol

mossy holly
#

Nah it’s me lmao I didn’t look in depth at the documentation (I used vscode with autocompletion and the description of the methods so I must’ve missed the edit)

#

Thanks a lot then ^^

proud mason
#

haha

#

Although this doesnt use interaction.response.edit_message

so you will have to defer and then use the edit method

mossy holly
#

Nice thanks 😃

merry dune
#

@proud mason i think u can help me now, sorry for ping

I remembered that if suddenly the host is somewhat unstable and I need to somehow connect to the message with the button so as not to restart the button cmd

merry dune
#

@strange beacon sorry but i haven't time and really i need help with code blobpain

#

My code

errant craneBOT
#

Here's the persistent example.

merry dune
#

TY ❤️

mossy holly
proud mason
mossy holly
#

but I'll just delete the old and send a new

novel jay
#

Do you access reactions via await msg.reactions[0].users().flatten() or something? Since when i do that it says list index out of range
Snippet of code im using (not full):

channel = ctx.guild.get_channel(12345) #this isn't the problem
msg = await channel.send(f"{giveawayrole.mention}", embed=embed) #nor this, this works
await msg.add_reaction("🎉")
await ctx.respond ("Giveaway created!", ephemeral=True) #I do defer before this
await asyncio.sleep(time*86400) #Time is chosen by user in the inputs
users = await msg.reactions[0].users().flatten() #This is where the error happens
```Nobody else can add reactions in my case
#

There are reactions on the message when the error happens

#

nvm i figured out a way to do it

cerulean halo
#

So the command worked successfully but afterwards it showed that message any fixes?
Except await ctx.defer() -> cause then the bot is thinking...

young bone
cerulean halo
#

I send smth

#

Do you want the code?

young bone
#

do you use ctx.respond?

cerulean halo
#

No,ctx.send

young bone
#

you have to use ctx.respond

cerulean halo
#

Can you explain why?

silver moat
young bone
#

you have to respond to interactions

silver moat
#

Slash Commands are a type of interaction.

cerulean halo
#

Ok seems fair.

#

Ty

silver moat
#

What ctx.send does is send a message in the channel, not related at all to responding to the interaction.

cerulean halo
#

Yeah, I realized that was very retardedto ask ty guys

sand niche
#

Say I want to resolve a snowflake to a channel and then delete it, what would that look like?

I tried:

channel = discord.abc.Snowflake(id)
await channel.delete()
``` but I get protocols cannot be instantiated.
I see that there is a class for discord.abc.GuildChannel, but when I use that I see constructor takes no arguments.
silver moat
#

Actually nvm. I think you actually need the channel object itself

sand niche
#

okay, so I just need to make two calls? one to grab and one to delete?

sand niche
#

I need to do something similar for roles. wasnt sure if there was a way to save on calls though.

since I am doing it in batch, assume fetch_roles then grabbing what I need is better than two calls per role. I dont remember if roles had a plural equivalent. I need to look

#

ah, it does. good.

#

too bad there isnt a batch delete.

solemn idol
#

okay so uhm;

icon_url=ctx.guild.icon.url

I basically have that in my embed footer but I realised that this does not work for servers without a set icon... how do I fix this?

#

ctx.guild.icon returns NoneType when the guild has no server icon set bigbrain

#

nvm just put an if statement which only shows the footer text without an icon if the ctx.guild.icon == NoneType

rare ice
#

How can I get a dictionary object of a discord.Message’s data?

sand niche
#

I feel like I am probably using defer wrong:

await ctx.defer()

seems to hang. Do I actually have to specify ephemeral and invisible or something?

full basin
#

What

#

Seems to hang? Wdym by that?

sand niche
#

as in, infinite loop. nothing else in the function or any other executes.

sand niche
# full basin Show your code

Sure. Sorry for the delay. had to step away for a bit.

async def configure(self, ctx: discord.ApplicationContext):
    await ctx.defer(ephemeral=True)
    #...code

If I change this to ctx.respond(content) and just use edit_original_message later, it works with no issues.

proud mason
proud mason
#

See what you get

fast badger
#

is there any way to get a message just from it's id?

silver moat
fast badger
#

ah ok thanks

jaunty jewel
#

how this bot have no online status ?:>

#

i mean if this is websocket playing that will be so epic

sand niche
silver moat
jaunty jewel
silver moat
#

This has nothing to do with activity/status.

jaunty jewel
#

how they did that angy

limber urchin
obtuse cairn
#

When I use any of the following two lines to move a newly created custom_role right below the top_divider role:

await custom_role.edit(position=top_divider.position-1)
await guild.edit_role_positions(positions={custom_role: top_divider.position-1})

The custom_role is always moved a few roles below the top_divider, and not directly below it. Why is this happening and how can I fix it?

sand niche
#

yeah something weird is going on. I am getting outputs now, but something inexplicably broken

proud mason
silver moat
proud mason
sand niche
#

okay, so I have an update. it seems to be hanging when creating the roles. if I disable the create role line it works. tf

#
for key, role_template in role_templates.items():
  print(role_template['name'], type(role_template['hoist']))
  role = await guild.create_role(name=role_template['name'], hoist=role_template['hoist'])
  print(role)
#

role_templates is just a dict mapped with role names and hoist for now. If I comment out the role creation line, it loops through all entries. If I dont, it goes through one iteration and stops. No exceptions or errors. blobpain

jaunty jewel
#

modals can have dropdowns 🤨

formal galleon
#

Why slash commands may not be updated?

green hinge
#

Does anyone have any ideas on how I can make adding and removing the select menus better or is this already a good way to do it? 🙂

fervent cradle
#

how can I get the members avatar URL as png?

I've tried this:

profile_picture_url = str(member.avatar_url_as(format='png'))

full basin
#

member.avatar.url

#

Member.avatar returns an asset

#

.rtfm asset.url

winter condorBOT
full basin
#

You might be looking for:

#

.rtfm asset.with_format

winter condorBOT
fervent cradle
#

thanks

worldly schooner
#

is it a good practice to put all the imports into separated classes?

ornate current
#
Task exception was never retrieved
Traceback (most recent call last):
  File "D:\DiscordBots\EconomyBot\cogs\economy_commands.py", line 38, in on_timeout
    await self.message.edit(view=None)
          ^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'edit'```
```py
class Pagination(discord.ui.View):

    def __init__(self):
        super().__init__(timeout=5.0)
        self.current_page = 1
        
    async def on_timeout(self):
        await self.message.edit(view=None)```
#

Got into an error

young bone
ornate current
#

nope doesnt work

#
        
    async def on_timeout(self):
        for child in self.children:
            child.disabled = True
        await self.message.edit(view=None)```
young bone
#

what is the py-cord version?

ornate current
#

2.4.1

#

I fixed it

#

It seems that when i edit a message with the view it doesnt register the message

#

bug? prolly?

solemn idol
#

wait did you fix it or just find the issue?

ornate current
#

both ig

proud mason
winter condorBOT
# formal galleon Why slash commands may not be updated?

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

proud mason
#

Different topic but same checklist

proud mason
ornate current
proud mason
ornate current
#

i did something like this

    def __init__(self, msg):
        super().__init__(timeout=5.0)
        self.msg = msg
    async def on_timeout(self):
        await self.msg.edit(view=None)
            view = Pagination(msg=ctx)
            await ctx.edit(embed=embed, view=view)```
#

i guess it works

stark walrus
#
TypeError: Invalid usage of typing.Union```
#

How and why

proud mason
# stark walrus

Not possible with Slash cmds. Input type can be a single type only

#

Discord limitation

stark walrus
#

Why does the example show double types

#

Does discord.VoiceChannel here refer to text channels inside voice channels?

rare ice
proud mason
drifting birch
#

One of my cogs in not loading, but I don't know why. I'm guessing there's an error, but it's not displaying in console. I remember there was a way to show errors in cogs, but can't remember how

limber urchin
#

Do you have a try, except around your load_extension(s)? If you do, remove it and the error will be printed.

worldly schooner
#

I'm running this and doing the command, it simply does nothing

#

yes right below the flavor command it has the bot.run(token)

#

it does nothing

young bone
worldly schooner
#

just say the word and thats it?

young bone
silver moat
worldly schooner
#

oh

#

mb

#

thanks

silver moat
#

If you are looking for text-based commands, you would be looking for commands.Bot

grizzled sentinel
#

Or on_message if you don't want a prefix

#

Not recommended (slow) and discord might not verify if you want to use onymessage tho

silver moat
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
#

Also

#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#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)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

proud mason
#

Don't forget those ^ @worldly schooner

drifting birch
#

I have already identified my problem, but I would like to have errors in the future

worldly schooner
proud mason
#

Also what Py-cord version?

drifting birch
#

To clarify, I do get errors when the cog loads correctly, but something goes wrong during command handling. But I don't get errors when the cog fails to load

worldly schooner
#

Is there a way to have a slash_command visible only for the bot owner?

#

for owner commands as an example

#

or just dont use slash commands, use prefix commands instead right?

proud mason
drifting birch
#

Another problem I have, is autocomplete for options in slash commands don't really work. Only the first 25 options are shown, no matter what the user wrote.

async def test_autocomplete(ctx):
    return [str(x) for 
x in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]]

@discord.slash_command(
        name="test",
        description="test",
    )
    async def test(
        self,
        ctx,
        test: discord.commands.Option(
            str,
            description="Thing you want to test",
            autocomplete=test_autocomplete,
            required=True,
        ),
    ):
        await ctx.respond("test", ephemeral=True)

Am I doing something wrong?

proud mason
drifting birch
worldly schooner
proud mason
proud mason
#

where 12345 is the guild id

worldly schooner
#

tysm!

solemn idol
#

is there any way to do this better?

#

I use it to prevent any formatting in an embed based on user input obtained somewhere

mossy holly
#

~~Hey guys quick question: I use bot.get_user() with an ID to get a user's avatar (using the guild.fetch_member() is too long for some reason it takes 5s for 23 members) but bot.get_user() returns None each time (with both ids of ppl who are in the test server and ids of ppl who aren't), do you have any idea what I might be doing wrong ?

Here's the part of my code that uses it

tmp = self.bot.get_user(id)
print(id, tmp)  # debug
if tmp != None: self.set_thumbnail(url=tmp.display_avatar.url)

The goal is to display the user's avatar on an embed (and my test server uses another server database to try so the members ids are not all on the test server (so guild.fetch_member is not a good idea + it's too long for some reason)~~

nvm found the answer (using bot.get_or_fetch_user())

mossy holly
# solemn idol is there any way to do this better?

Well to avoid copy / pasting I would use a list (+ it's easier to add or remove new char / substrings) but otherwise idk another method to do it

I would do something like that

# Define all unwanted chars / substring here or somewhere else
UNWANTED_SUBSTRINGS = ['*', '_', '~', '`', '|', '>', '[', ']']


def sanitize(text: str) -> str:
    for substring in UNWANTED_SUBSTRINGS:
        text.replace(substring, "")
    return text

But maybe there's a method in pycord to avoid formatting

solemn idol
mossy holly
astral mist
#

how do u make linkedroles

#

is there a example sample/docs page

proud mason
astral mist
#

will that come tho

#

in the future for pycord

proud mason
#

Hmm I'm not sure

astral mist
proud mason
proud mason
proud mason
solemn idol
proud mason
#

regular expressions

#

it is used for pattern matching

#

can be used for simple stuff as well as really complex shit

#

it is a built in python module

#

has a method for substitute

obtuse cairn
proud mason
#

use aiohttp

solemn idol
fervent cradle
#

bot join the voice but plays nothing what is wrong?

    channel = client.get_channel(int(NONE))
    voice = await channel.connect()
    source = FFmpegPCMAudio('NONE.mp3')
    player = voice.play(source)
    await ctx.send("Playing audio")
coarse cargo
#

Hey, there in my bot every time an user create a ticket it gets stored in a .json file with this code.

        ticket_data = {
                   "creator_name": interaction.user.name,
                   "creator_id": interaction.user.id,
                   "create_time": time.strftime('%H:%M:%S')
            }

         with open("data\created.json", "r") as file:
             data = json.load(file)

             data[ticket_channel.id] = ticket_data

         with open("data\created.json", "w") as file2:
              json.dump(data, file2, indent=2)

Anyway i would like to add a filter so an user can't create more than X tickets, so i need to check in this file how many keys creator_id have x value. But i really don't know how i would do it. Anybody could please help me. Thanks

solemn idol
#
UNWANTED_SUBSTRINGS = ['*', '_', '~', '`', '|', '>', '[', ']']

def sanitize(text: str) -> str:
    for substring in UNWANTED_SUBSTRINGS:
        text = text.replace(substring, "") # Here you forgot to put text = ...
    return text
mossy holly
obtuse juncoBOT
#

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

Advantages of using a database:

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

Popular database management systems:

- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
solemn idol
proud mason
errant craneBOT
#

examples/basic_voice.py lines 76 to 79

source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(
    source, after=lambda e: print(f"Player error: {e}") if e else None
)```
green hinge
#

Does anyone have any ideas on how I can make adding and removing the select menus better or is this already a good way to do it? 🙂

fervent cradle
#

I'm trying to install pycord on my server with this command: python3 -m pip install -U py-cord

But it only install pycord 1.7.3 and not 2.4

drifting birch
#

I'm getting this error

Task exception was never retrieved
future: <Task finished name='Task-35' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at /home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/bot.py:853> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>```
But everything works. Is this something that I've done, or is this some issue with the library?
Traceback:

Traceback (most recent call last):
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/bot.py", line 856, in callback
return await command.invoke_autocomplete_callback(ctx)
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1011, in invoke_autocomplete_callback
return await ctx.interaction.response.send_autocomplete_result(
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/interactions.py", line 1017, in send_autocomplete_result
await self._locked_response(
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/interactions.py", line 1090, in locked_response
await coro
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/webhook/async
.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```

young bone
#

that happend the most of the time if the python is not 3.8+

coarse cargo
#

I have a .yml config file where the user should be able to define the color of the button, i already have parsed it but i dont know how to concat it without getting an error

button_color: green
style=discord.ButtonStyle. < What i put here?
full basin
#

Shouldn't it be just .green

#

It's not a method

coarse cargo
# young bone .green

Maybe i didnt explain it very well, i want to get the value of button color in the style of the button. But i dont know how to achieve it, so for example if the user select danger it should change

limber urchin
#

You can't do it like that, that's not how code works. You need to store a dict of the corresponding values to your strings

harsh raft
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/Create.py", line 92, in callback
    await Creation.generate_make_ticket(
  File "/home/container/cogs/Create.py", line 271, in generate_make_ticket
    channel = await guild.create_text_channel(
  File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1355, in create_text_channel
    data = await self._create_channel(
  File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1213, in _create_channel
    payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
AttributeError: 'NoneType' object has no attribute 'id'```

I broke it, halp. ![shrug](https://cdn.discordapp.com/emojis/1089783073299767426.webp?size=128 "shrug")
cyan quail
#

oh no

cyan quail
#

oh wait i see

#

did you pass overwrites to create_text_channel?

harsh raft
#

Yes it's being passed

#
class DropdownServersList(discord.ui.Select):
    def __init__(self,bot,title,check_linked,answered_questions):
         self.bot = bot
         self.title = title
         self.check_linked = check_linked
         self.answered_questions = answered_questions

         super().__init__(options = None , placeholder="Click Here",min_values = 1,max_values=1)

    async def callback(self, interaction: discord.Interaction):
          #Now all the info has been collected eg the questions answered actually make the ticket 
          await Creation.generate_make_ticket(
               self.bot,
               interaction,
               interaction.guild,
               interaction.user,
               self.title,
               self.check_linked,
               self.answered_questions,
               server_name=self.values[0]
          )```
cyan quail
harsh raft
#
          #SetChannelPermissions
          overwrites = {guild.default_role: discord.PermissionOverwrite(view_channel=False,send_messages=False, read_message_history=False)} ```
#
         #PhsyicallyMakeTheChannel
          try:
               channel = await guild.create_text_channel(
                    name=f"{ticket_type_info['ChannelShortname']}-{newticket_num}",
                    overwrites=overwrites,
                    category=category
               )
          except (discord.HTTPException, discord.Forbidden):
               if not autogenerated:
                    return await interaction.response.send_message(content=f"**Error** : We currently have too many of those tickets - please try again shortly",ephemeral=True)
         
         
          if not autogenerated:

               member_id = member.id
               member_name = member.name
          else:
               member_id = None
               member_name = None```
#

I have these two sections

cyan quail
#

it looks like it's None

harsh raft
#

It's set to our Guild ID

#

So yes

cyan quail
#

yeah but what happens when you try to print it, for example

harsh raft
#

I've confirmed that the bot has access to the categories and correct permissions, the category ID's match up and it's intents are on.

cyan quail
#

aight lemme lay it out a bit clearer

#

This is your errorpy File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1213, in _create_channel payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id} AttributeError: 'NoneType' object has no attribute 'id'In this code, only target.id can cause the error. So we first figure out what target is in the function:py for target, perm in overwrites.items():this is looping through each key-value pair in your overwrites dict, which is py {guild.default_role: discord.PermissionOverwrite(view_channel=False,send_messages=False, read_message_history=False)}As such, target is guild.default_role

#

and thus, guild.default_role must be None for some reason when you're creating the channel

#

so how does default_role work? all it does is attempt to return a role matching the guild's ID, the @ everyone rolepy @property def default_role(self) -> Role: """Gets the @everyone role that all members have by default.""" # The @everyone role is *always* given return self.get_role(self.id)If this isn't working, it means your role cache is disabled for some reason

harsh raft
#

Am I able to create a gc with you and the owner to speak about this? 😅

cyan quail
#

uhh you don't really need to, if you want you can open up a forum thread via #969574202413838426 or we can just troubleshoot here idk

harsh raft
#

Inviting owner here

thorn saffron
#

Hey @cyan quail I'm owner of the discord that the bot is running in

cyan quail
#

iseeisee

#

what intents do you have enabled?

thorn saffron
#

all

#

it was working and it randomly stopped

#

it works for our payment support tickets but not our others

cyan quail
#

hmmm it shouldn't really be a category issue...

#

could you try printing

  1. guild.roles
  2. guild.default_role
    and let me know the results
thorn saffron
#

but our linking system is also down (at the same time)
when i try doing the link command to pull their steam64 that's linked to their discord it gives this error

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/main.py", line 47, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'```
#

not sure if it has any connection

cyan quail
#

can you show the code triggering that?

thorn saffron
#

that could troubleshoot the issue further

#
import re
import json
import logging
import discord
import asyncio
from discord.ext import commands,tasks


import logging
logging.basicConfig(level=logging.INFO)

with open("config.json", "r") as f:
    data = json.load(f)
    
client = commands.Bot(command_prefix="+", intents=discord.Intents.all())

with open("config.json", "r") as f:
    client.data = json.load(f)
    client.embed_hex = int(client.data["Hex_Color"].replace("#", "0x"), 16)


@client.event
async def on_ready():
    print(f"\nWe have logged in as {client.user}\n")

@client.event
async def on_message(message: discord.Message):
    if message.author.bot or not message.guild:
        return
    await client.process_commands(message)


@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please pass in all required arguments")
    
    elif isinstance(error , commands.CommandNotFound):
        return

    elif isinstance(error, commands.errors.MissingAnyRole):
        await ctx.channel.purge(limit=1)
        await ctx.send(f"{ctx.author.mention}, You don't have perms for this command ")


    else:
        raise error



extensions = [
  "cogs.AddRoles",
  "cogs.BotStatus",
  "cogs.StaffCommands",
  "cogs.SyncFromMain"
]

async def main():
  if __name__ == "__main__":
    async with client:
        for ext in extensions:
            await client.load_extension(ext)
        await client.start(client.data["BOT_TOKEN"],reconnect=True)
asyncio.run(main())


#

Line 47: else: raise error

cyan quail
#

well that's just the error handler

thorn saffron
#

ofc

cyan quail
#

but the error itself is being caused by the command

#

not quite sure which since that doesn't seem to be the full traceback

thorn saffron
#
ERROR:discord.client:Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/cogs/StaffCommands.py", line 19, in linked
    StaffList = await utilmisc.build_stafflist(self)
  File "/home/container/utils/util.py", line 29, in build_stafflist
    Member_List_From_Roles = Management.members + Operations.members + SAdmin.members + Admin.members + TAdmin.members + SMod.members + Mod.members
AttributeError: 'NoneType' object has no attribute 'members'

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

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/main.py", line 47, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'```
#

could it be the fact we don't have smod.members anymore?

#

the array

#

could be getting confused?

cyan quail
#

so presumably all those variables are roles

thorn saffron
#

correct

cyan quail
#

meaning you either deleted a role or you got the ID wrong

thorn saffron
#
    "CommunityRoleID":1049046310709366857,       
    "Management_role_id": 896145297128955974,
    "Operations_role_id":959002629533499402,
    "SAdmin_role_id": 896145295543533588,
    "Admin_role_id": 895995833382748241,
    "TAdmin_role_id": 899385196313452575,
    "SMod_role_id": 896145522870603816,
    "Mod_role_id": 895995793339715614,```
#

could that be the main issue for this bot?

cyan quail
#

possibly

#

try printing all of those variables (Management, Operations, SAdmin etc.)

#

and see which show up as None

thorn saffron
#

okay I fixed that

cyan quail
#

so back to the original question, does printing guild.default_role show the correct role?

thorn saffron
#

it's not defined anywhere

cyan quail
#

i mean when you have e.g. interaction.guild or ctx.guild in some function

#

what shows when you print interaction.guild.default_role, for example

thorn saffron
#

nothing

cyan quail
#

what if you change it to print interaction.guild.roles

thorn saffron
#

where am i printing this btw?

#

sorry, I'm not a developer he's currently asleep but we have active players trying to make ticket's that's all 👍 so just trying to look for a fix

cyan quail
#

basically any command function or button/dropdown callback that has interaction or ctx in the args

#

might be better to open a separate thread for this

thorn saffron
#

yeah

#

could I not screenshare this for you?

#
          overwrites = {guild.default_role: discord.PermissionOverwrite(view_channel=False,send_messages=False, read_message_history=False)} 
          for role_id in ticket_type_info["RolesInChannel"]:
               overwrites[guild.get_role(role_id)] = discord.PermissionOverwrite(view_channel=True,send_messages=True,read_message_history=True,embed_links=True,attach_files=True)```
#

only thing I see with

#

guild.default_role:

cyan quail
#

oh

#

that makes so much more sense now

cyan quail
#

or if not, do show how it's defined

thorn saffron
#

that's from the linking system

cyan quail
#

basically

#

one of your role IDs in that list is wrong

thorn saffron
#

so someone deleted a role 😦

cyan quail
#

as long as all the IDs in there are real roles and integers, your tickets should work again.

thorn saffron
#

makes sense

#

got it, it was one it was meant to be removing

#

let's see if it fixes it

#

Done all that, fixed all the roles within config, still doesn't work

#

same error

#
ERROR:discord.ui.view:Ignoring exception in view <DropdownServersViewList timeout=60 children=1> for item <DropdownServersList placeholder='Click Here' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Atlas - US 5x | No BPs | Kits | JUST WIPED 04/11' value='Atlas - US 5x | No BPs | Kits | JUST WIPED 04/11' description=None emoji=None default=False>, <SelectOption label='Atlas - EU 5x | No BPs | Kits | JUST WIPED 08/04' value='Atlas - EU 5x | No BPs | Kits | JUST WIPED 08/04' description=None emoji=None default=False>, <SelectOption label='Atlas - AU 5x | No BPs | Kits | JUST WIPED 04/04' value='Atlas - AU 5x | No BPs | Kits | JUST WIPED 04/04' description=None emoji=None default=False>, <SelectOption label='Atlas - Development' value='Atlas - Development' description=None emoji=None default=False>, <SelectOption label='Atlas - US 2x Main | Vanilla | 03/21' value='Atlas - US 2x Main | Vanilla | 03/21' description=None emoji=None default=False>, <SelectOption label='Atlas - US Mondays 3x | No BPs | Just Wiped! 02/27' value='Atlas - US Mondays 3x | No BPs | Just Wiped! 02/27' description=None emoji=None default=False>]>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/Create.py", line 92, in callback
    await Creation.generate_make_ticket(
  File "/home/container/cogs/Create.py", line 271, in generate_make_ticket
    channel = await guild.create_text_channel(
  File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1355, in create_text_channel
    data = await self._create_channel(
  File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1213, in _create_channel
    payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
AttributeError: 'NoneType' object has no attribute 'id'```
cyan quail
thorn saffron
#

it's saying these @cyan quail

#

896145297128955974 Manager
896145295543533588 Senior Administrator
895995833382748241 Administrator
899385196313452575 Trial Administrator
896145522870603816 None
895995793339715614 Moderator
992961996687417394 Trial Moderator

but 896145522870603816 isn't defined in my config?

cyan quail
#

well it must be

thorn saffron
#

it's not? 😂

cyan quail
#

are you 100% sure you edited RolesInChannel

thorn saffron
#
        "Guild_ID":870207685541363732,
        "Operations_Role_ID":959002629533499402,
        "Roles":[
            870539877337399296,
            896145297128955974,
            896145295543533588,
            895995833382748241,
            899385196313452575,
            895995793339715614,
            992961996687417394
        ],
        "RemoveOnClaimed":[
            895995793339715614,
            992961996687417394
        ]
    },```
cyan quail
#

you might need to restart the bot then

#

wait

#

that's not even the right one though

#

the code is referring to a different config file

thorn saffron
#

I've restarted it,

Roles = the ones who get added to the ticket
Removedonclaimed = id's who get removed?

limber urchin
#

that's in the config you sent

thorn saffron
#

that's not a config file @limber urchin that's a print error that the loop is picking up

cyan quail
#

ok

#

find where ticket_type_info is defined

limber urchin
cyan quail
#

no it's just a dict

limber urchin
#

but the ID is in that dict

cyan quail
#

yeah but it's irrelevant because the code's iterating through a list

#

so it's not that

thorn saffron
#

I'm assuming it'll be

#

for role_id in ticket_type_info["RolesInChannel"]:

cyan quail
#

yes

#

either there's another config file containing RolesInChannel or you straight up missed it in the same file

#

that is what you have to edit

thorn saffron
#

Let me go on a search 😂

proud mason
#

If only you could have varible values in the errors blobpain

cyan quail
#

well that's why debuggers exist

proud mason
#

I would use a debugger. Smth like vscode debugger

cyan quail
#

but eh we're too far gone

proud mason
thorn saffron
#

or simply put RolesInChannel in the config file? 😒

cyan quail
#

...it already exists

#

somewhere

#

it's your code man idk

thorn saffron
#

Yeah haha not my code but yeah

#

if it was GMT timezone wouldn't be an issue

#

developer would be online

cyan quail
#

can you find where ticket_type_info is defined in the file

#

defined, not just used

thorn saffron
#

Hmm

 #If the ticket type has questions then send a model with input boxes else make ticket
          ticket_type_info = self.bot.questions_data["Categories"][ticket_type]
          if ticket_type_info["Questions"]:
               try:
                    return await interaction.response.send_modal(ModelWithQuestions(self.bot,ticket_type,ticket_type_info["Questions"],check_linked))
               except discord.errors.NotFound:
                    return
          else:
               return await Creation.generate_make_ticket(self,interaction,guild,member,ticket_type,check_linked)


     async def generate_make_ticket(
          bot = None, 
          interaction: discord.Interaction = None,
          guild: discord.Guild = None,
          member: discord.Member = None,
          ticket_type: str = "",
          steam64: str = "0",
          questions: dict = None,
          autogenerated:bool = False,
          autogenerated_info:dict = None,
          server_name:str = "None",
          autogenerated_reportID: str = None,
          ) -> None:

          if not guild:
               guild = bot.get_guild(bot.data["StaffListInfo"]["Guild_ID"])
          
          

          #FindCategoryFromConfig
          ticket_type_info = bot.questions_data["Categories"][ticket_type]
          category = bot.get_channel(int(ticket_type_info["TicketCategory"]))

          #TicketNumber
          newticket_num = bot.ticketnum + 1
          if newticket_num == 1488:
               newticket_num = 1489
#

if this helps

cyan quail
#

ok....

#

so in your main bot file find questions_data

thorn saffron
#

FOUND IT!!!

cyan quail
#

nice

thorn saffron
#

it works now

cyan quail
#

nice

thorn saffron
#

thank you @cyan quail

here is an ice cream 🍨

cyan quail
#

if only...

thorn saffron
#

add me back

solemn idol
grizzled sentinel
real frost
#

wassup, How can i detect command usage other bots (like /bump) ?

solemn idol
silver moat
#

.rtfm message.interaction

solemn idol
#

I'm so confused rn

young bone
bronze vector
#

how can I remove @everyone role from guild's roles list?
ctx.guild.roles.pop(0) is just returning @everyone role

#

or am I doing something wrong?

full basin
bronze vector
#

i always thought that pop is for remove, ty

full basin
#

It removes the item from the list

#

The method returns the removed item

bronze vector
#

yeah I get it

silk spindle
#

hello, is it possible to use a datetime argument for a slash command ?

silk spindle
real frost
tired crag
#

How do I get server ID / where is it in the docs

proud mason
tired crag
#

im assuming its like ctx.guild or something

proud mason
#

ctx.guild is absolutely correct

#

so you would do ctx.guild.id

tired crag
tired crag
#

i see

proud mason
#

ctx.guild is just a reference to ctx.interaction.guild. so both are the same

tired crag
tired crag
#

wdym

#

like full error?

proud mason
#

yes

tired crag
#

okay

#
  File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1114, in invoke_application_command    
    await ctx.command.invoke(ctx)
  File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ProgrammingError: Could not process parameters: int(1030942556307062925), it must be of type list, tuple or dict```
proud mason
#

hmm doesnt have much info

#

can you show the line where your use this?

tired crag
#

yep

proud mason
#

btw guild id is already an int

tired crag
#

ah, let me try that

tired crag
proud mason
#

so you could do val = (ctx.guild.id ,)

tired crag
#

okay I have a new error

#

I'm pretty sure im using all parameters

proud mason
tired crag
#

bruh..

#

im not doing db.commit()

#

maybe that's it?

proud mason
tired crag
#

nope. same error

proud mason
tired crag
#

oh, what's that?

proud mason
#
tired crag
#

ive not really used mysql with python 😂

#

is that not val?

proud mason
#

you would put a ? after VALUES

proud mason
tired crag
#

wait wdym

proud mason
#

so smth like INSERT INTO table_name (column) VALUES (?)

#

replace table_name and column

tired crag
#

oh

#

do I just do a ? or do I need to change the ? to something

proud mason
#

so yeah keep it like that

tired crag
#

okay

#

yeah still same error

proud mason
proud mason
tired crag
proud mason
tired crag
#

kinda sus

#

AHA

#

no errors anymore but it's saying no database selected

#

and I can fix that

#

ty @proud mason ❤️

proud mason
#

im so sorry

tired crag
#

all good! lol

proud mason
#

i thought it was sqlite lel

tired crag
#

lmaoo

#

na mysql hates me rn lol

#

wtf going on lol

#

brb

#

back

sand niche
#

Say I have an interaction that my bot responds with an ephemeral message that is supposed to be added or changed later. If the user dismisses the message, does that count as the original being deleted for the context of a followup or edit? edit: typos

#

Should I just check for a not found exception and then just post the message with ctx.respond?

sand niche
# rare ice sql sucks, use mongodb

mongodb sucks. just put everything in memory and dump state to/from disk on shutdown/restart and give chrome a run for its money with memory usage. /s edit: typos

rare ice
#

then maybe not self host your mongodb?

sand niche
#

I was clearly making a joke. I have no opinion on mongo.

rare ice
#

"clearly"? we using a text chat app where i can't see your emotions

#

no shit i cant tell

sand niche
#

dude there is a /s. as in sarcasm. thats pretty clear and common.

rare ice
#

ok?

copper pine
#

Hello, I just want to add a link button to an embed. Can someone tell me how to do it? (I tried to search for help but the example in link.py requires a "query".)

finite flame
#

how can I use discord.utils.format_dt() to display the current time? I noticed that datetime.utcnow() gives me a time 2 hours shifted from my actual time

rare ice
finite flame
#

ok noice

silver moat
copper pine
rare ice
#

How can I add a view from the bot object in either the __init__ or the setup() of the cog?

cyan quail
rare ice
#

it says there is not event loop running

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 786, in _load_from_module_spec
    setup(self)
  File "/home/container/cogs/ticketsv2.py", line 67, in setup
    bot.add_cog(TicketsV2(bot))
  File "/home/container/cogs/ticketsv2.py", line 21, in __init__
    bot.add_view(CreateTicketView(bot))
  File "/home/container/cogs/ticketsv2.py", line 9, in __init__
    super().__init__(timeout=None)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 183, in __init__
    loop = asyncio.get_running_loop()
RuntimeError: no running event loop```
cyan quail
#

Then just do it in on ready with wait until ready

rare ice
#

i cant

cyan quail
#

Why

rare ice
#

i am doing it where all cogs load their own views

#

since its easier

cyan quail
#

Then make it an on ready listener in the cog

rare ice
#

oh

#

i didnt think of that

young bone
lean marten
#

My bot is supposed to grab the message of users (on_message) and send them in a channel (without any editing).
If a user sends a message with e.g. a imgur link (image) it doesnt display the embedded image in the channel but only the hyperlink.

How its supposed to be:
https://i.imgur.com/aKrQpCs.png

How it is sent:
https://i.imgur.com/BUAvy74.png

Any ideas how I can fix it?

full basin
soft girder
#

What is the name of the function, with which the buttons will turn off at the right time for me.

limber urchin
#

what?

lost lodge
#

Hey guys,

How can i create a post in a forum channel?

full basin
winter condorBOT
#

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

full basin
#

.rtfm ForumChannel.create

west quest
#

Hey, how would I handle the discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions error?

#
    if isinstance(error, discord.Forbidden):
        await ctx.author.message("Please add read channel permissions to the bot.")``` I have tried this
fast flame
#

Does @discord.ui.button have a url argument?
Something the python says is missing.

limber urchin
#

The decorator does not, because a url button can't have a callback

lost lodge
full basin
#

The same way you get a normal channel.

lost lodge
proud mason
lost lodge
lost lodge
young bone
lost lodge
young bone
#

Im not really sure that a ForumChannel is

lost lodge
young bone
#

I mean this

young bone
full basin
#

guild.get_channel is a method

young bone
#

^

full basin
#

.rtfm get_channel

lost lodge
#

but theres still an error (unexpected arg)

full basin
#

You don't pass it as a kwarg

lost lodge
full basin
#

Remove the id=

lost lodge
lost lodge
#

Now i have an other problem:

code:

channel = ctx.guild.get_channel(int(config_todo['channel']))
        thread = await channel.create_thread(name=f"{who.mention} - {strength}", reason="Todo", message="Hey")
        await thread.send(f"{what}")```


Command raised an exception: TypeError: ForumChannel.create_thread() got an unexpected keyword argument 'message'

sick surge
#

hi

#

is there a way to detect when new forum post is created (like an event)

lost lodge
strange beacon
lean marten
grizzled sentinel
winter condorBOT
grizzled sentinel
#

You will need to check if it is in a forum Channel though.

grizzled sentinel
#

.rtfm Embed.set_image

winter condorBOT
west quest
# young bone commands.ThePermission

yeah but I'm unable to figure out which one. it's just a problem when someone uses a slash commands in a channel the bot doesn't have access to

fervent cradle
#

What should I do to fix this?

discord.errors.InteractionResponded: This interaction has already been responded to before
A button that responds with something after clicking then disables it

#

I used await interaction.response.edit_message(view=self) to edit the view, but I think that's the cause. I am not sure what to do, can someone help?

silver moat
#

.rtfm interaction.edit_original_message

winter condorBOT
fervent cradle
#

I didn't understand, can you explain?

real frost
#

Hello, how to edit responded interaction through the paginator.edit()?
i've tried paginator.edit(ctx.message) and paginator.edit(ctx.interaction.message)

knotty surge
#

Hello all been doing some googles and not found anything. There anyway to return all users assigned to a tag such as @LoremIpsum (return all users)

full basin
full basin
full basin
real frost
full basin
#

.rtfm Paginator.edit

winter condorBOT
knotty surge
full basin
full basin
winter condorBOT
full basin
#

Just get the role and use the atteibute

#

.rtfm get_role

winter condorBOT
knotty surge
#

So I would want to use Guild right to return all members with that role?

real frost
#
Traceback (most recent call last):
  File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped     
    ret = await coro(arg)
  File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 978, in _invoke     
    await self.callback(self.cog, ctx, **kwargs)
  File "d:\moneyrain\Harrison\leveling.py", line 130, in leaderboard
    await paginator.edit(ctx.message)
  File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\pages\pagination.py", line 1058, in edit
    raise TypeError(f"expected Message not {message.__class__!r}")
TypeError: expected Message not <class 'NoneType'>

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

Traceback (most recent call last):
  File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Message not <class 'NoneType'>

full basin
#

Try passing await ctx.interaction.original_response()

real frost
#

I need to just replace it right?

fervent cradle
#

What's followup and how do I use it?

knotty surge
#

Hello all, I am trying to return all users with a role. This is my code:

@bot.slash_command(name="createclass")
async def createclass(
        ctx: discord.ApplicationContext,
        role: discord.Role
):
    role = discord.utils.get(ctx.message.server.roles, name="mod")
    if role is None:
        await bot.say('There is no "mod" role on this server!')
        return
    empty = True
    for member in ctx.message.server.members:
        if role in member.roles:
            await bot.say("{0.name}: {0.id}".format(member))
            empty = False
    if empty:
        await bot.say("Nobody has the role {}".format(role.mention))

Getting this error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'server'

full basin
full basin
full basin
#

And use ctx.guild

#

There's no need to use ctx.message.guild

#

Read the docs

knotty surge
#

so ctx.guild.roles for example?

full basin
#

Yes

#

And bot.say doesn't exist

knotty surge
# full basin Yes

Its only returning the first user

@bot.slash_command(name="createclass")
async def createclass(
        ctx: discord.ApplicationContext,
        role: discord.Role
):

    role = discord.utils.get(ctx.guild.roles, name= str(role))
    if role is None:
        await ctx.respond(str(role) + ' is not a valid BUD/S Class on this server!')
        return
    empty = True
    for member in ctx.guild.members:
        if role in member.roles:

            # Check if SA/SR only as INSTRUCTOR has tags also
            print(member.nick)


            # Create NAME TAG
            # SEND INTO ZIP

            #await ctx.respond("{0.name}: {0.id}".format(member))

            empty = False

    if empty:
        await ctx.respond(str(role) + ' is Empty!')
    else:
        await ctx.respond(str(role) + ' is Not Empty!')
full basin
#

members = role.members 
if len(members) == 0:
    return await ctx.respond("This role has no members")

parsed_members = [f"{member.name} {member.id}" for member in members]

await ctx.respond(content="\n".join(members))```
#

It's as simple as that

#

You definitely need to learn more python

knotty surge
full basin
#

Full error

#

Code

#

And If you don't know python, you shouldn't be coding a Discord bot

knotty surge
#

I fixed it however it is only returning one user. My mate mentioned something about SERVER MEMBERS INTENT could be the reason why it is not returning more then one person

#

I've turned it on and it seems to have no change

proud mason
#

You have to turn it on in your code too

full basin
#

Are you passing the intents to the bot instance?..

proud mason
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#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)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

knotty surge
#

sorted it, simply forgot to assign the intents. Thanks for the help!

boreal nova
#

Hello, how to override slash commands without turning off the bot?

solemn idol
#

.rtfm sync

solemn idol
#

-.-

#

hold on

boreal nova
solemn idol
#

.rtfm sync_commands

solemn idol
#

Yeah that's syncing

solemn idol
#

.rtfm extension

solemn idol
#

the reload_extension, you could also make a load and unload command which should unload of load a cog but it doesn't because as I said. Pycord Library issue :/

dense tide
#

How do I get the current username from the user id, if I can?

lost lodge
#

Hey guys!

Could anyone tell me how to change the tags of a forum thread?

boreal nova
solemn idol
#

.rtfm fetch_user

solemn idol
solemn idol
lost lodge
solemn idol
#

I'm looking through the docs myself rn lol hold on

lost lodge
solemn idol
#

Thanks

lost lodge
solemn idol
#
# Get the thread you want to edit
    thread = client.get_channel(THREAD_ID)
    
    # Define the new tags you want to apply
    new_tags = [discord.ForumTag(name="new_tag_1"), discord.ForumTag(name="new_tag_2")]
    
    # Edit the thread and apply the new tags
    await thread.edit(applied_tags=new_tags)
lost lodge
#

ah with name

lost lodge
#

smart

solemn idol
#

Yeah I am not sure if that works but I suppose it should work. thinkCat

#

Lemme know if it works.

solemn idol
lost lodge
#

np

solemn idol
lost lodge
solemn idol
#

debugging at its best

#

for example after defining the thread you wish to edit you can try printing the Thread variable

#

also make sure the bot has permissions to edit threads :P

#

Manage Threads permission is required for that.

lost lodge
solemn idol
solemn idol
#

THREAD_ID = 123456789

#Get the thread you want to edit
thread = client.get_channel(THREAD_ID)

print(f"The ID of {thread} is {THREAD_ID}")
#

@lost lodge

solemn idol
#

I'm not entirely sure if tags have ID's...

lost lodge
lost lodge
solemn idol
lost lodge
solemn idol
#

oh damn

#

hmmm

#

It seems that the ForumTag class does have an id attribute.

So I assume you can do this;

new_tag = discord.ForumTag(id=TAG_ID)
solemn idol
#

still looking at that rn

lost lodge
#

ok

solemn idol
#

guild.fetch_forum_tags() ?

lost lodge
solemn idol
#

hmm

#

well I am out of options rn...

#

and ideas :/

lost lodge
#

me too

solemn idol
lost lodge
#

i have it

solemn idol
#

Ayyyyyyyy

#

literally the only line I found ab this

merry dune
#

Guys who worked with the database, what is better to use for a massive database for collecting identifiers, and a message counter, and what is easier to apply in coding (who says json (pls run away in forest 😅)

obtuse juncoBOT
#

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

Advantages of using a database:

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

Popular database management systems:

- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
solemn idol
#

there are some

#

for absolute massive amounts of data I suppose MongoDB can help you

#

does that help?

#

blobpain and he was never heard from again...

merry dune
#

Thanks and seems i can use Postgre in replit but is there anything free doggokek

solemn idol
#

anything good is never free

#

atleast not from my experience

merry dune
#

I don't want to create json, I really don't like how it works and sometimes if it collects more than 50k user data, my host burning kek

solemn idol
merry dune
#

today its one ping and button press i had to run the code from my phone because it has two streams per output

solemn idol
merry dune
#

Idea counts messages in history entry error 4xx
doggokek
Next time i create and collect data in db

solemn idol
#

boi

#

you're in for a ride

merry dune
#

We have 138k users on server kek

#

just to hold events and create a barrier for tweak accounts, we decided to create a verification level, and since the idea with the history failed so that the discord restricted access to messages, it was decided create db and after couple months add in verify code limit for messages

solemn idol
#

... you store all of that in Json?

#

@merry dune is that a yes or a no?

merry dune
merry dune
solemn idol
#

for bigggg databases

#

otherwise I can recommend a lightweight database Sqlite3

merry dune
#

TY u best❤️
Now i need open vpn and learn db❤️

limber urchin
#

Mongo is definitely not necessary in your case. Just use an SQL based database if you don't already know how to use Mongo

#

And for hosting, don't use AWS. It's relatively speaking overpriced and most of it's features are useless for a simple project like a Discord bot. Use something like DigitalOcean, GalaxyGate, Vultr etc.

limber urchin
#

The big hosting providers like Google Cloud, AWS, Microsoft Azure, Oracle Cloud etc. will typically make you pay more. Although being more reliable and robust, they're rarely worth it and you can find hosts for way cheaper.

#

And as for databases, NoSQL databases tend to create a lot of unnecessary complications with little payoff. 138k users is not even close to being considered a "big" database. When you start reaching hundreds of millions, or even billions of rows.. that's when NoSQL might come in handy. I highly recommend using a simple SQL based database instead, such as Postgres, SQLite or MariaDB.

lean marten
limber urchin
#

Or just don't send an embed at all

meager heron
#

Is there a way to see if a message’s author is a webhook?

elfin dagger
#

i have a discord.ui.View class with an on_timeout function that disables all buttons but when i go to apply these changes im getting AttributeError: 'NoneType' object has no attribute 'edit'
i have no idea what's happening, i've checked all intents on the developer page and in main

eager bronze
#

i am getting this error when i try to reload a cog containing a bridge command
:'BridgeCommand' object has no attribute 'name'

the code is:

@bot.bridge_command()
async def reload(ctx, cog: str):
    try:
        bot.reload_extension(f'cogs.{cog}')
        await ctx.send(f"{cog} has been reloaded.")
    except Exception as e:
        await ctx.send(f"Error reloading {cog}: {str(e)}")```
proud mason
proud mason
#

1st

eager bronze
#

any fixes?

proud mason
#

Not that I know of unfortunately

eager bronze
#

so i cannot unload bridge commands using cogs?

merry dune
elfin dagger
#

im almost certain it's worked before but i don't remember :/

proud mason
elfin dagger
#

yes

silver moat
proud mason
elfin dagger
#

ah so it's a known issue

proud mason
#

But for the time being, you can do

view = View()
msg = await ctx.respond(...)
view.message = msg

This is only if you defer

proud mason
silver moat
elfin dagger
eager bronze
meager heron
merry dune
#

@meager heron but u can use same msgs
This embed in commands/events
And send in any channel/guilds and dmsdoggokek if u want send in dms

merry dune
meager heron
#

I know how to create webhooks and send messages from them. This is specifically for reducing my database calls by only making them when a webhook message is deleted. It's very specific for my use case

stark walrus
#

how to make it so that Either role or channel argument (only one of them) can be passed

errant craneBOT