#discord-bots

1 messages · Page 353 of 1

viscid hornet
#

looks like it exists

#

did you add the cog with the bot attr?

#
async def setup(bot):
    await bot.add_cog(YourCog(bot))```
leaden olive
#

command really doesnt work, did you find any problems?

#

im looking for hours, and didnt find anything

viscid hornet
#

use this to open your .sql file

#

and screenshot the contents

glad marsh
#

no

viscid hornet
# glad marsh no

pretty much all free vps sites have drawbacks that will force you to perform tradeoffs

#

they do want money after all

#

how else is their business gonna stay afloat

glad marsh
#

i have a laptop

midnight oracle
slate swan
#

@viscid hornet any chance you can help me to achive what im trying to do and not do channel.send?

slate swan
#

can anyone help me im getting this error

raise InteractionResponded(self._parent) discord.errors.InteractionResponded: This interaction has already been responded to before

class SetEmail(discord.ui.Modal, title='Set Email'):
    inputemail = discord.ui.TextInput(style=discord.TextStyle.short, required=True, label="Email Address", placeholder='Enter your email address', min_length=1, max_length=100)

    email_set_event = asyncio.Event()

    async def on_submit(self, interaction: discord.Interaction):
        userid = interaction.user.id
        email = self.inputemail.value

        data = read_json("users")
        for user in data['users']:
            if user['id'] == userid:
                user['email'] = email
                write_json(data, "users")
                await interaction.response.edit_message(content="Email set", view=None)
                self.email_set_event.set()
                return
        else:
            await interaction.response.edit_message(content="Error setting email", view=None)
            return

    

    @app_commands.command(name="buy", description="Buy gifting credits")
    async def buy(self, interaction: discord.Interaction):
        class PaymentMethodSelect(discord.ui.Select):
            def __init__(self):
                super().__init__(
                placeholder="Payment Method",
                min_values=1,
                max_values=1,
                options=[
                    discord.SelectOption(label="Test")
                ],)

            async def callback(self, interaction: discord.Interaction):
                selected_method = self.values[0]
                if selected_method == "Test":
                    if not check_email(interaction.user.id):
                        await interaction.response.send_modal(SetEmail())
                        await SetEmail.email_set_event.wait()

                    embed = discord.Embed(title="Test Payment", description="Click the button below to pay with Test", color=discord.Color.dark_theme())

                    await interaction.response.edit_message(embed=embed, view=None)

                    return

        class PaymentMethodView(discord.ui.View):
            def __init__(self):
                super().__init__(timeout=None)
                self.add_item(PaymentMethodSelect())

        embed = discord.Embed(title="Payment Method", description="Select a payment method", color=discord.Color.dark_theme())

        await interaction.response.send_message(embed=embed, view=PaymentMethodView())```
fading marlin
#

You're responding to the interaction twice. First you're sending a modal, and then you're editing a message

slate swan
fading marlin
#

You can use a followup if you need to edit the message after the modal has been responded to

supple jacinth
#

How do I let the bot wait until someone replies to the original message the bot sent. I’m currently using context.bot.wait_for(‘message’, check = check) but it is only doing it for every message sent. So if people actively talk the bot will think a response has been sent

#

I also have a timeout of 25.0

slate swan
#

I'm trying to make a discord Automod that deletes curse words. The code I have linked below accesses a file called "bad_words.txt" which contains each word on a separate line. The bot can see these words and sends list of them all in the console but it just deletes any messages the person sends? How can I get it so it deletes just the words from the file?

( I suck at coding so I use tutorials to help )

from discord.ext import commands

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

bot = commands.Bot(command_prefix='!', intents=intents)

def load_bad_words():
    with open('bad_words.txt', 'r') as file:
        return [word.strip().lower() for word in file.readlines()]

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.event
async def on_message(message):
    if message.author.bot:
        return 

    bad_words = load_bad_words()

    for word in bad_words:
        if word in message.content.lower():
            await message.delete()
            await message.author.send("Your message containing a bad word has been deleted.")
            break

    await bot.process_commands(message)

bot.run('YOUR_BOT_TOKEN') ```

I ofc won't put my actual token. It doesn't give me a specific error but just deletes any message sent rather than just messages containing the bad words
fading marlin
supple jacinth
fading marlin
fading marlin
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

supple jacinth
supple jacinth
#

Hmm message.reference.message_id NoneTyoe object has no attribute message_id

supple jacinth
#

Fixed that issue but now I have this issue which I have no clue how that is working

#

The second embed replies to the first one

#

May if found this issue

slate swan
#

@fading marlin I keep getting the error

#

and now when there is a email im getting Unknown Webhook

torn solar
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

torn solar
#

idk why it wouldnt let me copy the error

#
@bot.tree.command(name="register", description="Register your account")
async def register(interaction: discord.Interaction):
    user = interaction.user
    cn = getNextEmptyRow(wks2)
    wks2.update_cell(cn, 1, user.name)
    wks2.update_cell(cn, 2, 0)
    embed = discord.Embed(title='Account Created', color=e_color, timestamp=datetime.now(), description="""
                          You have successfully registered your account.
                          Thank you for registering.
                          """)
    await interaction.response.send_message(embed=embed, ephemeral=True)```
torn solar
#

idk if im tweakin like ive made thousands of commands before

frigid estuary
#

im literally dying rn

#

@potent helm i remember your smart maybe you can help?

viscid hornet
frigid estuary
viscid hornet
#

like anything on the discord side?

frigid estuary
#

the lack of a message ;-;

viscid hornet
#

use sanitisation for your inputs

frigid estuary
#

thats the data tables for example

viscid hornet
#

? is for sqlite which i'm guessing is your db language

frigid estuary
#

postgresql

viscid hornet
#

ah alright

viscid hornet
#

the normal version is blocking

frigid estuary
#

all the other async functions work

#

just the one 2 send the level up message doesnt

#

would the db deploy logs be helpful?

viscid hornet
#

wait delete it nvm i dont need it

#

i found your error

frigid estuary
#

what is it?

viscid hornet
#

.get_channel() returns either a Channel or None

#

so if it can't find the channel, it basically just returns the command and cuts it off there

#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
frigid estuary
#

so how do i fix it?

viscid hornet
#

then rerun the code to make sure that's the error

viscid hornet
#

i said add it if there's no channel

frigid estuary
#

oh

blazing beacon
#

!d discord.Guild.fetch_channel

frigid estuary
#

k, the bot is launching with the changes ill let you know what happens in a minute

viscid hornet
blazing beacon
#

bro is single handedly resolving every issue 😭

shadow vigil
#

I am not a fan of the new tag

frigid estuary
#

dies

#

wait, could it be because its defining guild as ctx.guild, its recieving guild when called, but its not set to take guild when run?

frigid estuary
#

could that make conflicts that may not necessarily be represented as errors?

frigid estuary
#

k...

frigid estuary
#

self and ctx parameters are self-fulfilling iirc....

viscid hornet
frigid estuary
#

oof

blazing beacon
#

stupid suggestion:
maybe try to comment out the db code for now and call the func just to make sure whats causing the issues

frigid estuary
#

i did that already 🙂

blazing beacon
#

ah okay, and the bot did what you were expecting it to?

frigid estuary
#

ye

blazing beacon
#

neat, im also gonna assume you "wrapped" the db statements with prints to see where it messes up

frigid estuary
#

uhm no...

blazing beacon
#

try that frfr

#

also a stupid suggestion btw

frigid estuary
blazing beacon
#

very interesting

frigid estuary
blazing beacon
#

wait

#

are u lvling up urself somehow

#

to call the function

frigid estuary
#

yes

blazing beacon
#

okok hmmm

frigid estuary
#

1 message = 1 xp, 10xp = 1 level, the leveling system works (ik cause when i call view_level its right)

blazing beacon
#

since im not all too familiar with sql or the like i wont be of much help

frigid estuary
#

im mid with postgresql

blazing beacon
#

something feels fishy

#

im mid with sqlite LMAO (i just use json or just ignore a db)

frigid estuary
#

lol

frigid estuary
blazing beacon
#

ah i see, well can you send me your code so i can look @ it on pc

viscid hornet
frigid estuary
#

it has some documentation

blazing beacon
viscid hornet
frigid estuary
#

if its helpful im hosting on railway.app from github

blazing beacon
frigid estuary
blazing beacon
#

yeah i really dont know either, its a skill issue from me dude

frigid estuary
#

lol

#

this is one of the times i wish there where errors so at least i could fix them

blazing beacon
#

rightt

frigid estuary
#

actually imma go left cause something with this code aint right pithink

blazing beacon
#

i cloned ur bot so i can meditate on the code

frigid estuary
#

kk

viscid hornet
#

you're on dpy v1.7.3 💀

blazing beacon
#

now that im looking at pins

blazing beacon
#

(also if it works let us know 🦾 )

frigid estuary
blazing beacon
#

pip install -U discord i believe is the command

viscid hornet
frigid estuary
#

that doesnt work, theres a requirements file instead

#

also, i remember that the code worked 4 hours ago, but between then and now there was a discord update

torn solar
frigid estuary
#

i forgot to ping on reply 💀

viscid hornet
torn solar
frigid estuary
viscid hornet
viscid hornet
viscid hornet
frigid estuary
#

2.4.0?

viscid hornet
# torn solar wdym?

Unknown interaction only happens when you do interaction.followup.whatever()

#

or am i tweaking

viscid hornet
torn solar
frigid estuary
#

what da hail

torn solar
#

i can send u the whole file in dms

frigid estuary
#

im getting mixed signals lol

blazing beacon
#

the version you have is 1.7.3, uninstall it and reinstall the latest one

frigid estuary
#

but which one is the latest one lmao

blazing beacon
frigid estuary
#

ah ok

viscid hornet
torn solar
#

oh yeah

viscid hornet
viscid hornet
unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

torn solar
frigid estuary
#

2024-04-18 03:52:06 INFO discord.client logging in using static token

2024-04-18 03:52:12 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 010b5def581cd10add8b4bc0947b3be1).

Successfully logged in as Echo#4570

main.py:29: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(messageModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:30: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(memberModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:31: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(weatherModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:32: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(channelModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:33: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(HelpModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:34: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(ModerationModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:35: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(reminderModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

main.py:36: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

bot.add_cog(levelModule(bot))

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

...

torn solar
#

use patebin for that

blazing beacon
#

1 sec lemme get the github up again

frigid estuary
#

well at least im getting something now 🙂

blazing beacon
#

🦾

#

main.py lines 29-36, put await infront of the bot.add_cog(...)

frigid estuary
#

i did

#

but the message sendy thingy still isnt working

blazing beacon
#

did you make your setup function async?

frigid estuary
blazing beacon
#

alright

frigid estuary
#

i think it is

#
@bot.event
async def on_ready():
    create_database()
    print('Successfully logged in as {0.user}'.format(bot))
    await bot.add_cog(messageModule(bot))
    await bot.add_cog(memberModule(bot))
    await bot.add_cog(weatherModule(bot))
    await bot.add_cog(channelModule(bot))
    await bot.add_cog(HelpModule(bot))
    await bot.add_cog(ModerationModule(bot))
    await bot.add_cog(reminderModule(bot))
    await bot.add_cog(levelModule(bot))
    await bot.change_presence(status=discord.Status.online, activity=discord.Game('Starting...'))
    await asyncio.sleep(5)
    status_cycle = cycle(variables)
    while True:
      current_status = next(status_cycle)
      await bot.change_presence(status=discord.Status.online, activity=current_status)
      random_delay = random.uniform(30, 600)  
      await asyncio.sleep(random_delay)
      
bot_token = os.environ.get('TOKEN')
bot.run(bot_token)
blazing beacon
#

no in each cog

frigid estuary
#

the launch file is smol

blazing beacon
#
async def setup(bot):
  await bot.add_cog(...(bot))
frigid estuary
#

no i didnt... is that important?

naive briar
#

No, but that's how people usually make cogs; in an extension file

blazing beacon
#

yeah

frigid estuary
#

🍞 im dumb

#

build 2.001

#

2 because i updated the discord requirements file so its pretty much a different system

#

unforunately the message sendy thingy still aint workin

torn solar
drifting arrow
#

Idk what the message sends thingy is

torn solar
#

someone please help error is in the register command

naive briar
#

You didn't respond to the interaction in time (3 seconds), so it expires

torn solar
#

its not even a long command what

drifting arrow
frigid estuary
#

i ran it through an ai to see if its all up to date and erm....

drifting arrow
#

You may want to defer the interaction

naive briar
torn solar
quick gust
#

to make it work you defer

naive briar
#

You'd want to call the interaction.response.defer method to defer the interaction at the top and respond instead with interaction.followup

torn solar
#

how can i do so

frigid estuary
drifting arrow
#

On my phone so I cbf writing code

torn solar
#

ok ty

drifting arrow
#

Someone dragged me outside

#

Now I’m in the city

frigid estuary
drifting arrow
#

Suffering

frigid estuary
#

🐦 burb 🙂

drifting arrow
#

And then it’s interaction.followup.send()

frigid estuary
drifting arrow
#

Interactions have 3 seconds to complete normally and defer extends to 10 minutes

frigid estuary
#

3 seconds... sounds like my attention span

frigid estuary
#

ye

drifting arrow
#

Is it meant to be inside the other function?

frigid estuary
#

no

#

its called by the other function

drifting arrow
#

Paste error or you didn’t see the indent?

frigid estuary
#

idk ;-;

#

wait... could the indent be messing it up

drifting arrow
#

Yes

#

If this pastebin is your actual code then yes

frigid estuary
drifting arrow
#

The 2nd function is inside the first

frigid estuary
#

in my code it isnt...

drifting arrow
#

See how the 2nd highlight is more right?

#

That tells python it’s inside the first function

quick gust
#

its probably a paste error

drifting arrow
#

I hope so

blazing beacon
#

just incase it is a paste error thats the source

quick gust
#

yep paste error

naive briar
# drifting arrow

The spaces in front of the first line is removed by the message storage in most cases

#

Discord also does that

drifting arrow
#

It’s why I asked

#

Could just be a paste error and it looks like it is

naive briar
#

:P

frigid estuary
quick gust
drifting arrow
#

I’m gonna ignore indent errors

frigid estuary
quick gust
#

add print statements in different places to see where it stops

frigid estuary
#

i did 🙂

quick gust
#

and what'd u infer

drifting arrow
drifting arrow
#

Ya

#

Try catch doesn’t output every error

#

You want to ideally use it for as little a codeblock as possible

#

And only in instances where there’s a possibility it could fail

#

Not as an entire wrapper for a block of code

#

Alright time to go stumble back to my car . Back in 15 . If I don’t return in 30 assume the best

frigid estuary
#

still no errors

quick gust
#

its not printing first check passed?

frigid estuary
#

nope

quick gust
#

that means

if new_level > current_level:```
#

this isnt being met

#

try printing out both the variables

#

before the if statement of course

frigid estuary
#

k

#

when i use Echo_view_level the levels are updating properly.... so am i just dumb or...

#

we shall see

quick gust
#

i think i got your error

frigid estuary
#

507

508

quick gust
frigid estuary
#

well

quick gust
#

I have a feeling these are string types

#

print(type(new_level))

frigid estuary
frigid estuary
quick gust
frigid estuary
#

yes

#

we had a little xp accident

drifting arrow
#

You may need to do some test variables to ensure it works lol

#

Write two new variables before the check overwriting the original and set them to something that will trigger the check

frigid estuary
#

?

drifting arrow
#

Force it to trigger

#

This is why I need my pc lol

#

I would write it up

quick gust
# frigid estuary yes

if 507 is current level, 508 is new level, and both are integers. theres absolutely no way the print("first check") isnt outputting...

frigid estuary
#

hmmmmm

drifting arrow
#

Which is why you need to put fake levels in for now so it forces to run

quick gust
# frigid estuary ?

what they mean is

new_level = 1000
current_level = 10
if new_level > current_level:
  ...```
drifting arrow
#

Yes

frigid estuary
#

OH

drifting arrow
#

This forces it to run

frigid estuary
#

wait a sec.... when i do view_level it returns level_row = self.ldb_cursor.fetchone()
prev_level = level_row[0] if level_row else 0
return int(prev_level)
not the new level

#

should be fine

#

but thats the command ive been using to check if the leveling system is working

#

and this is fine iirc

drifting arrow
#

@frigid estuary basically to properly debug you first need to see where your code stops. So put print statements everywhere and anywhere. If you reach a point where it doesn’t work as intended you can easily trace back the last time it did work

frigid estuary
#

↓↑↨→←

drifting arrow
#

There is probably better ways to do it

#

But I like this way

#

It forces me to read my code

quick gust
#

nah print statements is the best way

drifting arrow
#

Also don’t be afraid to read your code out loud

#

Saying what it does as you go.

#

And what you expect to see etc

#

This helps you process what is actually happening

#

Like you will read it out loud and go “wait. wtf. No that’s not right”

#

Or realise you’re saying the same thing 5 times

#

Also invest in a rubber duck

frigid estuary
#

i feel like im about to fall asleep ngl... but i wanna get this working

drifting arrow
#

Sounds silly but it works

blazing beacon
drifting arrow
#

Sometimes I use my private discord servers to rubber duck

#

Like I don’t even need help I just need to process my thoughts

frigid estuary
#

why is total_xp defined twice hmmmmmmmm

drifting arrow
#

First line defines its value

#

Second one increments

frigid estuary
#

oh ye

quick gust
drifting arrow
#

Could shorten to one line if needed

quick gust
#

yes but readability 🫡

drifting arrow
#

Fuck readability!

frigid estuary
#

i keep looking at these and feel like im missing smthn

drifting arrow
#

Yes

quick gust
drifting arrow
#

I just realised

#

Remove ctx

quick gust
drifting arrow
#

Unless ctx is used in the send level up message then you need to define it

#

If you don’t properly assign the params when you call the function python will just assign the values in order

#

So ctx is actually user id in this case

frigid estuary
#

so if ctx isnt assigned then erm ugh

drifting arrow
#

You aren’t assigning ctx at all

blazing beacon
#

just have another arg for guild_id

drifting arrow
#

Normally discordpy does it but since this isn’t a command you need to pass it through

frigid estuary
blazing beacon
#

when u r calling the function from the message listener u can pass ctx and get everything

drifting arrow
#

Oh to be young and inexperienced

blazing beacon
#

sorry im still looking at ur code, i was setting up a postgresql db to try and recreate ur issue but i forgot the password i used to set it up 😭

drifting arrow
#

I remember when I was as inexperienced as @frigid estuary

#

Now my issues are more advanced lol and often so unique and niche that not even chatgpt can help lol

blazing beacon
drifting arrow
#

It is currently 3pm and I haven’t heard a car honk in 10 minutes

#

Almost forgot I was sat in a car park in the middle of the city

frigid estuary
#

trust me im great at front end but back end..... meh

drifting arrow
#

Same here but in reverse lol

frigid estuary
#

lol\

blazing beacon
drifting arrow
#

Ooo I hear a siren!

frigid estuary
#

mb

drifting arrow
#

Who wants to take the over and under on when the next car toot will be?

#

I say 2 minutes

#

Timer starting now

frigid estuary
#

buuuut....

drifting arrow
#

Not even

frigid estuary
#

if new_level > current_level:
print("first check passed")
# Send level-up message if the user leveled up
await self.send_level_up_message(guild, user_id, level=new_level)

i need to define guild 😮

drifting arrow
#

1 minute 40!

frigid estuary
#

also why do i feel like the inequality arrow is whats messing it up

drifting arrow
#

It’s not

frigid estuary
#

ik but i just have a feeling

#

like somethings wrong right about there

drifting arrow
#

You aren’t assigning guild at all

#

I wish I was at my computer lol

frigid estuary
#

same

drifting arrow
#

Can someone who understand what I am saying show him an example?
He is calling the function correct but he is assigning “user id” to the “guild” parameter and the “user id” param remains empty. The user id doesn’t have get channel

#

Your function takes 3 params and you only send two

frigid estuary
#

why isnt it giving me an error saying that then 😮

drifting arrow
#

Or to change it up. You need three keys to open this door and you have only used two

frigid estuary
#

@potent helm

#

bro was online last time i pinged him and went idle without even looking 😭

drifting arrow
#

Heh honk

#

Truck go honk

frigid estuary
#
if new_level > current_level:
            guild = ctx.guild
            print("first check passed")
            # Send level-up message if the user leveled up
            await self.send_level_up_message(guild, user_id, level=new_level)
frigid estuary
drifting arrow
#

I should hear another honk within 3 minutes

frigid estuary
#
async def update_user_xp(self, user_id, xp_increment):
        # Update user's XP in the leveling database
        self.ldb_cursor.execute('''
            INSERT INTO user_xp (user_id, xp)
            VALUES (%s, %s)
            ON CONFLICT (user_id)
            DO UPDATE SET xp = user_xp.xp + EXCLUDED.xp
        ''', (user_id, xp_increment))
        self.ldb_connection.commit()
        await self.update_level(user_id, xp_increment)

this seems right

#

i think i have an idea

drifting arrow
#

Oh boy

#

Here we go

frigid estuary
#

lol

#

so... the event on_message can pass ctx... and i can use ctx to get the guild... so why not pass ctx from on message to the function

drifting arrow
#

Idk give it a shot

fathom tree
#

i am tring to send an image but i am getting a no response for this line (py-cord)

await ctx.respond(file=discord.File(fp=f"test.png"))
latent jay
#

and is test.png in the same folder you're running the bot in

latent jay
#

try catching the error

fathom tree
#

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

#

this is the error

fathom tree
latent jay
#

Can you show the full code of the command?

#

you're probably trying to respond to a dead interaction

frigid estuary
#

i can die in peace...

#

i mean sleep.... i can sleep in peace

latent jay
#

that isn't the full command

frigid estuary
frigid estuary
blazing beacon
#

happy coding 🦾

frigid estuary
#

thnx 🙂

fathom tree
#

the test image is being saved each time i run the command

latent jay
#

what are you trying to do?

fathom tree
#

put a filter on avatar

latent jay
#

what type of filter

blazing beacon
latent jay
#

an API probably exists already for what you want to do

fathom tree
#

that's a different image...
but that's not the problem here
this works and the image is being saved

#

i can't use API in everything... i wanna do it myself

frigid estuary
weary verge
#

Hello i want make my bot 24h i use python

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

drifting arrow
#

It costs money but that’s the price to pay

#

Alternatively you can host it yourself on a computer and never turn it off

blazing beacon
weary verge
slate swan
#

Its Client

robust fulcrum
#

guys how can we mention a slash command in a message in disnake?

naive briar
golden portal
#

tbh why is he replacing the bot after defining commands above it

quick gust
#

some bots have commands here, what is this called?

slate swan
quick gust
#

you got a guide for this? are they added through the api wrapper or through the dev portal?

#

Can't find it if i search for "context" in disnake docs (maybe they don't have it?)

naive briar
#

The API

#

!d discord.app_commands.context_menu

unkempt canyonBOT
#

@discord.app_commands.context_menu(*, name=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command context menu from a regular function.

This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.

Examples...
naive briar
#

Average discord.py W

quick gust
#

disnake doesn't have it?

naive briar
#

I don't know other libraries besides discord.py :P

quick gust
#

unfortunate :(

naive briar
#

Maybe try searching something like message command?

quick gust
#

!d disnake.APIMessageCommand

unkempt canyonBOT
#

class disnake.APIMessageCommand```
A message context menu command returned by the API.

New in version 2.4.
quick gust
#

thank you

naive briar
#

🐈

hushed galleon
lament depotBOT
umbral carbon
#

im so confused with the music cog, are there any tips, i just want it to be basic nothing too complicated, something i can use for my own self

pale zenith
#

actually tho what did you change from soheab's? I hate gists don't keep commit history so I can't diff it :c

hushed galleon
pale zenith
#

And yeah that's what I mean. When forking a gist it doesn't keep the revisions

glad cradle
# hushed galleon iirc the format is `</cmd name:id>`, where ID is the slash command's ID with dpy...

currently on disnake the only way is by fetching the list of global commands / fetching the global command using

disnake.ext.commands.Bot.fetch_global_commands
or
disnake.ext.commands.Bot.fetch_global_command

they either return a list of objects or an object from which you can access the .id attribute

obviusly the most easy way to do this currently would be by manually retrievieng all the ids instead of fetching them every time

hushed galleon
glad cradle
#

auto-sync can be disabled by passing the appropriate flags when creating a Bot instance, so you need to create from scratch your own logic so it is possible but it's a very advanced thing

viscid hornet
fathom tree
#

i am learning that's why i asked for help here but was told to use API instead

upbeat otter
hushed galleon
# fathom tree i am learning that's why i asked for help here but was told to use API instead

#media-processing would be appropriate for questions specific to pillow, but as for integrating them into dpy, you'll want to make sure you're doing your image manipulation in a separate thread to avoid blocking your bot's event loop, and saving to an in-memory file to avoid concurrently writing to the same file on disk, e.g. ```py
import asyncio, io

def make_praise_image(image_data: bytes) -> io.BytesIO:
... # do some pillow magic
f = io.BytesIO()
image.save(f, format="png")
f.seek(0)
return f

@bot.command()
async def praise(ctx, user: discord.Member = commands.Author):
image_data = await user.display_avatar.read()
image_file = await asyncio.to_thread(make_praise_image, image_data)
file = discord.File(image_file, filename="praised.png")
await ctx.send(file=file)``` api reference: BytesIO, Image.save(), asyncio.to_thread()

ivory storm
#

hi i need help with command in discord bot sending on chanel "There was a problem processing your request. Please try again later."

@bot.command()
async def ltcc(ctx, transaction_id: str):
    token = "95b43bad72c14cde9b9eb521d0b8a14e"
    api_url = f"https://api.blockcypher.com/v1/ltc/main/txs/{transaction_id}?token={token}"
    currency_api_url = "https://api.coingecko.com/api/v3/simple/price?ids=litecoin&vs_currencies=eur"

    try:
        response = requests.get(api_url)
        data = response.json()

        if response.status_code != 200:
            error_message = f"Error communicating with LTC server (status: {response.status_code})"
            print(error_message)
            return

        total_value_ltc = sum([output['value'] for output in data['outputs']]) / 100000000

        currency_response = requests.get(currency_api_url)
        currency_data = currency_response.json()

        if currency_response.status_code != 200:
            error_message = f"Error getting currency rates (status: {response.status_code})"
            print(error_message)
            return

        ltc_to_eur = currency_data['litecoin']['eur']
        total_value_eur = total_value_ltc * ltc_to_eur

        transaction_date = datetime.fromisoformat(data['received']).strftime('%Y-%m-%d %H:%M:%S')

        embed = discord.Embed(title=f"LTC Transaction Details (ID: {transaction_id})", color=discord.Color.blue())
        embed.set_thumbnail(url="https://cryptologos.cc/logos/litecoin-ltc-logo.png")
        embed.add_field(name=":link: Hash", value=data['hash'], inline=False)
        embed.add_field(name=":white_check_mark: Confirmations", value=data['confirmations'], inline=True)
        embed.add_field(name=":calendar: Transaction Date", value=transaction_date, inline=True)
        embed.add_field(name=":inbox_tray: Inputs", value=len(data['inputs']), inline=True)
        embed.add_field(name=":outbox_tray: Outputs", value=len(data['outputs']), inline=True)
        embed.add_field(name=":moneybag: Total Value (LTC)", value=f"{total_value_ltc:.8f} LTC", inline=False)
        embed.add_field(name=":euro: Total Value (EUR)", value=f"{total_value_eur:.2f} EUR", inline=False)

        await ctx.send(embed=embed)

    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        pass
pale zenith
#

What exactly is outputted to your channel btw?

ivory storm
#

how can i do this

#

@pale zenith

#

i,m beeginer

pale zenith
#

do what?

#

could you answer my question

ivory storm
#

how should I make it work

ivory storm
#

"There was a problem processing your request. Please try again later."

pale zenith
#

right now what you're asking is pretty inactionable, as you're not being very specific.

ivory storm
viscid hornet
mild zephyr
#

im starting to reach a breaking point, i need someone willing to review my project x3 i think i'm doing bad practices on some stuffs yet i dont know where

blazing beacon
#

how do i get the input box thingy

#

!d discord

golden portal
#

modal?

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
hushed galleon
#

reminds me how weird it is to have {self.name} in that doc example

#

for a while i thought dpy did some magic to replace text inputs with strings, until i realized it was just returning .value from its __str__ method

blazing beacon
slate swan
#

Hi i have a problem when i have my discord bot and my flask website running at the same time im getting this error Timeout context manager should be used inside a task when i go on one of my apis and i want it to send a dm to a user when i go onto the api but I get that error

#

heres the code

#
@app.route('/api', methods=['GET', 'POST'])
def api():
    data = request.json
    asyncio.run(start_api(data))
    return 'Our server has received your api.', 200

async def start_api(data):
    try:
        if data['status'] == "COMPLETED":
            pass
        else:
            return
        
        discordid = data['discordid']

        discordid = int(discordid)

        try:
          user = await bot.fetch_user(discordid)
          if not user:
              return
          else:
              user.send("You have been given credits")
          return
        except Exception as e:
            print(f"Error in start_api: {e}")
    except Exception as e:
        print(f"Error in start_sellapp: {e}")```
midnight oracle
#

How can I get a discord.Guild object of a server with just the server ID to be able to create channels, categories, etc?
The thing is that the command that orders the creation of the channel/category can be used in all the servers the bot is in and make effect in one of the selected servers even if the command was not called from that server. Is that possible?

glad cradle
glad cradle
#

!d discord.ext.commands.Bot.fetch_guild

unkempt canyonBOT
#

await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity) and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice) per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member).

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_guild) instead...
glad cradle
#

you can use this to fetch a guild object

#

given the guild id

midnight oracle
#

OH

#

oka oka, thanks!

#

letme try

golden portal
#

its raising that error because you're using the bot with a different event loop, use asyncio.run_coroutine_threadsafe to use coros in a different thread and event loop

#

!d asyncio.run_coroutine_threadsafe

unkempt canyonBOT
#

asyncio.run_coroutine_threadsafe(coro, loop)```
Submit a coroutine to the given event loop. Thread-safe.

Return a [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future) to wait for the result from another OS thread.

This function is meant to be called from a different OS thread than the one where the event loop is running. Example...
slate swan
open sail
#

Is there a direct method to create a private thread that the admin cannot access.

viscid hornet
open sail
open sail
#

I'm using that right now

#

but admin can still enter the thread through the #threads

#

I know maybe dm is a way, but is there a method that can work in a server?

viscid hornet
open sail
viscid hornet
#

it's a lot cleaner

viscid hornet
open sail
#

the bot needs to detect the users and remove it....

viscid hornet
open sail
viscid hornet
#

just use DMs

open sail
#

but I need groups..

#

it's not personal

#

or is there a method to change a server's admin to a bot

open sail
#

can a bot be a server's admin

viscid hornet
#

with permissions?

open sail
viscid hornet
open sail
#

is it possible?

viscid hornet
#

its a bot

#

servers are created by users themselves

open sail
viscid hornet
#

there will always be higher roles that can see it

open sail
viscid hornet
#

owners are users because a user has to make it in the first place

open sail
viscid hornet
#

the person who ran the command?

open sail
viscid hornet
#

either way just use DMs

open sail
viscid hornet
open sail
tawdry swallow
#

can anyone give me an example for required parameters in a slash command?

open sail
viscid hornet
tawdry swallow
#

I need a requried option

viscid hornet
tawdry swallow
#

Well, this is a parameter isn't it?

#

The auto-fill

viscid hornet
tawdry swallow
#

I want the parameter to auto-fill with an answer

#

wait let me see if I can give you an example ;-;

viscid hornet
tawdry swallow
#

Like this :

tawdry swallow
#

Ah

#

alright, Thanks!

thin raft
thin raft
#

!d discord.Client.create_guild

unkempt canyonBOT
#

await create_guild(*, name, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

Bot accounts in more than 10 guilds are not allowed to create guilds.

Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
viscid hornet
thin raft
#

it is...

viscid hornet
#

you cant transfer server ownership to a bot?

open sail
thin raft
thin raft
#

wdym by that

upbeat otter
thin raft
open sail
#

what does that limit mean

#

sorry, I'm not familiar with guild

thin raft
#

guild = server

open sail
#

so creat_guild will actually create a new server?

#

a new one?

upbeat otter
thin raft
#

I just copy pasted

open sail
thin raft
upbeat otter
upbeat otter
tawdry swallow
#

Quick question :

How would I check if a member has a specific roles in a slash command? Discord.py

thin raft
#

if role in interaction.user.roles ?

upbeat otter
unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).

New in version 2.0...
tawdry swallow
#

Alright

#

thanks

open sail
#

cuz I might restart the bot

#

Very frequently lol

upbeat otter
#

Or if you're willing to explain everything again 💀

open sail
#

so I was trying to create a private thread for a certain group of users

#

it's a group, so DM doesn't work

#

but I want it to be purely private

#

even the admin cannot enter it

upbeat otter
#

Well then your bot can create create a server and then you can use that server to create private channels for your users

#

!d discord.Client.create_guild

unkempt canyonBOT
#

await create_guild(*, name, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

Bot accounts in more than 10 guilds are not allowed to create guilds.

Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
open sail
#

yeah but will it create the server everytime a start it?

upbeat otter
#

Nah you can just create it once and then delete that line of code if you want it to remain unchanged

open sail
#

lol

#

okay I'll try it

upbeat otter
#

Yeah

open sail
#

when I start the bot?

upbeat otter
#

No

#

In a command preferably

#

Then run that command and store the server id

#

Then use that id for further processing

open sail
#

so is it possible for me to transfer the ownership

#

cuz... there are so many members in my server

robust fulcrum
#

guys how can i get all slash commands from a ext by its name in disnake?

viscid hornet
thin raft
#

haha

#

just don't go over 10 guilds

viscid hornet
thin raft
#

it's a fork iirc

#

like pycord and nextcord

robust fulcrum
unkempt canyonBOT
mild zephyr
open sail
#

I was trying to get the user id by username

#

and it always return None

robust fulcrum
#

guys should i make text based commands or slash commands, like which are preffered and easy to use?

viscid hornet
viscid hornet
open sail
#

get the user id by username

viscid hornet
viscid hornet
#

whats the scope of your username search?

#

one server? multiple servers? the whole of discord?

open sail
open sail
#

I used guild.members

open sail
viscid hornet
golden portal
#

!d discord.Guild.get_member_named

unkempt canyonBOT
#

get_member_named(name, /)```
Returns the first member found that matches the name provided.

The name is looked up in the following order...
open sail
#

I still get None

fierce oxide
#

How can i do a while loop with integers?

viscid hornet
fierce oxide
#
age = str(int(input("How old are you?: ")))

while len(str(age)) == 0:
    age = int(input("How old are you?: "))
#

To make it loop until the user types a full answe

#

i tried

age = int(input("How old are you?: "))

while len(age) == 0:
   age = int(input("How old are you?: "))

But then i just get the error

Traceback (most recent call last):
  File "D:\First\First\HelloBubba.py", line 10, in <module>
    while len(age) == 0:
          ^^^^^^^^
TypeError: object of type 'int' has no len()
naive briar
#

This is not a question about Discord bots, I'm afraid

viscid hornet
leaden elbow
#

Is there a good way to check if a token is a bot token or user token?

viscid hornet
leaden elbow
viscid hornet
leaden elbow
#

But I have to check if it's a bot then bot or user token then user.. because in the headers in the auth I have to set it to bot {token} when it's a bot token

viscid hornet
#

theres not really any way around that

#

whats your use case?

leaden elbow
#

A token tool... You find a token and then you can for example show all guilds the user/bot is on

#

But I guess I will just add a u/b input to select if it is a user or bot token

sonic kelp
#

am I importing it correctly? 🗿

sonic kelp
#

lemme try in a sec

open sail
sonic kelp
#

okay

open sail
#

I enabled the members intent in the developers portal

sonic kelp
#

well, ofc

quick gust
#

but yeah the import is correct

sonic kelp
quick gust
#

? so why ask

quick gust
sonic kelp
quick gust
#

the display of humour was lacking but alright

sonic kelp
near crown
#

how do i configure telegram bot to listen message from my channel and respond to it
I already have the channel id
currently bot is listening to itself and responds

viscid hornet
viscid hornet
quick gust
viscid hornet
sonic kelp
#

it does

#

if youre gonna decide to be a smartass, do it correctly

#

and i am clearly in pycharm, so it would highlight incorrect shit

viscid hornet
quick gust
#

apparently it does work 💀

#

today I learned

viscid hornet
sonic kelp
#

🗿

glad cradle
#

Understanding where you could do better is part of the improvement

agile spade
#

Im using discord.py and was wondering how i could check if i have the ability to ban a member from a server?

slate swan
hushed galleon
slate swan
#

@hushed galleon may you help me out with a problem I’m having

golden portal
#

fairly straightforward

#

tbh i would recommend just not combine flask and discord.py in the same process/project

slate swan
open sail
#

is it possible to add multiple users to a thread at a time?

#

(I want to prevent users added to thread notification messages from being too long)

midnight oracle
#

Any idea why this is not giving me the role when I react to the message?

@bot.event
async def on_reaction_add(reaction: discord.Reaction, user: discord.User):
    if user.bot:
        return

    try:
        with open('projects/project_data.json', 'r') as infile:
            project_data = json.load(infile)
    except (json.JSONDecodeError, FileNotFoundError):
        project_data = []

    if isinstance(project_data, list):
        for project_info in project_data:
            if project_info['message_id'] == reaction.message.id:
                if reaction.emoji == '✅':
                    project_details = project_info['project_data']
                    server_guild = await bot.fetch_guild(project_details['server_guild'])
                    role = await server_guild.get_role(project_details['role_id'])
                    await reaction.user.add_roles(role)

queen leaf
#

I need to call src/image_gen.py and then an image output is generated by it

#

My bot needs to display the image

vale wing
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add), this is called regardless of the state of the internal message cache.

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
vale wing
#

I think I have some open source repo with image generating bot

#

Lemme see

midnight oracle
vale wing
#

And it will never be in cache after bot restart

midnight oracle
#

oooh

midnight oracle
#

gotcha

vale wing
#

Specifically at async functions that wrap sync image generation functions

golden portal
#

asyncio.get_event_loop().run_in_executor(None, ...) is equivalent to asyncio.to_thread(...), better of using that function, most people actually just make a deco for it so its not a bloat

open sail
#

is it possible to add multiple users to a thread at a time?
(I want to prevent users added to thread notification messages from being too long)

vale wing
#

It still looks pretty unholy

vale wing
open sail
#

but the problem is

#

users added to thread notification messages will be sooooo long

golden portal
#

the endpoint for adding members to thread doesnt seems to provide a way to add multiple users per call

vale wing
open sail
#

what would happen if you get ratelimited

vale wing
#

Discord doesn't let you send requests for some time

open sail
#

I think I've got this from clearing messages

vale wing
#

How many users get added to thread at one time

upbeat otter
open sail
#

I'm adding it by a for loop

#

which will cause the thread having 12 messages like
{user1} has been added to this thread
{user2} has been added to this thread
{user3} has been added to this thread
...
{user12} has been added to this thread

#

so I was finding for a method

#

that can add them once

#

{user1, user2, user3, ... user12} have been added to this thread

#

is this clear enough?

quick gust
#

Are you manually sending this message? like with .send()? If so then you don't need to send the message again and again

golden portal
#

huh for a sec i thought they just want a single api call to add multi users into thread, guess it was just logic issue

queen leaf
#

Actually could u explain what I need to do in simpler terms? If possible

#

My smooth brain can't process this

vale wing
#

If you mean the system message

vale wing
#

Scroll down till you see async functions

viscid hornet
open sail
abstract granite
#

How do I make a help menu with select menu?

#

@viscid hornet

viscid hornet
#

a help command with a select menu?

abstract granite
#

yeah

#

:v

abstract granite
viscid hornet
#

my guess is that you would get all the cogs, load them into a select menu, then get a list of commands and their details like usage, description, etc into a list from those cogs and display them in a paginator

#

but thats like surface level, idk the intricacies 🤷🏽‍♂️

abstract granite
#

@vapid parcel

vague spade
#

Hello, it does not detect the prefix of my bot.

vale wing
#

What is It

vague spade
vale wing
#

No PREFIX in your environment

#

You mistyped it ig

#

PREFÏX or smth

vague spade
#

There is

vale wing
#

Cause there's a weird dot in code

#

Make sure it's normal I

vale wing
vague spade
#

I don't understand

quick gust
#

in your code add print(os.environ)

vale wing
#

Before the erroring line so it actually prints

vague spade
quick gust
#

what there is?

vale wing
#

According to screenshot you sent there's no

#

At least I only see traceback

vague spade
#

client = commands.Bot(command_prefix=os.environment['PREFİX'])

vale wing
#

Yeah you did add dot above I

#

Please just type normal I

quick gust
#

PREFIX

#

assuming thats whats in ur env

vague spade
#

I understand now

#

Thanks 😊

quick gust
#

^ 🙏

vague spade
vague spade
quick gust
unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

vague spade
#

I'm new to Python so I don't know much

quick gust
#

u missed this part

vague spade
#

@quick gust

hollow coral
#

Anyone free to help me out lil bit?

naive briar
#

Just ask

upbeat otter
leaden elbow
hasty gale
#

Hey guys how do i reset bot on discord. My commands wont show up

#

i have this weird problem where unless i kick a bot from my server the new commands dont show up

quick gust
#

have u tried restarting discord after u update the code?

whole wind
#

does someones knows if is possible to create a discord bot that execs a specific cell on a jupyter notebook in github codespaces? I have a minecraft server located in github codespaces, and i want to create a bot to start the server directly on discord without entering on github

viscid hornet
#

are these slash commands?

hasty gale
viscid hornet
hasty gale
#
from discord import app_commands
from discord.ext import commands
import os

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f"{bot.user.name}")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)
fiery girder
#

how do i make a discord bot that takes recording from your mic and plays it in a voice channel

viscid hornet
hasty gale
#

ok

viscid hornet
fiery girder
fiery girder
#

like duplicate commands

#

max commands reached

#

and more so its better to print errors if you dont have error handling

naive briar
#

If you get an error, it will be printed automatically

#

No need for any try-except

fiery girder
naive briar
#

print will print the exact same thing

hasty gale
fiery girder
#

not the traceback

naive briar
#

Oh right

#

But that makes everything even worse

fiery girder
#

i would prob print the formatted traceback

#

from the trackback package i think\

slate swan
#

recommendation: use setup_hook for syncing
better recommendation: make command for syncing

naive briar
fiery girder
naive briar
fiery girder
naive briar
#

It just adds more unnecessary code for no benefit or use

fiery girder
#

anyways i was wondering how i can make a bot that can use my mic in my computer and tranmit the voice to a discord voice channel

#

i made one before but it made recordings of 1 min in my computer then played then and then deleted them but i am trying to figure out how to do it without cause its a pain to wait 1 min

#

but most of the time it didnt even play it properly even tho the recording had audio it didnt played them

fiery girder
quick gust
naive briar
#

I remember py-cord being able to record sounds

#

They called those sinks

quick gust
quick gust
viscid hornet
naive briar
#

It was long ago

quick gust
#

ah

naive briar
#

Idk if it's still a thing

quick gust
#

interesting

fiery girder
quick gust
#

well I guess if you want to use pycord you could refer to this @fiery girder

fiery girder
#

i will not be in a voice channel

quick gust
#

like, itll play as you speak?

fiery girder
#

yes

quick gust
#

not sure if thats possible...

fiery girder
#

it is

#

i saw it in a vid but it didnt show the code

vivid holly
#

well if the bot is run locally, you can do that

fiery girder
quick gust
vivid holly
vivid holly
#

I haven't done exactly that so idk what libs you would need, but it's definitely possible

fiery girder
#

i got the audio from the mic but it isnt piping it in yor bot

fiery girder
#

@vivid holly this makes 1 min audio and plays it

#

but i want it live

vivid holly
fiery girder
fiery girder
#

its not working it just keep playing nonsense noices

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno -9998] Invalid number of channels
it litreely says int he discord.AudioSource that it should be stereo still its dooing this

fiery girder
vivid holly
fiery girder
#

yea lol

#

but it doesnt repay my audi

vivid holly
#

like not even a remote resemblence?

fiery girder
#

not

vivid holly
#

that is certainly weird, but then again, I have not done this so maybe it is just unusable

fiery girder
#

it doesnt even match the pitch

hasty gale
#

how do i fix this while still using discord.ext commands

mossy jacinth
#

im trying to make a speechbubble command but i dont know how to turn the speech bubble invisible so you can see the discord background instead of black.. i even asked chat gpt to make it invisible but that ofc just ruined the code so that didnt help at all and i also tried searching through google with no luck at all

I'm using cv2

@bot.slash_command(name="bubble", description="Add a speechbubble to a gif or an image.")
async def bubble(ctx: nextcord.Interaction, file: nextcord.Attachment):
    try:
        file_data = await file.read()
        img_user = cv2.imdecode(np.frombuffer(file_data, np.uint8), cv2.IMREAD_COLOR)
        img_bubble = cv2.imread('bubble2.png', cv2.IMREAD_UNCHANGED)
        img_bubble_resized = cv2.resize(img_bubble, (img_user.shape[1], img_user.shape[0]))
        _, _, _, alpha = cv2.split(img_bubble_resized)
        alpha_inv = cv2.bitwise_not(alpha)
        bubble_alpha_mask = cv2.merge([alpha_inv, alpha_inv, alpha_inv])
        img_content_cut = cv2.bitwise_and(img_user, bubble_alpha_mask)
        img_bytes = cv2.imencode('.png', img_content_cut)[1].tobytes()
        await ctx.response.send_message(file=nextcord.File(io.BytesIO(img_bytes), filename="adminhelper_speechbubble.png"))
    
    except Exception as e:
        print(f"Error: {e}")
viscid hornet
hasty gale
#
import discord
from discord.ext import commands
import sqlite3

#Database

bot = commands.Bot()

active=False

@bot.event
async def on_ready():
    print(f"{bot.user.name}")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)
viscid hornet
#

just put py synced = ... print(f"Synced {len(synced)} commands")

#

you wont get any traceback

#

do that and tell me the error that comes back

slate swan
#

I think syncing can raise errors

#

but in certain scenarios

viscid hornet
hasty gale
#

still gives an error next to tree

viscid hornet
hasty gale
viscid hornet
viscid hornet
hasty gale
#

idk

#

must be because of these damn databases

slate swan
#

maybe there are forks in the libs?

hasty gale
#

since i imported them i have problems

viscid hornet
viscid hornet
#

are you using dpy?

hasty gale
slate swan
#

Explains alot

viscid hornet
hasty gale
viscid hornet
#

thats probably your error

viscid hornet
hasty gale
viscid hornet
#

are you using discord.py or another library

hasty gale
#

OHHHHH

viscid hornet
hasty gale
#

ik now sorry im dumb

viscid hornet
#

that is weird ngl

viscid hornet
viscid hornet
#

should look like this (as example) py bot = commands.Bot(command_prefix = '!', intents = Intents.all())

viscid hornet
viscid hornet
#

this will fix the issue (change according to your preferences)

hasty gale
#

nope doesnt work

viscid hornet
hasty gale
viscid hornet
hasty gale
#
import random
import discord
from discord.ext import commands
import sqlite3

database = sqlite3.connect('data.db')
cursor = database.cursor()
database.execute("CREATE TABLE IF NOT EXISTS cars(car_name STRING, car_id INT)")

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

active=False

@bot.event
async def on_ready():
    print(f"{bot.user.name}")
    synced = bot.tree.sync()
    print(f"Synced {len(synced)} commands")

viscid hornet
#

his IDE might be tweaking ngl

hasty gale
#

i m using pycharm lol

viscid hornet
hasty gale
viscid hornet
viscid hornet
#

there was a slash command, @bot.tree.command()

viscid hornet
#

whats that? show it here

hasty gale
#
@bot.tree.command(name="claim")
async def ping(ctx):
  #script
viscid hornet
#

also thats supposed to take interaction, not ctx

#

@bot.command() for a prefix command

slate swan
#

this seems cursed

hasty gale
#
@bot.tree.command(name="claim")
async def ping(ctx):
    global active
    if active==True:
        car_name = "Porsche 911"
        await ctx.response.send_message(f"@{ctx.user.name} has claimed the car! The car is in your garage now!")
        query = "INSERT INTO cars VALUES (?, ?)"
        cursor.execute(query, car_name)
        database.commit()
        active=False
    else:
        await ctx.response.send_message("There is no car to claim!")
slate swan
#

how about you try bot.__tree.sync() or smth pithink

#

this is weird though since tree property should exist

slate swan
#

and what is the error?

hasty gale
slate swan
#

try __tree, not tree

hasty gale
#

doesnt work

slate swan
#

even though this seems so wrong

#

commands.Bot inheritates from discord.Client and BotBase class which has a tree property

#

that should return your app_commands.CommandTree

#

@pale zenith pithink

hasty gale
#

thgat i cant import it

shrewd apex
#

have you installed the latest discord.py? can you do pip show discord.py

viscid hornet
slate swan
#

are there for sure 0 forks?

shrewd apex
#

we shall know soon hopefully