#discord-bots

1 messages · Page 271 of 1

slate swan
#

what messagwe

sharp whale
slate swan
#

you assign the select callback after already sending the view

sharp whale
#

what

slate swan
#

you assign callback in this line selectmenu.callback = selectmenu_callback

and you send view in this line await interaction.response.send_message("Select a platform", view=view)

#

sending is before assigning

sharp whale
#

as a callback

slate swan
#

do you have any error handler?

#

that may be silencing your errors?

sharp whale
slate swan
#

and you have no errors in the terminal?

sharp whale
#

no

slate swan
#

can you do print(guild) before creating text channel?

sharp whale
#

okay

slate swan
#

code?

sharp whale
# slate swan code?
async def ticket_callback(interaction):
    guild = interaction.guild
    Moderator_role = guild.get_role(config.MODERATOR_ROLE)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.user: discord.PermissionOverwrite(view_channel=True),
        Moderator_role: discord.PermissionOverwrite(view_channel=True)
    }
    minecraftemojiID = "1127972711193391267"
    discordemojiid = "1127973464179998780"
    
    discordemoji = await interaction.guild.fetch_emoji(discordemojiid)
    minecraftemoji = await interaction.guild.fetch_emoji(minecraftemojiID)
    selectmenu = ui.Select(placeholder="Select a platform", options=[
        discord.SelectOption(
            label= "Minecraft",
            value="01",
            emoji = minecraftemoji
        ),
        discord.SelectOption(
            label= "Discord",
            value="02",
            emoji = discordemoji
        )
    ])
    view = ui.View(timeout=None)
    view.add_item(selectmenu)
    await interaction.response.send_message("Select a platform", view=view)
    async def selectmenu_callback(interaction):
        if selectmenu.values[0] == "01":
            print(guild)
            category = discord.utils.get(guild.categories, id=1130129162489827389)
            channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}", category=category, overwrites=overwrites)
            await interaction.response.send_message("Opened a ticket", ephemeral=True)
    selectmenu.callback = selectmenu_callback```
slate swan
#

error says this line caused the error await interaction.response.send_message(view=view) i dont see it here

sharp whale
#
@bot.tree.command(name="ticketmenu", description="Sends ticket menu")
async def ticketmenu(interaction):
    ticketbutton = ui.Button(label="Open Ticket", style=discord.ButtonStyle.primary, custom_id="ticketbutton")
    view = ui.View(timeout=None)
    view.add_item(ticketbutton)
    ticketbutton.callback = ticket_callback
    await interaction.response.send_message(view=view)```
#

how can this cause error

slate swan
sharp whale
#

what

slate swan
#

thats the issue you are getting

sharp whale
#

how do i fix it

slate swan
#

did you even read the github issue comments?

sharp whale
#

but other commands are working

#

ok nvm

#

i restarted the bot and the error gone now

#

the command works

sharp whale
slate swan
#

and what if you print channel

#

the varriable you get from creating

sharp whale
#

ok wait

sharp whale
#

ticket-trix

slate swan
#

So it got created

sharp whale
#
channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}", overwrites=overwrites)```
#

this works

#

but this doesn't

channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}",category=category, overwrites=overwrites)
slate swan
sharp whale
slate swan
#

you can just do category.create_text_channel(...)

sharp whale
#
category = discord.utils.get(guild.categories, id=1130129162489827389``` is this the problem?
#

nope

#

not working, same issue

sharp whale
#

oh

slate swan
#

print it out

sharp whale
slate swan
sharp whale
#

i did

#

same issue

slate swan
#

same issue meaning the channel is not created?

sharp whale
#

I checked everywhere

#

it should create the channel in the category

#

but its not creating it

slate swan
sharp whale
#

i dont even know why

slate swan
#

we do

slate swan
sharp whale
slate swan
sharp whale
sharp whale
turbid condor
#

you are trying to create a channel in a specific category?

turbid condor
slate swan
#

he is trying to create a channel in category. He gets no errors. If he doesnt pass category kwarg it is created category.create_text_channel(...) doesnt work as well simple as that

turbid condor
#

there is a category parameter in create text channel

slate swan
#

he is using that

#

but if he does pass it it wont work

turbid condor
#

is his category being returned?

slate swan
turbid condor
#

did you try the discord.CategoryChannel method?

#

!d discord.CategoryChannel

unkempt canyonBOT
#

class discord.CategoryChannel```
Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the category’s hash.

str(x) Returns the category’s name.
turbid condor
#

^

sharp whale
turbid condor
#

can u show the snippet?

turbid condor
sharp whale
#

.

turbid condor
#

weird

sharp whale
#

and it even returns the category name

#

but still the channel isn't getting created

turbid condor
#

that's the weird thing

#

you can try asking in discord developers server

sharp whale
#

idk why but i am

buoyant quail
#

Works fine by me

turbid condor
#

from there too

sharp whale
#

is it because of my server or what

buoyant quail
#

¯_(ツ)_/¯

sharp whale
#

the bot has all the intents

#

and admin perms

slate swan
turbid condor
#

check your dpy version then

sharp whale
turbid condor
#

now that's pretty wierd

#

for vitness it's working and not you

slate swan
#

check the action log

#

see what actually happens

#

or audit log

#

however is that called

buoyant quail
#
print(channel, channel.category)

gives the channel and category?

sharp whale
slate swan
turbid condor
slate swan
#

from your bot side the channel is being created

#

maybe something other is removing it

sharp whale
slate swan
#

expand it

turbid condor
sharp whale
#

listen

#

to me

slate swan
#

by expand i mean click the arrow on the right

sharp whale
#

I may or may not had the category closed

#

LMAO

slate swan
#

..

sharp whale
#

BRO IM SO STUPID

#

im really sorry

ember mango
#

Does anyone know how to fix this?

slate swan
ember mango
#

Error Wibsite or my code.

#

?

ivory crypt
#

My slash command seems to be registered twice. How can I solve it?

slate swan
golden portal
ivory crypt
#

My codes are now so long that I need to divide them into cogs or not it will be super inconvenient. Maybe I should give up to try this :(

hushed galleon
#

do you need that many commands in a single group?

#

i guess an alternative if you dont mind reloading a lot of code at once is to have the extension define the group and add commands to it in separate modules without cogs (imo this is even more unconventional than using other refactoring techniques)

buoyant quail
#

!d discord.ext.commands.Group.add_command

unkempt canyonBOT
#

add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.

This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.

Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")

Changed in version 2.0: `command` parameter is now positional-only.
buoyant quail
#

You can add commands in the group manually
But yeah what you are trying to do is weird

#

Commands from the same group logically would be in the same cog

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.

#
Empty JSON error

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

slate swan
#

also dont use requests in a discord bot

#

its blocking

#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

but the urls are supposed to return one

#

in simple terms:

  • you are trying to get data in json format from a website
  • website did not return json, returned error page instead (request failed)
  • you tried to convert it to json which failed
#

use aiohttp and check if the response status is okay

#

example here

left dew
#

is there anyway that i can avoid this?

ValueError: 'corrupt' is not in list```

```py
      if "corrupt" in details.lower():
        position = values.index("corrupt") - 1
        multiplier = float(values[position])
        price = multiplier * 8.65
        total_price.append(price)
      elif "corrupts" in details.lower():
        position = values.index("corrupts") - 1
        multiplier = float(values[position])
        price = multiplier * 8.65```
#

if i input corrupts, then it thinks ive inputted corrupt and throws an error

buoyant quail
#

You are checking in details.lower() and then indexing in values

#

These are two different variables

left dew
#

details is what is in my db column, values is that data but split

#

so they have the same data in them

naive briar
#

Same data? Like literally?

buoyant quail
#

print out details and values

left dew
#

details = 100,iceps,100,corrupts
values = ['100', 'iceps', '100', 'corrupts']

buoyant quail
#

ah ofc

#

"corrupt" is in that string

#

and "corrupts" is in that string

naive briar
#

!e

details = "Uwu corrupts owo"

if "corrupt" in details.lower():
    print("Corrupt")

elif "corrupts" in details.lower():
    print("Corrupts")
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

Corrupt
buoyant quail
#

just check for corrupts in the list

left dew
#

!e

details = "Uwu corrupts owo"

if "corrupts" in details.lower():
    print("Corrupt")

elif "corrupt" in details.lower():
    print("Corrupts")```
unkempt canyonBOT
#

@left dew :white_check_mark: Your 3.11 eval job has completed with return code 0.

Corrupt
left dew
#

ok got it

left dew
# buoyant quail just check for corrupts in the list

what about this, the abbreviations, which would i check first?

      if "icepiercers" in order_details.lower():
        position = values.index("icepiercers") - 1
        multiplier = float(values[position])
        price = multiplier * 8.45
        total_price.append(price)
      elif "icepiercer" in order_details.lower():
        position = values.index("icepiercer") - 1
        multiplier = float(values[position])
        price = multiplier * 8.45
        total_price.append(price)
      elif "iceps" in order_details.lower():
        position = values.index("iceps") - 1
        multiplier = float(values[position])
        price = multiplier * 8.45
        total_price.append(price)
      elif "icep" in order_details.lower():
        position = values.index("icep") - 1
        multiplier = float(values[position])
        price = multiplier * 8.45
        total_price.append(price)```
buoyant quail
#
if "word" in values:
    values.index
...
#

you don't need the order_details

left dew
#

ok

buoyant quail
#

But actually your code is doing some inefficient duplication of code

left dew
#

yea idk how to make it more efficient

buoyant quail
#

At least you could iterate over the words

for word in "ice", "icep", "icepir", ...:
    if word in values:
        position = values.index(word) - 1
        multiplier = float(values[position])
        price = multiplier * 8.45
        total_price.append(price)

Also you can maybe iterate just over the values instead of using in each time but can't say from that part of code

left dew
#

would that eliminate the errors ive been having?

naive briar
#

What errors

left dew
#

this is what happens if i input for example icepiercer and it thinks icep is in it and it cannot index the position

ValueError: 'corrupt' is not in list```
#

@naive briar

upbeat ice
#

!e ```py

x = [1, 3, 5]

y = x.index(5)

print(y)

unkempt canyonBOT
#

@upbeat ice :white_check_mark: Your 3.11 eval job has completed with return code 0.

2
left dew
potent spear
potent spear
upbeat ice
#

you also can make your life easier by storing your data in details as a list in your db instead of some concatenated string

left dew
upbeat ice
#

corrupt isnt in the list

left dew
#

it’s just an example that’s what happens

left dew
upbeat ice
#

corrupts is in your list corrupt is not

left dew
#

yes so it gives me a value errror cuz it thinks corrupt is in corrupts, and it cannot index the list

left dew
#

i will do

potent spear
#

this fixed EXACTLY what you want (that's what the if statement does)
and was suggested 45 mins ago...

left dew
#

that will fix my error?

upbeat ice
#

it gives you a value error because its not in the list

left dew
#

never mind

potent spear
#

don't blindly copy paste the code, try to understand it

upbeat ice
#

!e ```py

x = ["word", "ice", "corrupt"]

y = x.index("corrupts")

print(y)```

unkempt canyonBOT
#

@upbeat ice :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     y = x.index("corrupts")
004 |         ^^^^^^^^^^^^^^^^^^^
005 | ValueError: 'corrupts' is not in list
potent spear
#

seems like you didn't even read what the error you were having meant

left dew
#

i did understand it

#

i didn’t know how to fix it

potent spear
#

well, then you'd also understand that
if "corrupts" in <your_list>:
would mean that you'd only index if the word is in the list

upbeat ice
#

do you mean SelectOption?

#

are you using slash commands?

potent spear
#

ctx begs to differ

upbeat ice
#

select options are a part of app_commands or "choices" not sure what discord actually calls it

#

still, options are only available for interactions not context commands

#

well actually nvm

#

Im reading the docs for pycord

#

you sure you have pycord installed? @slate swan

#

and you are not in a venv?

left dew
upbeat ice
left dew
#
    position = values.index(word) - 1
ValueError: 'icep' is not in list```
#

my code:

      for word in "icepiercer", "icepiercers", "icep", "iceps":
        if word in order_details.lower():
          position = values.index(word) - 1
          multiplier = float(values[position])
          price = multiplier * 8.45
          total_price.append(price)```
#

i inputted iceps

upbeat ice
#

what is in order_details

left dew
#

100,harvs,100,iceps

upbeat ice
#

theres your problem

#

you have a string

left dew
#

should i be using values?

turbid condor
#

Make it a list

left dew
#

values = ['100', 'harvs', '100', 'iceps']

upbeat ice
#

you need to convert your order_Details to a list

turbid condor
#

Try and see

left dew
#

ok

upbeat ice
left dew
#

yess it worked

#

finallyyyy

upbeat ice
left dew
#

yes

#

it works

upbeat ice
#

youre starting your index at -1?

left dew
#

what was happening was it wasn’t giving me the correct value every time, so i just did -1 and it worked

upbeat ice
#

try it with the first word in the list

#

first item in values

left dew
#

yea works fine

upbeat ice
#

im not sure how lol

left dew
#

same but ill take it

upbeat ice
#

did you try with +1 instead of -1?

#

thats makes more sense to me

upbeat ice
#

!e ```py

x = [1, 2, 3]

y = x[-1]

print(y)```

unkempt canyonBOT
#

@upbeat ice :white_check_mark: Your 3.11 eval job has completed with return code 0.

3
left dew
#

oh

ornate sapphire
#

anyone know how to put a timer on an on_message event?
I want to do an event that when I say something the bot responds like normal... but you cant run the command again for a certain amount of time

buoyant quail
#

You are doing commands in on_message? brainmon

proper thicket
#

how would i run this cmd on macbook

slate swan
#

like you would do on windows

#

in terminal

#

also dont use requests within a discord bot

#

it is blocking

proper thicket
#

also its for roblox api

slate swan
#

try pip3

slate swan
proper thicket
slate swan
#

instead of requests?

proper thicket
slate swan
proper thicket
#

so install requests correct?

slate swan
#

you can but i dont recommend

proper thicket
#

why?

slate swan
#

it will be synchronous

proper thicket
#

oh

slate swan
#

meaning slower

proper thicket
#
   response = requests.get(f"https://api.roblox.com/users/get-by-username?username={roblox_username}")```
slate swan
#

you have example here how to convert requests to aiohttp

proper thicket
#

alr thanks

slate swan
proper thicket
slate swan
proper thicket
upbeat ice
#

You can run requests in an executor

ornate sapphire
#

just how do I put a timer on an on message

slate swan
#

what do you mean timer?

ornate sapphire
# slate swan what do you mean timer?

when I say the key word the bot responds like normal. but I want it so if i try and do it again it will only work again in a certian amount of time

slate swan
#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
buoyant quail
#

xd

slate swan
#

ah again in amount of time

#

then use cooldowns or sum

#

but if its in on message may be hard

buoyant quail
#

just use commands with built-in cooldowns lol

#

don't implement everything by yourself with on_message

#

and then you can apply cooldown on it

pure sparrow
#

Hi guys, I was wondering if it was possible on discord.py to mention commands in a embed please ? because I only find programs on discord.js... thanks have a nice day

sick birch
#

For instance: </tag:1079848585027399791> becomes </tag:1079848585027399791>

pure sparrow
#

omg thanks

#

and I get the id in discord developper portal ?

sick birch
#

You can just copy it from the client

#

If you right click on the dark gray area above the text box

pure sparrow
#

alright, thank you soo much robin for your help

sick birch
#

no worries

hushed galleon
plucky sun
#

How to add space in slash command name ?

#

@sick birch

sick birch
plucky sun
#

How come there are random bots in someone?

#

@sick birch

sick birch
thin raft
ornate sapphire
#

2 different people can do it but not the same

upbeat ice
ornate sapphire
#

idk how to do a cooldown

ornate sapphire
#

hehehe

upbeat ice
#

You wouldn't do this in on message

ornate sapphire
#

ya reallized that

ornate sapphire
# upbeat ice You wouldn't do this in on message
@client.command()
@commands.cooldown(1, 10, commands.BucketType.user)
async def foo(ctx: commands.Context):
    await ctx.send("Success!")```
I copied what the link you sent said to see if it worked... and it didnt
upbeat ice
#

What's your error

ornate sapphire
#

dont get one

#

just doesnt respond

upbeat ice
#

Show your file

ornate sapphire
#

this is what I use for testing

#

so thats all I have

upbeat ice
#

Do any of your cmds work

ornate sapphire
#

no

#

T-T

upbeat ice
#

Comment outyour on message event for now and try

ornate sapphire
#

asyeee

#

it worked

#

idk why

#

but how do I adjust the cooldown time??

upbeat ice
#

You need to add await client.process_commands(message) to the end of that function

upbeat ice
#

No that goes in on_message

ornate sapphire
upbeat ice
#

The 1 is the rate and 10 is per

ornate sapphire
#

also it doesnt respond when its on cooldown to the command... when I do it the bot just doesnt respond

upbeat ice
#

It raises an error that you'll have to catch now

ornate sapphire
#

so to catch it waht do I do?

#

im new okay still learning

upbeat ice
#

Create a function called on_command_error

#

Takes two parameters ctx and error

buoyant quail
#

and you are doing absolutely nothing in on_message so you can just remove it

ornate sapphire
#

so if I add the code im working on now those wont work

#

I did this and it doesnt work

buoyant quail
upbeat ice
#

The last line shouldn't be under the if statement

ornate sapphire
#

so like this?

buoyant quail
#

ye

ornate sapphire
#

it worked! but now back to the command...

#

I have the cooldown working but I want it to say how much time remaining you have left when you try and do it again

upbeat ice
#

you can send the error back in your error handler

buoyant quail
ornate sapphire
ornate sapphire
#

but the part that says foo.error I replace foo with the name of my command right?

buoyant quail
buoyant quail
ornate sapphire
upbeat ice
#

you can also do error.retry_after instead of hardcoding it

ornate sapphire
upbeat ice
#

and send it in an f string

#

f"You are on cooldown. You need to wait {error.retry_after} to use that command."

ornate sapphire
#

is their a way for it to not show all those extra numbers?

upbeat ice
#

you can add {error.retry_after:.2f}

buoyant quail
#
{error.retry_after:.1000f}

ducky_vader

ornate sapphire
#

I actually did lmao

upbeat ice
#

lmao

#

precision

#

although interesting it gives up after a few decimal spots

ornate sapphire
upbeat ice
#

i think you just have to represent the hours in seconds

buoyant quail
upbeat ice
#

so your parameters are (1, 3600, w/e)

ornate sapphire
buoyant quail
#

instead of your current 5 seconds cooldown

#

or anywhere you want

ornate sapphire
#
hour=60*60 seconds
@client.command()
@commands.cooldown(1, 60, commands.BucketType.user)
async def foo(ctx: commands.Context):
    embed=discord.Embed(title="test", description="it worked!", color=discord.Color.red())
    await ctx.send(embed=embed)```
like this?
buoyant quail
#

i'll just spoonfeed...

@client.command()
@commands.cooldown(1, 3600, commands.BucketType.user)
async def foo(ctx: commands.Context):
    embed=discord.Embed(title="test", description="it worked!", color=discord.Color.red())
    await ctx.send(embed=embed)

it's one hour

ornate sapphire
#

not how many seconds left

upbeat ice
#

you would need to convert it back to hours

buoyant quail
upbeat ice
#

classic programming 101 problem

ornate sapphire
#

yes... but how

buoyant quail
#

Go without programming

You have 31245 seconds
How will you find out how many hours is it?

#

Like just in words

#

maths ducky_sphere

ornate sapphire
#

imma just make the error say... "your on six hour cooldown before you can use the command again" instead of the exact

#

make life easy

buoyant quail
upbeat ice
#

Don't do that

ornate sapphire
upbeat ice
#

They could run the command with one hour left and it will always says 6

buoyant quail
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
buoyant quail
#

the answer is there in the documentation of send method.
you should find out what to use by yourself

ornate sapphire
#

im a genius... but how do I make it 5 seconds

buoyant quail
#

you already did

ornate sapphire
#

oh yayyyy

#

I take back the genius thing

#

everything works! thanks guys

ornate sapphire
#

how do I make the command only work in a specific channel

#

Ik how to do it on an on_message but idk how to do a command

buoyant quail
#

You can just add if in the beggining of the function
Or you can make a custom check and apply it

buoyant quail
#
@bot.command()
async def foo(ctx):
    if ctx.channel.id == ...:
        await ctx.send("ok")
#
def in_channel(ctx):
    return ctx.channel.id == ...


@bot.command()
@commands.check(in_channel)
async def foo(ctx):
    await ctx.send('ok')
ornate sapphire
#

channel would be undefined right? I would have to do
channel=(my id)

buoyant quail
#

as the second value to compare

ornate sapphire
#

would it work only in that channel?

buoyant quail
#

yes

ornate sapphire
#

this didnt work. No errors just didnt respond

#

wait nvm

#

I spelt it wrong

#

heheheh sorry

buoyant quail
#
  1. It's not similar to the any of two codes i gave
  2. You need to cast channel id to string or your ids to integers
  3. To check for a value in a list you can't use ==. It is comparing
ornate sapphire
buoyant quail
#

What do you have now

ornate sapphire
#

oh waittttt why do I have return instead of if

buoyant quail
#

You can check negative and do return

#
@bot.command()
async def foo(ctx):
    if ctx.channel.id != ...:
        return
    await ctx.send("ok")
ornate sapphire
#

ohhhh

#

still works in all channels

upbeat ice
#

anyone know if there is a way to determine if an interaction has been deferred

ornate sapphire
#

is this number 2?

buoyant quail
#

nope

ornate sapphire
buoyant quail
#

It won't even run

ornate sapphire
#

cmonnnn

ornate sapphire
buoyant quail
unkempt canyonBOT
buoyant quail
#

maybe this? it would be some of these. but i am not sure

ornate sapphire
upbeat ice
#

ohh maybe this

buoyant quail
ornate sapphire
#

YES

ornate sapphire
buoyant quail
#

no

ornate sapphire
buoyant quail
#

Then you need to learn something new

#

== is not enough

ornate sapphire
#

OH WAIT

#

is it in?

buoyant quail
#

ye

ornate sapphire
#

hehehehe

#

I did know that one hehehehhe

ornate sapphire
buoyant quail
#

what's the current code?

ornate sapphire
buoyant quail
ornate sapphire
#

BROOOOO In my real code I have an on message one with a list of channels that it only works in... but I watned it to work in every channel accept one. But I didnt know how so I just made it only work in ALL the channels

#

when I COULDA JUST DONE WHAT I JUST DID

buoyant quail
#

uh?

ornate sapphire
#

idk

#

but how do I get it to work

buoyant quail
#

make an opposite condition

ornate sapphire
#

can I take away the return?

buoyant quail
#

or like this and put the code inside if

ornate sapphire
#

I do that with { that right?

buoyant quail
#

do what

ornate sapphire
#

to put the code inside if I surrouned it with this symbe {?

buoyant quail
#

you learned some other language?

ornate sapphire
#

did I?

buoyant quail
#

no, for that you use indentation in python

ornate sapphire
#

ohhhh

buoyant quail
ornate sapphire
#

hehehe

ornate sapphire
buoyant quail
#

not exists

#

not False = True
not True = False

ornate sapphire
#

@buoyant quail this time it worked in all of them. (even the specified channels)

buoyant quail
#

current code

ornate sapphire
buoyant quail
#

works in all channels?

ornate sapphire
#

ya

buoyant quail
#

rerun the code

ornate sapphire
#

same thing

#

oh wait

ornate sapphire
# buoyant quail rerun the code

I dont use commands I only use on message. I made a help message that the bot responds to and gives info... But now that I added a command I get the one I made. And the built in help

#

how do I fix that

buoyant quail
#

how to remove built in help?

ornate sapphire
#

ya

buoyant quail
#
client = commands.Bot(..., help_command=None)
ornate sapphire
#

do I just take away the prefix?

buoyant quail
#

no

#

add the help_command=None

ornate sapphire
#

ah ok thx

ornate sapphire
upbeat ice
ornate sapphire
ornate sapphire
upbeat ice
sick birch
upbeat ice
#

^that seems right

ornate sapphire
sick birch
ornate sapphire
#

instead of worrying about that. How do I make the bot send a message in a different channel when you say something

ivory crypt
#

Is there any way to get the amount of subcommands under a command group?

slate swan
#

len(group.commands)?

slate swan
sick birch
#

yes

slate swan
sick birch
#

no

slate swan
#

Only in servers?

sick birch
#

only in large server so far it seems

slate swan
sick birch
#

I think they're rolling it out slowly

#

This server has it but some others im in don't

slate swan
#

Ah that's cool

near slate
#

Hey so I wanted to update todays date in my python bot code every 5 mins, is there any way I can achieve it?
I have already made a function to get todays date

vocal snow
#

Update it where?

#

And why do you need to update it every 5 minutes? The date changes every 24 hours

near slate
vocal snow
torn solar
#

is it possible to make custom options for a slash command argument

vocal snow
#

Yes

#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
near slate
#

theres a list of dates on which I want my bot to run

#

So for that I have to check daily right

vocal snow
#

Just check before you process commands

near slate
#

like a reminder

vocal snow
#

Override the bots on_message event and call bot.process_commands only if the current date is a valid date

near slate
#
import os
import discord
from get_date import get_date

TOKEN = os.environ['BOT_TOKEN']

client = discord.Client(intents=discord.Intents.all())



@client.event
async def on_ready():
  print(f"Logged in as {client.user}")


@client.event
async def on_message(message):
  if message.author == client.user:
    return
  if message.content.startswith("?h"):
    await message.channel.send("Hello")
  if message.content.startswith("?p"):
    await message.channel.send("Ping")


client.run(TOKEN)
from datetime import date


def get_date():
  today = date.today()
  today_date = today.strftime("%d %m %Y")
  return today_date

get_date.py

#

What I was thnking of doing was to check date after a certain time interval and if it matches a date then it will do certain commands

torn solar
#

i think datetime.now() works fine

buoyant quail
#

now it's again appearing somewhere

slate swan
#

but bots can use it anyways

rugged shadow
vale wing
naive briar
slate swan
#

does it also warn you when its redirecting to discord site

#

apparently not

#

or i have it whitelisted

thin raft
#

why would it tho

slate swan
#

could be for every link

potent light
#

oh the embed looks ugly

vocal laurel
turbid condor
#
[Text](<link>)
vocal laurel
#

Oh ok

turbid condor
#

That suppresses the embed

vocal laurel
#

Isn’t there like a cross on the top right if embed to remove tho

#

I swear there was one before

turbid condor
vocal laurel
#

Oh ok

turbid condor
#

I don't see any cross

vocal laurel
slow fog
#

It's not working for me

#

no hyperlinks

turbid condor
#

It's not working in all servers

#

For now that is

naive briar
#

What do you mean not working? If you mean Discord isn't making the [Text](URL) a hyperlink, it's because it's still rolling out

copper gulch
#

Im so confused rn, which is the actual original way of doing discord.py buttons

vocal laurel
vocal laurel
copper gulch
vocal laurel
#

Hold up

turbid condor
# copper gulch anyone knows the docs for the discord.py buttons

If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit

You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

turbid condor
vocal laurel
turbid condor
#

i once tried refering ppl to that server but for some reason my url were getting blocked

vocal laurel
#

Was about to do then saw u do it and knew it was for this

vocal laurel
turbid condor
#

so i stopped sending server invite link

vocal laurel
#

Which u kinda were

vocal laurel
#

Or they should add R. Danny

turbid condor
#

that would actually help alot

vocal laurel
#

Exactly

#

Just using tags here would be so useful

vocal snow
#

There are tags here for common things

#

And you can add your own as well

vocal laurel
turbid condor
#

but will need to recreate tags that danny uses

vocal laurel
#

There is one for like everything

vocal laurel
turbid condor
turbid condor
#

especially the !d command

vocal laurel
#

Mhm

slate swan
#

What does this mean?

turbid condor
ember mango
#

Well, why is most bot economy built in JavaScript????

vale wing
ember mango
vale wing
#

You can create whatever discord bot with python

ember mango
vale wing
#

"Economy" is just having a database

#

It's not about language

ember mango
vale wing
turbid condor
#

learn SQL first

ember mango
turbid condor
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vale wing
turbid condor
#

or u can check w3schools

ember mango
turbid condor
vale wing
#

Bro why tf 90% of recommended bots on top.gg are anime, I'm trying to do market research

turbid condor
#

XD

slate swan
#

bot developers are weebs, I guess

turbid condor
#

but i guess they will also fetch anime bots

vale wing
turbid condor
#

thought so

#

cuz anime bots are widely used

#

you can use some other platform

vale wing
#

I tryna figure out if bobux bot is unique

turbid condor
#

Good luck figuring

slate swan
#

Has anyone made a discord for listing hypixel skyblock accounts where it displays all of the stats and you set price/payment method

turbid condor
#

Try searching git hub for that

slate swan
#

its SkyHelper

#

Couldn’t find any

#

support server: fd4Be4W

#

Sky helper will tell you your stats

#

I want to list accs for sale in my server

#

accounts for sale?

#

Like this bot

#

then no and we wont help with it its against hypixel tos

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

slate swan
#

That’s crazy

slow fog
#

is it really against hypixel's tos

safe trail
#

there's probably an API to get this data but other than that I don't have much clue on this

slow fog
#

never mind

safe trail
slate swan
#

buying/selling accounts is against minecraft tos anyways

slow fog
#

yes

slate swan
#

Well it is for educational purposes

#

But I figured it out

#

It’s easy with hypixel api

buoyant quail
#

I robbed a bank for educational purposes

slate swan
left dew
#

when using this code

      for word in "corrupt", "corrupts":
        if word in values:
          position = values.index(word) - 1
          multiplier = float(values[position])
          price = multiplier * 8.65
          total_price.append(price)

it appends the price to total_price, however when i input a new order with different items, it seems to print the total of all the orders ive inputted. how do i make it print the total price for just the ones ive inputted? do i need to do total_price.clear()?

upbeat ice
#

If you want to remove all of the items from the list then yes, you can do that

turbid condor
slate swan
#

thats like 10 years huh

turbid condor
#

Can reduce it to 3652 days

#

Now it's less then 10 years

slate swan
civic reef
turbid condor
civic reef
#

wdym?

turbid condor
civic reef
#

still this error

thin raft
civic reef
#

me

thin raft
#

show code

civic reef
#
import discord

intents = discord.Intents.all()

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Bot is Online & ready to work!!')

@client.event
async def on_message(message):
    if message.author == client.user :
        return
    
    print("Message content:", repr(message.content))
    if message.content == 'hey' :
        await message.channel.send('hellooo')

client.run('TOKEN')
#

message.content string is empty

thin raft
#

!intents

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.

civic reef
civic reef
warm coral
#

hi

#

i want to learn how to code discord bots

#

can someone help

turbid condor
#

Do you know python basics and oop?

warm coral
#

ik python

#

oriented object programming or oop idk it

#

idk how to code with it

#

and i dont even know what its name

#

meaning*

turbid condor
#

Welp u will need knowledge about it too

#

If you want to create discord bots

warm coral
#

ik python basics

#

but im not advanced

#

like print or loop or elif or else

#

these things yk

upbeat ice
warm coral
#

ty

upbeat ice
#

heres some reading for you

warm coral
#

ty

#

i can use repl it and uptime to host my bot right?

#

@upbeat ice

upbeat ice
#

probably should start with the basics first before worrying about hosting

warm coral
#

ok

turbid condor
warm coral
#

what can i use ?

#

node?

turbid condor
#

discloud, daki

warm coral
#

what is this

turbid condor
#

Tho they also use shared ip

#

But the machines are bit more powerful than replit

turbid condor
warm coral
#

ok

#

i just got into the introduction :
import discord

class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')

async def on_message(self, message):
    print(f'Message from {message.author}: {message.content}')

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

client = MyClient(intents=intents)
client.run('my token goes here')

#

and i dont understand

warm coral
#

i gotta go anyways

nimble mirage
#

anyone got docs for slash commands

upbeat ice
cloud dawn
nimble mirage
upbeat ice
#

enjoy

cloud dawn
cloud dawn
potent spear
#

I think there are docs, but they're in development... 👀
so not in the "main" branch of dpy's gh

left dew
#

if i input harvs, then it prints 2x the price, anyone know how to stop it from happening?

      for word in "harvester", "harvesters", "harv", "harvs":
        if word in values:
          position = values.index(word) - 1
          multiplier = float(values[position])
          price = multiplier * 8.50
          total_price.append(price)```
slate swan
#

Is there anywhere I can host my python discord bot for free

buoyant quail
buoyant quail
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

[8.5]
left dew
unkempt canyonBOT
#

@left dew :white_check_mark: Your 3.11 eval job has completed with return code 0.

[8.5]
left dew
#

huh

#

seems to work now

#

no clue what was wrong with it before

abstract kindle
#

is it possible to change a users focus? like what text channle they're on? Or is that client side

slate swan
#

unless the channel is removed

abstract kindle
#

yeah, I'm deleting a channel, but I want them to be redirected to another channel

#

But I don't think I can do that

#

I wish I could handle a user clicking on a channel mention, but I can't do that either

slate swan
abstract kindle
#

yeah. its for a party invite system. I create a temp channel with a party invite for them, and if they clicked join I wanted it to redirect them to the party channel and delete the invite channel.

slate swan
#

then give them a jump url to follow

void mauve
#

So my issue is that after slash command /help bot responding with 'APP DIDNT RESPOND', how do i get rid of that? (Command works and output is correct, sent to a text channel where command was mentioned)

import discord
import pyuac
from discord import app_commands
from datetime import datetime, timedelta
from config import token, GUILD_ID


SnoopRat_icon = 'https://i.ibb.co/sPZ0TDD/images.png'

bot_token = token

intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)


def console_msg(msg):
    print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] [Console]: {msg}')


@tree.command(name="help", description="Shows a list of commands.", guild=discord.Object(id=GUILD_ID))
async def help(ctx):
    embed = discord.Embed(title="SnoopRat Bot",
                          description="__SnoopRat client information tab__\n\n> Supported commands\n"
                                      "\n**Developers**\n@void mauve",
                          colour=0x00b0f4,
                          timestamp=datetime.now())
    embed.set_thumbnail(url=SnoopRat_icon)
    embed.set_footer(text="SnoopRat",
                     icon_url=SnoopRat_icon)

    await ctx.channel.send(embed=embed)

def main():
    client.run(bot_token)


if __name__ == "__main__":
        main()
thin raft
#
@tree.command(name = "help")
async def help(interaction: discord.Interaction):
  await interaction.response.send_message("Hello, World!")
slate swan
thin raft
void mauve
# thin raft np

I have another issue now 😄 So basically Im using function to find channel by its name, but how do i make sure interaction was made in a channel where command was called (e.g. i have seperate channel for commands and seperate channel for screenshots)? It appears to be the same error mesage 'APP DIDNT RESPOND'.

def find_channel(name):
    return discord.utils.get(client.get_all_channels(), name=name)


@tree.command(name="ss", description="Takes a screenshot and sends it", guild=discord.Object(id=GUILD_ID))
async def screenshot(interaction: discord.Interaction):
    output_file = os.path.join(outputdir, f"screenshot_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.png")

    with mss.mss() as sct:
        monitor = sct.monitors[0]
        sct_img = sct.grab(monitor)

        mss.tools.to_png(sct_img.rgb, sct_img.size, output=output_file)

    await find_channel("📷-screenshots").interaction.response.send_message(file=discord.File(output_file))
    os.remove(output_file)
thin raft
#

it doesn't work like that

#

a channel doesn't have an interaction attached to it

void mauve
#

oh ic, so how should i rewrite it

slate swan
#

if you want to send a message to a channel you just do channel.send

#

when you have TextChannel object

#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
void mauve
#

ok, thanks for help again

coral mirage
#

Hello, I need help.

#

I'm trying to host my bot in sparked hosting, but apparently is not getting my database. I imported my database, but it catches as a file.

#

Does any one knows how to install the bot correctly with database in sparked host.

#

??

buoyant quail
#

uhm what

#

first, what database is it?

coral mirage
thin raft
#

SQLite is a file

buoyant quail
#

sqlite database is a single file

slate swan
#

are you using .db file?

coral mirage
coral mirage
coral mirage
buoyant quail
#

wdym not getting it?

#

who is not getting

#

what are you doing

coral mirage
#

when I run it in my pycharm everything works, but it doesn't in the host.

buoyant quail
#

hosting issue ig ¯_(ツ)_/¯

#

you tried to reupload it?

coral mirage
slate swan
#

why dont you use intergrated Databases they give you

coral mirage
slate swan
#

what is php

buoyant quail
#

php is a programming language

#

it can't be a database

slate swan
#

man im not asking what php is

#

😭

#

what is in php i shouldhave asked

buoyant quail
coral mirage
#

I got confuse. I'm just trying to master python so I havent look out of the box yet.

buoyant quail
coral mirage
#

hey guys thank you for your time you guys take to reply.

Can you tell me which one I should chose?

slate swan
#

the one closest to you i would say

#

those are locations of the servers

coral mirage
#

I dont see it. I'm from Texas

buoyant quail
#

Doesn't matters ig
But you'd choose the nearest one to the your bot's server for speed

#

Just take europe

torn solar
#

im getting this error

#
@commands.is_owner()
async def setupAccounts(ctx: commands.Context):
    await ctx.message.delete()
    embed = discord.Embed(title="Accounts Info",
                          color=cb_color,
                          description="""Chase Bank offers a multitude of services when it comes to commercial banking.
                          We offer two different types of accounts for those who bank with us.
                          
                          **ACCOUNTS**
                          
                          Checking Accounts
                          > Chase's Checking Accounts are a smart and easy way
                          > to hold money that you can withdraw at any time. Money
                          > from Checking Accounts are not invested in any way.
                          
                          Checking Accounts Rates
                          > $10 withdrawal fee
                          > $100 monthly account fee
                          > $100 account closing fee
                          > Withdraw and deposit as many times as you want
                          
                          Savings Accounts
                          > Chase's Savings Accounts are a risk-free way to
                          > hold large amounts of money. Money from your Savings
                          > Account is subject to be invested for company purposes.
                          
                          Savings Accounts Rates
                          > $50 withdrawal fee
                          > $100 monthly account fee
                          > $100 account closing fee
                          > Withdrawals are only allowed once a week""")
    await ctx.send(embed=embed)```
slate swan
#

and where is that code located?

torn solar
#

its not nested or anything if thats what your asking

slate swan
#

im asking where is that

#

in what file

torn solar
#

my main file

#

all my code is in 1 file its sloppy

buoyant quail
#

send full code mb?

slate swan
#

dang

#

!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
#

any idea why its saying that cus my other commands r working

#

could it be the is_onwer()

buoyant quail
#

with such context that command should exist

upbeat ice
buoyant quail
#

is owner won't give you CommandNotFound

slate swan
#

share the code so we can inspect it

torn solar
buoyant quail
#

without token..

#

:p

torn solar
#

idc

#

ill just reset it later and i doubt you guys will do anything

#

the command starts on line 235

slate swan
#

everything looks fine

#

did you restart the bot after adding this command?

torn solar
#

yeah

#

restarting again now

#

to see if it didnt restart

#

aww fuck somebody nuked my server

buoyant quail
#

xddd

upbeat ice
#

Lmao

buoyant quail
#

it was fast

slate swan
#

did not take someone long skull

torn solar
#

its fine my server has like 15 people and not many channels

#

whoever did that just wasted time lol

#

the dumbass who nuked it made all the channels private

#

nobody got the pings 💀

coral mirage
#

So, the database it runs is MySQL.

thin raft
#

mysql is a database that requires hosting it, and connecting to the server for accessing it

#

sqlite is just a file, whoever has access to that file can do anything with the database

#

wait, idk if I was speaking to the correct guy

#

where you asking before some stuff from sqlite?

coral mirage
#

sqlite3.DatabaseError: database disk image is malformed

so why this comes out when I run it?

thin raft
#

the database is corrupted

coral mirage
thin raft
#

it is not usable

shrewd apex
#

it means that db is dead

torn solar
#

whoever nuked me needs to work on their skills cus u did a really shit job

#

🤣

thin raft
#

are you using a previous database?

coral mirage
thin raft
#

try creating one from scratch

coral mirage
#

😦

shrewd apex
#

why sqlite with discord bots

#

thats how it got corrupted in first place probably

coral mirage
shrewd apex
#

u tried and async/concurrent write on it prolly

thin raft
coral mirage
thin raft
#

create a new database file

#

although you should look on using mysql

slate swan
#

the sqlite3 one is blocking try using async library also

thin raft
#

that the hosting provides

shrewd apex
#

u create a new .db file but still unideal

#

use asynpg / aiosqlite / aiomysql

thin raft
#

what do you guys call your sqlite's database something.db or something.sqlite3?

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

buoyant quail
#

actually i call it just .sqlite

slate swan
shrewd apex
#

same

coral mirage
thin raft
#

which database do you guys use?

shrewd apex
#

i didn't know you could call it .sqlite3 till today

upbeat ice
coral mirage
#

hey guys, but I do use my async

shrewd apex
slate swan
buoyant quail
shrewd apex
#

if python i use postgres / mongodb
if js or ts i use something like firebase / mongo db / or some cms

coral mirage
#

I knew I should study mysql isntead of sqlite aghh.

shrewd apex
thin raft
shrewd apex
slate swan
shrewd apex
#

only place holder changes

slate swan
buoyant quail
#

sure, it's sqlite

coral mirage
thin raft
slate swan
shrewd apex
#

there are db viewers

thin raft
coral mirage
#

this is easy to use

slate swan
buoyant quail
#

Such exist for any database

shrewd apex
#

he prolly means viewers which visualise sql tables

slate swan
#

db browser works for sqlite for sure i used it as well

shrewd apex
coral mirage
thin raft
slate swan
buoyant quail
#

missed reply 😛

coral mirage
slate swan
#

only i dont use it ok ?

coral mirage
slate swan
#

yes

thin raft
coral mirage
#

alright let me do some changer.

buoyant quail
slate swan
#

not sure if dbbrowser supports it but other apps sure

thin raft
#

I use DataGrip, idk if it's free

shrewd apex
#

jetbrains comes with a bunch of stuff out of the box thats the cool part vs code ppl will say u can install extensions and whatever but those all still take time to setup compared to out of the box support and long term support by jetbrains itself

torn solar
#

down did u ever see anything wrong with the code that would makje the command not found

torn solar
#

did u test it when u nuked me

#

jk

buoyant quail
#

i didn't nuke :p

torn solar
#

the nuker was an idiot

slate swan
coral mirage
#

whats a nuker?

torn solar
#

he banned everyone (15 people) before pinging everyone

shrewd apex
#

ok bro we know 3rd time ur telling

torn solar
#

asher u look suspicious

shrewd apex
#

ok

slate swan
#

🧐

shrewd apex
#

i took over discord api brainmon

thin raft
torn solar
#

it was definitely u

coral mirage
thin raft
#

yeah I don't have anything better to do

shrewd apex
#

its meh but it's better than nothing

coral mirage
coral mirage
shrewd apex
#

cant wait*

coral mirage
#

fix

#

Alright Thank You guys for your help!
@shrewd apex @slate swan @buoyant quail @thin raft

thin raft
#

np

coral mirage
#

I did db all over inside host and it work!

#

what you can recommend me to save back up db files incase this inccident happens again.

warm coral
#

Hello

#

Im back again

void mauve
#

While calling this function console gives out an error message discord.app_commands.errors.CommandInvokeError: Command 'rec' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction and embed is not sent, what should i do in order to fix the issue?

@tree.command(name="rec", description="Records the screen for a specified duration", guild=discord.Object(id=GUILD_ID))
@app_commands.describe(duration="Video length")
@app_commands.rename(duration='duration')
async def screenrecord(interaction: discord.Interaction, duration: app_commands.Range[int, 0, 25]):
    output_file = f"{outputdir}rec_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.mp4"
    fourcc = -1

    frame_rate = 20.0
    frames_captured = 0

    screen = screeninfo.get_monitors()[0]
    screen_size = (screen.width, screen.height)
    out = cv2.VideoWriter(output_file, fourcc, frame_rate, screen_size)

    while frames_captured < (duration * frame_rate):
        with mss.mss() as sct:
            img = sct.grab(sct.monitors[1])

        frame = np.array(img)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        out.write(frame)
        frames_captured += 1

    out.release()
    cv2.destroyAllWindows()

    await find_channel("💻-screen").send(file=discord.File(output_file))

    embed = discord.Embed(title="Recording has been made!",
                          description=f"Check it out at <#{find_channel_id('💻-screen')}>",
                          colour=embed_color,
                          timestamp=datetime.now())

    embed.set_footer(text="SnoopRat",
                     icon_url=SnoopRat_icon)

    await interaction.response.send_message(embed=embed)

    await asyncio.sleep(5)
    os.remove(output_file)
potent spear
#

why? you may ask

void mauve
#

because my recording function is way longer than 3 seconds