#discord-bots

1 messages · Page 363 of 1

quick gust
#

in guild.members*

upbeat otter
#

yeah sorry

slate karma
#

my bot isn't responding on discord this is the code:
https://paste.pythondiscord.com/2QFA
I get this on my cmd:

[2024-05-08 14:50:00] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
[2024-05-08 14:50:00] [INFO ] discord.client: logging in using static token
[2024-05-08 14:50:01] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: df02e9c7af814420779c9fd726debdf1).
roblox has connected to Discord!

I have enabled the settings on discord dev portal but yet no respond.

fast osprey
#

You're not requesting it in code

slate karma
fast osprey
#

You need to enable the message_content flag on the Intents object you're passing into your bot

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

viscid hornet
#

what you're looking for is in the codeblock

slate karma
slate karma
# viscid hornet new error?

still getting this:
[2024-05-08 15 11 38] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
[2024-05-08 15 11 38] [INFO ] discord.client: logging in using static token
[2024-05-08 15 11 39] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 3530980cfef0825cd05cb4df16be243c).
roblox has connected to Discord!

viscid hornet
slate karma
viscid hornet
slate karma
viscid hornet
#

its like if i did this

#

!e py a = 5 a = 19 print(a)

unkempt canyonBOT
#

@viscid hornet :white_check_mark: Your 3.12 eval job has completed with return code 0.

19
viscid hornet
#

thats the same as this

#

!e py a = 19 print(a)

unkempt canyonBOT
#

@viscid hornet :white_check_mark: Your 3.12 eval job has completed with return code 0.

19
slate karma
#

oh bruh which ones do i need to remove?

viscid hornet
#
intents = ...
intents.something = True
intents.something_else = False```
slate karma
viscid hornet
#

you’re writing intents then overwriting it

slate karma
viscid hornet
slate karma
drifting arrow
#

I want to setup a command that uses dates. Is there a better setup than this:
/search day:XX Month:XX, Year:XXXX

viscid hornet
#

!d datetime.datetime.strftime

unkempt canyonBOT
#

datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.isoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat).
viscid hornet
#

oh wait its strptime

drifting arrow
#

But that's not for a python command param

viscid hornet
#

!d datetime.datetime.strptime

unkempt canyonBOT
#

classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) corresponding to *date\_string*, parsed according to *format*.

If *format* does not contain microseconds or timezone information, this is equivalent to:

```py
datetime(*(time.strptime(date_string, format)[0:6]))
```  [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime) or if it returns a value which isn’t a time tuple. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.fromisoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat).
drifting arrow
#

Im dealing with idiots players on a video game not programmers lol

#

They won't understand how to put a datetime in properly.

viscid hornet
drifting arrow
#

They're idiotsplayers

viscid hornet
drifting arrow
#

Trust me

#

they're fucking stupid.

viscid hornet
viscid hornet
slate karma
viscid hornet
slate karma
drifting arrow
slate karma
viscid hornet
slate karma
viscid hornet
# slate karma

your “command” is a message listener, not a command

#

when you send “!answer” it interprets that as a command

slate karma
#

oh

viscid hornet
#

or am i bugging

#

wait show whole code

fast osprey
#

If you want to use the command framework, you should make actual top level commands and get rid of your on_message

viscid hornet
#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

slate karma
viscid hornet
viscid hornet
#

it’ll fix your code dramatically

slate karma
viscid hornet
# slate karma thank u 😭

you get far more out of commands than a simple message event listener because commands are made to be commands and message event listeners are just plain text 🤷🏽‍♂️

#

@slate swan spit it out

slate swan
viscid hornet
crisp glacier
young dagger
#

@vale wingDo you know how to overwrite a text file with new data outside of the docker container?

#

I'm trying to update a text file based on data fetched from a URL, but it seems like the file changes are not persisting as expected locally

crisp glacier
#

!d str.join

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) objects. The separator between elements is the string providing this method.
upbeat otter
crisp glacier
#

My bad

viscid hornet
vale wing
#

If it is, file perms are read only, you can manually alter them and edit file

smoky patrol
#

Someone knows how i can add the a specifc value as the default value to ui textinput in discord.py
`class add_keyword(ui.Modal):
keyword = ui.TextInput(
label="Keywords",

        default=self.value
    )
excluded = ui.TextInput(
        label="Exclude",
        required=False
    )
def __init__(self, value):
    self.value = value`

that wouldnt work

young dagger
# vale wing If it is, file perms are read only, you can manually alter them and edit file

I'm running a task to update the text file. So there is no way to update the text file locally by the bot running in a docker container?

                        with open('blacklisted_domains.txt', 'r', encoding='utf-8') as f:
                            current_blacklist = f.read().splitlines()

                        if fetched_data.strip() != '\n'.join(current_blacklist).strip():
                            with open('blacklisted_domains.txt', 'w', encoding='utf-8') as f:
                                f.write(fetched_data)```
young dagger
vale wing
vale wing
viscid hornet
vale wing
#

But why lower_snake_case classname 😭

#

Please

#

UpperCamelCase

young dagger
# vale wing You pretty much can. Could you show how you mount it
#!/bin/bash

echo "Stopping existing Docker container..."
docker stop blitzcrank
wait

echo "Removing existing Docker container..."
docker rm blitzcrank
wait

echo "Removing existing Docker image..."
docker rmi blitzcrank
wait

echo "Building a new Docker image..."
docker build -t blitzcrank .
wait

echo "Starting a new container with the updated image..."
docker run -d --name blitzcrank --restart always -t blitzcrank```
vale wing
#

It's headache to configure volumes via cli

wispy falcon
#

how do i change the profile of a guild with a simple command?

vale wing
#

!d discord.Guild.edit

unkempt canyonBOT
#
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the guild.

You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild) to edit the guild.

Changed in version 2.0: The newly updated guild is returned.

Changed in version 2.0: The `region` keyword parameter has been removed.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
wispy falcon
vale wing
#

Spoonfeeding*

#

But fine

#
@command()
async def swap_icon(ctx):
    with open("new_icon.png", "rb") as fp:
        await ctx.guild.edit(icon=fp)
smoky patrol
wispy falcon
#

ok

viscid hornet
vale wing
#

You asked for example, not working code 😛

wispy falcon
#

ok

vale wing
#

Figure it out and adapt for your needs

wispy falcon
wispy falcon
young dagger
#

However, any idea how I can write to the text file locally?

vale wing
#

Well you'd still need compose first

#

Configuring volumes via cli is possible

#

But your build line will be long af and unreadable

wispy falcon
vale wing
#

You need to change the decorator and filename at the very least in order for it to work

limpid apex
#

If I wanted to use python (ro.py, discordpy) to make a roblox in-game verification system, is that possible

#

I’m aware it would need a webhook, I’m just not sure how to use them

young dagger
vale wing
young dagger
vale wing
#

And compose

vale wing
vale wing
#

Can do that pretty much from any app as long as you have internet connection xd

#

!pypi aiohttp use this

unkempt canyonBOT
#

Async http client/server framework (asyncio)

Released on <t:1713289750:D>.

limpid apex
#

Kk

#

Ty!

limpid apex
slate swan
vale wing
vale wing
limpid apex
#

Kk

vale wing
#

Yeah that one even has examples

#

They're using requests library however, keep in mind that you will need to swap to aiohttp when you get to implementing your verification system

young dagger
#

Is there a way to retrieve all members with a specific role without having to iterate through every member in the guild?

slate swan
#

!d discord.Role.members

unkempt canyonBOT
slate swan
#

@young dagger this

#

Hello y'all me again back with another issue lol, use have helped me solve many of my issues with my bot so far and it's currently working amazingly so Thank you,

Anyways I have added a new command which will remove said members from their current role and also update the embed message accordingly (by removing their @username from that category) however when I try to use the remove command I get the error message Unknown Integration within discord, how do I resolve this so the command works as it should.

fast osprey
#

Code and traceback?

slate swan
#
async def remove_from_category(ctx, category_name: str, member: discord.Member):
    try:
        if not ctx.author.guild_permissions.administrator:
            raise commands.MissingPermissions(["administrator"])

        normalized_category_name = category_name.lower()
        if normalized_category_name not in queue_categories:
            raise commands.BadArgument("Invalid category name.")

        role_name = queue_categories[normalized_category_name]
        role = discord.utils.get(ctx.guild.roles, name=role_name)

        if not role:
            raise commands.BadArgument("Role not found for the specified category.")

        await member.remove_roles(role)

        channel = ctx.guild.get_channel(TARGET_CHANNEL_ID)
        if not channel:
            raise commands.BadArgument("Target channel not found.")

        await update_embed(channel)
        await ctx.send(f"Successfully removed {member.mention} from {category_name}.")

    except commands.MissingPermissions as e:
        await ctx.send(f"You don't have permission to run this command: {e}")

    except commands.BadArgument as e:
        await ctx.send(f"Invalid usage: {e}")

    except Exception as e:
        traceback.print_exc()
        await ctx.send(f"An error occurred: {e}")```
young dagger
slate swan
#

members is a property, not a method

#

so it doesn't take any arguments

#

you would have to first get the role from the guild

#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
slate swan
#

and on that role use an members property

young dagger
slate swan
#

What I think it will do is looping thru every role and comparing its id to the one provided to you

#

and get_role will take the role from the cache

#

(will return None if not found)

young dagger
#

What is the best way to handle comparisons with member.joined?

# Check if member joined more than 5 minutes ago
            if (datetime.datetime.utcnow().replace(tzinfo=None) - member.joined_at.replace(tzinfo=None)).total_seconds() > 300:
slate swan
#

Thank you

naive briar
young dagger
#

I want to compare member.joined which is Discord related

#

Ofc anything is gonna be Python related too

naive briar
#

More like datetime

#

Sure. Right to my note 🤠

wispy falcon
#

is there another way to do application / slash commands without all the tree stuff?

naive briar
wispy falcon
#
async def on_message(message):
    if 'happy birthday' in message.content.lower():
        await message.channel.send('Happy Birthday! :balloon::tada:')```
#

what does lower mean?

#

or content.lower

proper spire
#

Hi guys, gonna ask for a suggestion, if there is already a bot for this use case, if not then I'll just end up making a bot for this

Use case: Ban the user if they write anything in the honeypot channel

This is being done to ban people who use spam bots.

viscid hornet
unkempt canyonBOT
#

str.lower()```
Return a copy of the string with all the cased characters [[4]](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.

The lowercasing algorithm used is [described in section 3.13 ‘Default Case Folding’ of the Unicode Standard](https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf).
viscid hornet
#

it makes the string all lowercase

viscid hornet
viscid hornet
proper spire
viscid hornet
#

on your own pc 👍🏽

viscid hornet
#

absolute no

proper spire
#

Sorta need it 24/7, can't have the pc running 24/7

viscid hornet
#

!hosting

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.

viscid hornet
#

there we go. check this out

proper spire
#

Thanks mate !

slate swan
#

what means channel "unbekannt" / "unknown" in the hosting factoid? that the resource changed?

viscid hornet
slate swan
#

you used the trigger "!hosting" and the bot posted a factoid as reaction. it suggests to join the channel "unknown" and it confuses me

viscid hornet
slate swan
#

oh, ok

viscid hornet
#

👍🏽

mellow token
#

Do try and except blocks on discord errors work? I have tried a bunch of stuff but none of them seem to be catching the discord errors

hushed galleon
# mellow token Do try and except blocks on discord errors work? I have tried a bunch of stuff b...

assuming you mean with discord.py using the commands extension, it depends on what raised the error - if it was something inside your command body then you can try-except that just fine, but for errors outside of it like check failures, CommandNotFound, MissingPermissions, etc., you need to write a special error handler for it:
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#error-handling py @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send(f"You are missing the following permissions: {error.missing_permissions}") else: raise error # print traceback to terminal

mellow token
wispy falcon
#

but i found another way

#

i think it was
@bot.hybrid_command(name="The_name", description ="The_Description")

#

and so on

#

with await bot.tree.sync in the async def on_ready event thing at the start

stoic island
#

Hey I'm just starting out with discord user installed apps in Python and wondering if someone could link some example code, or maybe just some barebones code that uses /hello and will output a little greeting from the bot. Much appreciated.

fast osprey
latent pier
latent pier
plush field
#

Hey can anyone help me

#

if
message = message.content.startswith("hey"): message.channel.send("¡Hey!")

But no work

#

∆:

latent pier
#

And bad indentation

plush field
#

To work

latent pier
#
if message.content.startswith("hey"):
    await message.channel.send("¡Hey!")
#

Have you learnt python?

plush field
#

I know a little

latent pier
# wispy falcon

on_ready might get called multiple times whenever your bot reconnects, starts, etc so triggering bot.tree.sync() so many times might lead you to timeout so it is better to use it only when necessary instead of calling it many times unnecessarily

plush field
latent pier
#

Show me full code instead of 2 lines

plush field
#

I think I miss a space

#

@latent pier

latent pier
#

Writing these two lines won't make it work

stoic island
plush field
latent pier
plush field
latent pier
plush field
latent pier
# plush field Can u make. 😭 I was looking for that
@bot.Event
async def on_message(message):
    if message.content.startswith("hey"):
        await message.channel.send("¡Hey!") 

But remember this channel isn't for spoon feeding you gotta learn things on your own and try to build it by yourself

plush field
latent pier
#

Why is it om line 474 what's the rest code?

wanton current
#

this is why you don't edit code inside pterodactyl

plush field
latent pier
#

Use proper IDE

plush field
#

I was looking for that

plush field
latent pier
plush field
#

Uh why I'm in mobile

#

So u can fix the code?

#

Uh.

viscid hornet
viscid hornet
latent pier
#

So point in investing energy....

viscid hornet
viscid hornet
latent pier
#

I've no idea because never experienced this error before

viscid hornet
# wispy falcon its just too much

how come? ```py

for main.py file

@bot.tree.command()
async def test(interaction):
await interaction.response.send_message("hello")

for cog

class MyCog(...):
...
@app_commands.command(name = 'test', description = '...')
async def test(self, interaction):
await interaction.response.send_message("hello")```

viscid hornet
viscid hornet
viscid hornet
latent pier
viscid hornet
latent pier
#

How bro wrote 500 lines when he can't even make simple event

latent pier
viscid hornet
viscid hornet
plush field
#

Uh what wrong?

latent pier
latent pier
plush field
latent pier
#

@bot.event
async def on_message(message):
    if message.content.lower().startswith("hey"):
        await message.channel.send("¡Hey!")

Try this

#

@plush field

wanton current
#

lowercase e on Event

plush field
plush field
latent pier
plush field
#

Only the "hey"

#

And don't give error where should I put?

fast osprey
mellow token
hushed galleon
#

in the case of commands, the command's error handler runs first, then cog_command_error(), then your global handlers

mellow token
#

Ahhh yeah makes sense WellDone I appreciate it!

viscid hornet
#

literally a cat

vapid parcel
#

So you can edit ephemeral messages, can you delete them?

#

I am talking abt interactions.

hushed galleon
unkempt canyonBOT
#

await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Deletes the original interaction response message.

This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
vapid parcel
#

alr ty 😁

#

Wait, I am calling a drop down, how can I do this? I wanna make the message go away after they select whatever they select ya know?

#

They press a button, which then calls a drop down.

viscid hornet
viscid hornet
#

!d traceback.format_exc

unkempt canyonBOT
#

traceback.format_exc(limit=None, chain=True)```
This is like `print_exc(limit)` but returns a string instead of printing to a file.
viscid hornet
#

i see too many beginners just printing the last line of the error and not including any traceback info as to what ent wrong

viscid hornet
#

let the select do it after it reloads

vapid parcel
#

in console it will show traceback

#

I am not going to show traceback inside of an embed.

viscid hornet
vapid parcel
#

Bro, inside of console, it shows the full error...

viscid hornet
vapid parcel
#

Does for me.

viscid hornet
#

!e
x = "abc"

try:
x = int(x)
except Exception as e:
print(e)

unkempt canyonBOT
#

@viscid hornet :white_check_mark: Your 3.12 eval job has completed with return code 0.

invalid literal for int() with base 10: 'abc'
viscid hornet
#

prints the last line

viscid hornet
vapid parcel
#

Pycharm shrug

#

Pycharm on top hehe

viscid hornet
#

cant run it for shit

vapid parcel
#

When did the word lightweight come into this..?

viscid hornet
#

!try-except

#

sad

vapid parcel
#

Runs on linux n mac os and windows just fine

#

maybe your pc just sucks shrug

viscid hornet
viscid hornet
viscid hornet
vapid parcel
#

Your pc just sucks then bro GoofySkull

viscid hornet
#

actually wait

#

im a fucking microwave 🤦🏽‍♂️

#

20 seconds

#

i was thinking about it wrong

#

eh shut up anyway

vapid parcel
#

So how to fix my issue again

#

instead of you talking abt goofy vsc

viscid hornet
#

printing an error is still bad practice 🤷🏽‍♂️

vapid parcel
#

IM NOT EVEN PRINTING ITTTT

viscid hornet
vapid parcel
#

SHOW THE PRINT

viscid hornet
vapid parcel
viscid hornet
vapid parcel
viscid hornet
vapid parcel
#

No I can't do that

#
        await interaction.delete_original_response()
#

It will give an error

#

404 error.

crisp glacier
viscid hornet
vapid parcel
#

discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

viscid hornet
#

that should in theory work fine

vapid parcel
#

now we try again

#

alr

#

it worked

#

I love you @viscid hornet kiss

crisp glacier
#

yeah hes big brain

crisp glacier
vapid parcel
crisp glacier
#

most of the time

viscid hornet
#

i thought you were gonna say “finally you’re useful” 😭🙏🏽

vapid parcel
#

this is the first time youve actually helped me

#

instead of me HELPING you

viscid hornet
vapid parcel
#

sometimes

#

😁

crisp glacier
viscid hornet
# vapid parcel it worked

also just so you know, it works because the parent interaction is what sends the message with the view so that interaction holds the original response. you can think of the select interaction as a child interaction where it doesnt have an original response

viscid hornet
crisp glacier
viscid hornet
vapid parcel
#

your first dm was you asking for help GoofySkull

#

waiting for bro to delete the message GoofySkull

viscid hornet
#

|| (not in front of the hoes) ||

vapid parcel
crisp glacier
vapid parcel
#

@viscid hornet

viscid hornet
#

yeah?

vapid parcel
#

Be more help, i was showing this man that only codes bots in js, my control panel, but he doesn't know what cogs are

#

so what would cogs be in js? I said extensions, he said no also GoofySkull

#

Tf do they have in js 😭

viscid hornet
vapid parcel
#

yes but like

#

do they not have cogs?

viscid hornet
vapid parcel
#

😭

viscid hornet
#

research it

vapid parcel
#

Research? whats that...?

viscid hornet
#

cogs are just discordian modules that you import

#

!d InteractionResponse @crisp glacier

vapid parcel
#

Lol

viscid hornet
#

!d discord.InteractionResponse @crisp glacier

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response).

New in version 2.0.
viscid hornet
vapid parcel
#

TO much work

viscid hornet
plush field
viscid hornet
#

show your imports

plush field
#

This?.

scarlet tiger
plush field
#

First line?

scarlet tiger
#
import discord 
from discord.ext import commands

Example

plush field
#

Ok thx

vapid parcel
#

I made this control panel in my bot, was wondering if anyone had any more ideas for it!! if not then that is fine!

shrewd apex
# vapid parcel

maybe further cog information, ability to enable disable commands in the cogs itself some handling of tasks as well i suppose?

#

cancel, start, restart tasks ig

cyan eagle
#
import discord
import os

# Set bot token as environment variable
os.environ['BOT_TOKEN'] = 'token'

intents = discord.Intents.all()
intents.messages = True
intents.message_content = True

class DiscordBot(discord.Client):
    def __init__(self, intents):
        super().__init__(intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user}')

    async def on_message(self, message):
        if message.embeds:
            for embed in message.embeds:
                self.print_embed(embed)

    def print_embed(self, embed):
        print("Embed Title:", embed.title)
        print("Embed Description:", embed.description)
        print("Embed Fields:")
        for field in embed.fields:
            print(f"  {field.name}: {field.value}")
        print("Embed Footer:", embed.footer.text)
        print("Embed Image:", embed.image.url)
        print("Embed Thumbnail:", embed.thumbnail.url)
        print("Embed Author:", embed.author.name)
        print("Embed URL:", embed.url)

    def run(self):
        try:
            super().run('BOT_TOKEN')
        except discord.errors.LoginFailure:
            print("Invalid bot token")
        except Exception as e:
            print(f"An error occurred: {e}")

if __name__ == '__main__':
    bot = DiscordBot(intents)
    bot.run()

#

Why my bot not responding

slate swan
#

Any additional information? What exactly doesn't work pithink

drifting arrow
#

🤔

viscid hornet
#

also you shouldnt go through the bother of subclassing Client because Client is a literal nothingburger when it comes to doing literally anything

#

also STOP PRINTING EXCEPTIONS. PLEASE 😭

cyan eagle
slate swan
#

man this my first time coding a bot and i cant even get it to run

viscid hornet
viscid hornet
cyan eagle
crisp glacier
cyan eagle
#

Don't even know what that means

slate swan
#
from typing import Final 
import os
from dotenv import load_dotenv
from discord import Intents, Client, Message 
from responses import get_response


TOKEN = 'token'

intents: Intents = Intents. default()
intents.message_content = True
client: Client = Client(intents=intents)


async def send_message(message: Message, user_message: str) -> None:
    if not user_message:
        print( '(Message was empty because intents were not enabled probably)')
        return
    
    if is_private := user_message[0] == '?':
        user_message = user_message [1:]

    try:
        response: str = get_response(user_message)
        await message.author.send(response) if is_private else message.channel.send(response)
    except Exception as e:
        print(e)


@client.event
async def on_ready() -> None:
    print(f'{client.user} is now running!')

@client.event
async def on_message(message: Message) -> None:
    if message.author == client.user:
        return 
    
    username: str = str(message.author)
    user_message : message.content
    channel: str = str(message.channel)

    print(f'[{channel}] {username}: "{user_message}"')
    await send_message(message, user_message)

def main() -> None: 
    client.run(TOKEN)

if __name__ == '__main__':
    main()```
viscid hornet
crisp glacier
viscid hornet
#

try writing code normally this time

slate swan
#

i followed a tutorial on yt for this

viscid hornet
cyan eagle
#

Ik basics

viscid hornet
viscid hornet
#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

viscid hornet
#
# codeblocks
"with syntax highlighting"
cyan eagle
viscid hornet
#
"""
makes things easier to read
"""```
crisp glacier
#

gambling go dms before i cut your balls

viscid hornet
cyan eagle
#

So I can do things with that

viscid hornet
cyan eagle
crisp glacier
#

why is ur username google btw

viscid hornet
#

¯_(ツ)_/¯

cyan eagle
cyan eagle
cyan eagle
#

Ahh

viscid hornet
#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

viscid hornet
#

three backticks then py at the end

#

then three backticks under the code

#

that gives it syntax highlighting which makes it easier to read

#

AY THERE WE GO

slate swan
#

i fixed xd

cyan eagle
viscid hornet
#

oh im dumb

#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
viscid hornet
cyan eagle
#

Reather then using events?

viscid hornet
viscid hornet
#

just how it goes yk ¯_(ツ)_/¯

slate swan
#

ic

crisp glacier
#

listen to gambling he big brain

slate swan
#

when i asked chatgpt it said that "SSL certificate verification failed due to the inability to get the local issuer certificate"

viscid hornet
unkempt canyonBOT
#
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

viscid hornet
#

show me this ^^

cyan eagle
#

And what should I change so it can work

viscid hornet
viscid hornet
#

😁

slate swan
#

its really long should i send all of it?

cyan eagle
#

Idk that stuff

viscid hornet
unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

viscid hornet
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
cyan eagle
viscid hornet
viscid hornet
unkempt canyonBOT
crisp glacier
#

i still dk what he means by reading embeds

#

why would you want to do that

viscid hornet
crisp glacier
#

hm

slate swan
crisp glacier
#

hi ray

viscid hornet
#

@slate swan thats a network issue i think. ask @fast osprey - she fixed this issue for someone

slate swan
#

hi

viscid hornet
#

i have no idea how to sort it ¯_(ツ)_/¯

viscid hornet
slate swan
#

alr

crisp glacier
#

solstices hard

viscid hornet
#

!d random.choices @crisp glacier

unkempt canyonBOT
#

random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError).

If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate)). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
viscid hornet
#

see it says cum weights

crisp glacier
#

notd

slate swan
#

and thats why you shouldn't use shortcuts

fast osprey
#

SSL issues very rarely have to do with network at all and typically are just a lack of certs on the local machine

crisp glacier
#

does markdown not work in embed fields?

scarlet tiger
crisp glacier
#

did i do something wrong

scarlet tiger
#

Code

crisp glacier
#
            blackjack_hit.add_field(name="Dealer deck", value=f"# {hand_value_dealer} -" + ",".join([str(c) for c in self.casino.dealer_deck]),
                                    inline=False)```
crisp glacier
#

wdym

#

i need it to be really big tho

#

not just bold

#

@scarlet tiger why isnt it working tho?

scarlet tiger
crisp glacier
#

yes

slate swan
scarlet tiger
crisp glacier
#

its going to be bold, i need it to be big

#

like this

#

and not like this

#

get it ?

scarlet tiger
#

you said markdown not big text

crisp glacier
#

my bad

#

i meant big text

#

doesnt this count as markdown tho?

scarlet tiger
#

Text

#

Hmmm no, in embeds no

fast osprey
slate swan
#

oh this was easier than i thought xd, thanks

crisp glacier
merry cliff
crisp glacier
merry cliff
crisp glacier
#

Damn could be

#

Thanks

merry cliff
#

np

vapid parcel
viscid hornet
crisp glacier
naive briar
quick gust
#

Pretty sure you can use headings in embed descriptions too

naive briar
crisp glacier
#

but why didnt it work when i tried

crisp glacier
naive briar
#

It does perfectly for me

#

Are you putting it in a field name? Because it doesn't work there

crisp glacier
#
            double_down.add_field(name="Dealer deck", value=f"# {hand_value_dealer} -" + ",".join([str(c) for c in self.casino.dealer_deck]),
                                    inline=False)```
#

nope im putting it in the value

naive briar
#

Still does

crisp glacier
viscid hornet
#

|| (try it and see) ||

sweet minnow
viscid hornet
#

also theres no point in printing a traceback so you dont need the “try except …” stuff

wanton current
#

is this code generated by ai?

viscid hornet
wanton current
#

since it's probably from an api that makes sense

viscid hornet
#

oh. fair enough 🤷🏽‍♂️

sweet minnow
#

All i wanted to know is whether if it's correctly implemented or not. Please help.

viscid hornet
#

can apis not send back large/long numbers or smth

wanton current
#

eg. a discord id is larger than a 32-bit integer

#

in python it doesn't matter but in js you'd have to use BigInt

viscid hornet
viscid hornet
#

is it like milliseconds since the computing big bang

wanton current
quick gust
sweet minnow
quick gust
#

top.gg website -> your bot -> webhooks I believe

spice seal
#

Guys how to get a story from this api
https://short-stories-api.onrender.com/
And display name as title and description of embed will be the story? I am new to APIs so pls help me

viscid hornet
spice seal
viscid hornet
#

it sends you a dictionary when you send it a get request

spice seal
#

Little bit

#

Not too much xd

viscid hornet
slate swan
#

@viscid hornet I gave up typing when I read "not too much" crii

viscid hornet
#

the rebirth of cancel 13

#

hes not even here

spice seal
#

Bruh I'm here lol

viscid hornet
#

@slate swan he got banned 💀

viscid hornet
slate swan
#

who was that fall

viscid hornet
wanton current
#

most unhinged help channel ive ever seen

slate swan
#

Anyways @spice seal, you wold need an aiohttp.ClientSession() and using that session you could make a GET request to the API which would return a Response object.

async with aiohttp.ClientSession() as session:
  async with session.get("url") as response:
    data = await response.json()

data in this meaning will be the JSON response from that API which is basically a python dictionary,
now having that data you could access elements / information that you need from it. Example:

some_json: dict[str, Any] = {
  "some_stuff": [ "image.jpg", "new.gif" ],
  "code": 200
}

print(some_json["code"]) # Will print value of the "code" key (200)
spice seal
#

import discord
from discord.ext import commands
import requests

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

@bot.command()
async def story(ctx):
    # Make a request to the API
    response = requests.get('https://short-stories-api.onrender.com/')
    data = response.json()

    # Assuming the API returns a list of stories and we're taking the first one
    story = data[0]

    # Create an embed with the title, description, and author's avatar as the thumbnail
    embed = discord.Embed(title=story['title'], description=story['description'], color=0x00ff00)
    embed.set_thumbnail(url=story['author_avatar'])

    # Send the embed in the current channel
    await ctx.send(embed=embed)

# Token and run goes here.```
This is still now working...
#

@slate swan

slate swan
#

I assume you get KeyError, right?

spice seal
#

Wait lemme show traceback

#

@slate swan

slate swan
#

I assume thats because you are accessing key that is against the rules? I don't really know since I would need to read scenarios in which JSONDecodeError happens. For sure the JSON key must be a string and you are accessing a key that is an int

shrewd apex
spice seal
#

I think so...

#

They have a github

wise oak
#

I a listening

shrewd apex
spice seal
#

This is the api

#

Wait a sec

#

I did it wrong

#

It's shortstories-api lol mb

slim bloom
#

@viscid hornet Could I give you a boost for the help you gave me with my bot?

spice seal
#

@slate swan your right there is a key error.

spice seal
slate swan
#

JSON keys are always strings

spice seal
#

How can I fix it...

slate swan
#

you would need to do something like data["film"] where "film" is a key name

viscid hornet
#

nitro is where its at 🤑

shrewd apex
# spice seal ```py import discord from discord.ext import commands import requests bot = co...
{"_id":"5fce5054b9455b1cacf1ca59","title":"The Crow and The Pitcher","author":"Aesop's Fables","story":"In a spell of dry weather, when the Birds could find very little to drink, a thirsty Crow found a pitcher with a little water in it. But the pitcher was high and had a narrow neck, and no matter how he tried, the Crow could not reach the water. The poor thing felt as if he must die of thirst. Then an idea came to him. Picking up some small pebbles, he dropped them into the pitcher one by one. With each pebble the water rose a little higher until at last it was near enough so he could drink.","moral":"In a pinch a good use of our wits may help us out.","__v":0}
#

this is a sample data from the api

#

title story author moral here are the keys

spice seal
#
import discord
from discord.ext import commands
import requests
intent=discord.Intents.all()
bot = commands.Bot(command_prefix='!',intents=intent,case_insensitive=True)

@bot.command()
async def story(ctx):
    # Make a request to the API
    response = requests.get('https://shortstories-api.onrender.com/')
    if response.status_code == 200:
        data = response.json()

        # Check if the expected keys are in the data
        if 'title' in data and 'description' in data and 'author_avatar' in data:
            # Create an embed with the title, description, and author's avatar as the thumbnail
            embed = discord.Embed(title=data['title'], description=data['description'], color=0x00ff00)
            embed.set_thumbnail(url=data['author_avatar'])

            # Send the embed in the current channel
            await ctx.send(embed=embed)
        else:
            await ctx.send("The required data is missing from the API response.")
    else:
        await ctx.send("Failed to retrieve data from the API.")

This is the code,the code works but this is the correct error @slate swan

slate swan
#

it should be data.keys() I think

night crater
#

nah dictionaries let you do key in dict

#

it implicitly is checking the key

#

log the response payload with pprint.pprint(data) and see if it matches your expectations

shrewd apex
slate swan
#

TIL

wanton current
slate swan
#

how to get this???

wanton current
#

I guess just check len(guild.members)

slate swan
spice seal
#
import discord
from discord.ext import commands
import requests
intents=discord.Intents.all()
bot = commands.Bot(command_prefix='!',intents=intents,case_insensitive=True)

@bot.command()
async def story(ctx):
    # Make a request to the API
    response = requests.get('https://shortstories-api.onrender.com/')
    if response.status_code == 200:
        stories = response.json()

        # Check if the response is a list and not empty
        if isinstance(stories, list) and stories:
            # Access the first story in the list
            story = stories[0]

            # Check if the expected keys are in the story
            if 'title' in story and 'description' in story and 'author_avatar' in story:
                # Create an embed with the title, description, and author's avatar as the thumbnail
                embed = discord.Embed(title=story['title'], description=story['description'], color=0x00ff00)
                embed.set_thumbnail(url=story['author_avatar'])

                # Send the embed in the current channel
                await ctx.send(embed=embed)
            else:
                await ctx.send("The required data is missing from the story.")
        else:
            await ctx.send("The API response is not in the expected format or is empty.")
    else:
        await ctx.send("Failed to retrieve data from the API.")

Updated code @slate swan this is still not working...

#

If possible someone dm cuz I can't follow up with the chat
Dms are always open for help 🙂

slate swan
#

stories variable would be instance of dict I believe

#

dict[str, Any]

wanton current
spice seal
#

I can't understand 😭
Can anyone update the code or help in detail
If possible pls dm

slate swan
#

This gives you a dictionary (Whole JSON data from the response) , now you need to access the "story" key

spice seal
#

I have done it in the embed tho right?

slate swan
#

Right but this check is failing

#

since "stories" is an instance of dict (thats what I think atleast)

shrewd apex
#

also the dictionary dosent have any description or author_avatar

#

the code just looks ai generated at this point

slate swan
#

I also recommended using aiohttp pithink

#

requests is blocking the event loop

viscid hornet
viscid hornet
#

what did i miss

viscid hornet
slate swan
viscid hornet
#

i aint see that

viscid hornet
#

😂

wanton current
#

ur weird

slate swan
viscid hornet
slate swan
#

I wonder if its a stupid idea to make a metaclass for creating Singletons

#

then subclassing the bot and passing it as a metaclass

shrewd apex
viscid hornet
slate swan
slate swan
shrewd apex
slate swan
viscid hornet
#

wait hold on

#

what is _instances

shrewd apex
shrewd apex
#

yes

slate swan
shrewd apex
#

u can instead override __new__ for this

#

!e

class Singleton:
    __instance = None

    def __new__(cls):
        if not cls.__instance:
            cls.__instance = super().__new__(cls)
        return cls.__instance
    
s = Singleton()
print("Object created", s, id(s))
s1 = Singleton()
print("Object created", s1, id(s1))
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Object created <__main__.Singleton object at 0x7f2075fdfcb0> 139777395260592
002 | Object created <__main__.Singleton object at 0x7f2075fdfcb0> 139777395260592
wanton current
#

very discord bot related

shrewd apex
slate swan
#

!e

class SingleMeta(type):
  _instances = {}

  def __call__(cls, *args, **kwargs):
    if cls not in cls._instances:
      cls._instances[cls] = super().__call__(*args, **kwargs)
    return cls._instances[cls]

class Test(metaclass=SingleMeta):
  def __init__(self, a):
    self.a = a

test1 = Test(2)
test2 = Test(5)

print(test1.a)
print(test2.a)
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 2
002 | 2
slate swan
shrewd apex
#

yeah it would work if u define __call__ for the metaclass because this way the __call__ method is being invoked when ur doing Test()

slate swan
marble rapids
#

!e

unkempt canyonBOT
#
Missing required argument

code

slate swan
#

@marble rapids #bot-commands

marble rapids
slate swan
#

this is a channel for bots support, use your commands there #bot-commands

marble rapids
#

i saw, i was just thinking this is like a bot for giving you python tests and you solving them with a solution

vapid parcel
viscid hornet
unkempt canyonBOT
#

remove_command(command, /, *, guild=None, type=<AppCommandType.chat_input: 1>)```
Removes an application command from the tree.

This only removes the command locally – in order to sync the commands and remove them in the client, [`sync()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.sync) must be called.
viscid hornet
#

omds im so smart holy fuck

#

guessed it asw 🤑

vapid parcel
#

Alr ty 😁

slate swan
vapid parcel
latent pier
thorny frost
#

Hello, newbie question here, is there a function in the discord API that allows a bot to ignore a message?

thorny frost
#

I have it set up as "?" being the key for the bot to private message the user, then the bot deletes the users message in the channel. I'm stuck on that the bot deletes even messages with only a "?" and nothing else!

latent pier
#

Do you know how to use if condition and startswith?

thorny frost
#

yes, a bit, I could send you the code if you'd like.

latent pier
#

You should've already sent it earlier

#

Don't ask for help without context

thorny frost
#

I did in the help channel and they sent me here so I thought I couldn't post code like that here!

#
 if user_message.startswith('?'):
        user_message = user_message[1:]
        try:
            response: str = get_response(user_message)
            await message.author.send(response)
            await message.delete()
        except:
            IndexError
            Forbidden(print('Forbidden'))
            NotFound(print('Not Found'))```
latent pier
#
 if user_message.startswith('?'):
        user_message = user_message[1:]
        try:
            response: str = get_response(user_message)
            await message.author.send(response)
            if not message.startswith("?"):
                await message.delete()
        except:
            IndexError
            Forbidden(print('Forbidden'))
            NotFound(print('Not Found')) 
thorny frost
#

Thanks, I’ll give that a shot!

slate swan
thorny frost
slate swan
#

!except

unkempt canyonBOT
#
Error handling

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

slate swan
#

this is how you catch errors

#
except:
    IndexError
    Forbidden(print('Forbidden'))
    NotFound(print('Not Found')) 

-> ```py
except IndexError:
# do something
except Forbidden:
print('Forbidden')
...

or if you want to do same thing for couple errors
```py
except (Forbidden, NotFound):
    print("Error")
#

also if you want to know what error was actually caught you can save it in a variable like this ```py
except (Forbidden, NotFound) as e:
print(e)

thorny frost
#

Ooooh! That actually makes it very clear! Thanks a bunch!

slate swan
long cove
#

Hi where can I create a bot?

latent pier
long cove
latent pier
#

Dumb question Developer portal

long cove
merry cliff
latent pier
long cove
latent pier
#

Python and OOP concept

merry cliff
merry cliff
#

It covers everything

long cove
#

But I have no idea about how I will do it

latent pier
#

Learning will take time

long cove
merry cliff
#

It’s built in

latent pier
long cove
latent pier
merry cliff
long cove
#

Okay

latent pier
long cove
#

But as said I have no idea how py works so i'ma just copy some tutorials on YouTube.

scarlet tiger
long cove
fast osprey
#

YouTube is a cesspit where people make things up and nobody checks them on it. You should not use it to learn

scarlet tiger
#

🤨

fast osprey
#

We can disagree on this, but there is an insane amount of bad practice and misinformation with no accountability measures or peer review

scarlet tiger
fast osprey
#

I personally recommend you get comfortable with reading articles, and use those from reputable sources that are reviewed to educational standards

#

If you only watch videos to satisfy your attention span, you are severely limiting yourself as most of the best content is written as that is the best medium for this information

long cove
#

That's all I need

fast osprey
#

You won't be able to do that yourself unless you understand the concepts at play

long cove
#

For example

fast osprey
#

If youre just looking to copy paste something that someone else wrote without understanding it, that's a whole other thing

long cove
scarlet tiger
fast osprey
#

And a lot of people who think they have learned are unaware of the depths of the bad practices they've ingrained in themselves by watching some rando making stuff up in his basement for YouTube clicks

scarlet tiger
thorny frost
latent pier
thorny frost
#

Sure, DM or here?

latent pier
latent pier
viscid hornet
unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

latent pier
viscid hornet
#

we have a pastebin for this 👍🏽

latent pier
#

Axo will help too 🤣

#

With late responses

viscid hornet
#

😭🙏🏽

latent pier
long cove
#

K

viscid hornet
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!
latent pier
#

Stop it Axo 🤣

viscid hornet
#

also what is your code supposed to do?

#

are you reading input like a command but with a message listener

viscid hornet
latent pier
#

That's complicated tho why don't you use dpy library instead

latent pier
viscid hornet
thorny frost
latent pier
viscid hornet
viscid hornet
thorny frost
viscid hornet
#

wait i think i misunderstood. can you give me an example of what you want to happen?

#

ok hold on

viscid hornet
#

ok wait im overcomplicating. basically just send the user command output

latent pier
#

I'm assuming

@client.event
async def on_message(message):
    if not message.startswith("?"):
        await message.delete()
thorny frost
#

the "?" operator should make the bot send you a private message instead of output in the channel

latent pier
#

Isn't it same?

viscid hornet
thorny frost
#

but it should not delete "?" if thats all the user sends

#

yes, if its more then a single "?"

viscid hornet
thorny frost
#

I had the code delete the "?" even tho the user should be allowed to send that. I have fixed that now!

latent pier
#

Not proper explaination

viscid hornet
thorny frost
#

So i make the message deletion happen in the command?

viscid hornet
#

have you used commands before?

thorny frost
#

I see where you are coming from, however I don't see how I can make it work since I want to have "!" as public commands

#

Wouldn't that make it 2x the code?

viscid hornet
#

no not necessarily

wanton current
viscid hornet
#

wait this got more complicated

viscid hornet
thorny frost
#

Imma head to bed, thanks for the input guys!

viscid hornet
#

alr np 👌

viscid hornet
fast osprey
#

IMO on_command_completion would probably be more suitable

viscid hornet
#

had no idea that existed

viscid hornet
wanton current
#

If I'm understanding the desired functionality correctly

#

Although you'd lose typing info on the parameters, but could probably fix that

viscid hornet
#

would you typehint to your new context class or make an instance of it already or what?

unkempt canyonBOT
#

examples/custom_context.py lines 27 to 32

class MyBot(commands.Bot):
    async def get_context(self, message, *, cls=MyContext):
        # when you override this method, you pass your new Context
        # subclass to the super() method, which tells the bot to
        # use the new MyContext class
        return await super().get_context(message, cls=cls)```
slim bloom
#

@viscid hornet

viscid hornet
slim bloom
#

@bot.tree or @app.commad

crisp glacier
#

app command

#

but you need bot tree also

#

and dont forget to make a prefix command for syncing

#

nvm imma fix it somehow

slim bloom
#

@crisp glacier

#
import discord
from discord.ext import commands

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

    @commands.command(name="ping", description="Prueba el comando ping")
    async def ping(self, interaction: discord.Interaction):
        await interaction.response.send_message("pong!")

    @commands.command()
    async def syncup(self, ctx):
        await self.bot.sync()
        await ctx.send("Listo")

async def setup(bot):
    await bot.add_cog(Slash(bot))```
#

?

pale zenith
viscid hornet
crisp glacier
#

solve what

viscid hornet
viscid hornet
crisp glacier
#

yeah im sure im not much help lmao

slim bloom
#

alr

#

thx

viscid hornet
viscid hornet
viscid hornet
slim bloom
#

@viscid hornet

crisp glacier
#

bro stop pinging and just tell us your problem

#

people will respond eventually

slim bloom
#

bot.py: py @bot.tree.command() async def test(interaction): await interaction.response.send_message("hello")

cog: ```py
import discord
from discord.ext import commands
from discord import app_commands

class Slash(commands.Cog):
def init(self, bot):
self.bot = bot

@app_commands.command(name = 'testt', description = '...')
async def test(self, interaction):
    await interaction.response.send_message("hello")

@commands.command()
async def syncup(self, ctx):
    await self.bot.sync()
    await ctx.send("Listo")

async def setup(bot):
await bot.add_cog(Slash(bot))```

slim bloom
sweet minnow
#
@bot.event
async def on_dbl_vote(data):
    try:
        print("User voted!")
        user_id = data["user"]
        bot_id = data["bot"]
        print(f"User ID: {user_id}, Bot ID: {bot_id}")
        if bot_id == '1182613510895697931':  # Make sure to replace with your bot's actual ID
            print("Bot ID matches!")
            # Logic to add reward to the user's account/profile
            #reward_user(user_id, reward)
            # Optionally, send a message to the user (you would need the channel or user object to do this)
            user = await bot.fetch_user(user_id)
            print("Fetching user...")
            await user.send("Thank you for voting for Sparkle Wonder! This is a test vote :c")
            print("Sent DM to user!")

    except Exception as e:
        print("An error occurred:")
        print(e)
        traceback.print_exc()
        raise

I've tested the code but it didnt work. None of the print statements were shown in console. I don't quite understand what i did wrong, please help me thxs.

slim bloom
sweet minnow
#

btw it is a topgg vote tracker

sweet minnow
crisp glacier
sweet minnow
#

i really wanted to learn

crisp glacier
#

yeah its all good

viscid hornet
#

yo im back

crisp glacier
#

hey

viscid hornet
sweet minnow
#

i dont have webook url/ auth token?

crisp glacier
#

bro lives in the help channels

viscid hornet
viscid hornet
sweet minnow
#

i said i tested the vote through actually voting

slim bloom
sweet minnow
#

and it didnt work as intended

slim bloom
#

?

sweet minnow
#

as in there is no print messages shown

viscid hornet
viscid hornet
crisp glacier
#

gay son or thot daughter

viscid hornet
sweet minnow
#

ive looked at the topgg docs and i dont see other valid ways to implement this?

crisp glacier
viscid hornet
#

yeah doesnt exist

viscid hornet
crisp glacier
sweet minnow
#

then wrong docs prob

#

what abt this one?

viscid hornet
#

!pypi dblpy

unkempt canyonBOT
viscid hornet
#

oh

sweet minnow
#

thats not correct either

viscid hornet
sweet minnow
#

not the same the version is different

#

im literally so confused rn

viscid hornet
#

well on dblpy i think i found what you’re looking for

sweet minnow
#

is it topgg or topggpy or dbl or dblpy... which is it?

viscid hornet
viscid hornet
sweet minnow
#

then how do i get webhook url and pass/auth?

viscid hornet
sweet minnow
viscid hornet
#

the wrapper takes care of the rest for you, would it not?

sweet minnow
#

ill have a look at it

viscid hornet
#

wait which site are you using?

#

i cant tell if its top.gg or dbl

night crater
#

You know topgg and dbl are the same site right?

viscid hornet
#

i swear they were different 😭

night crater
#

Dbl aka discordbotlist was the old site name before it became topgg

viscid hornet
#

how come its a separate site and they didnt depreciate it?

night crater
#

Because seo

viscid hornet
night crater
#

Wait NVM I'm the dumb one

viscid hornet
#

wait so if they’re the same website then how come they need different modules for each

viscid hornet
night crater
#

Did someone else buy the old domain 🤔

viscid hornet
#

research and find out

night crater
#

Welp I feel old now

#

So much has changed xD

sweet minnow
#

if i install topggpy, and use this one. what do i import?
i tried import topggpy, import topgg and both didnt work

viscid hornet
#

you just need a client instance or whatever, smth like that, and you should be good to go

sweet minnow
#

and says module not found error

viscid hornet
#

should say what to import

sweet minnow
viscid hornet
sweet minnow
#

ive read the docs

viscid hornet
#

ok so what does everything start with

#

should say X_name.Y_something

#

whats “X_name” in this case?

sweet minnow
#

topgg?

viscid hornet
viscid hornet
sweet minnow
#

requirements.txt on vps

#

install*

viscid hornet
#

and whats in the requirements.txt file

#

!pypi topggpy

unkempt canyonBOT
viscid hornet
slim bloom
#

@viscid hornet The slash does not work nor does it respond to the syncs command

viscid hornet
#

!traceback 🗣🗣🗣

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

viscid hornet
#

always start with this

rancid leaf
#

getting a 404 error 10015 on interaction for pressing a button HoloThinkFRI

viscid hornet
#

!traceback for more reference

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

rancid leaf
#

its a decently long chain of u.i embeds and components put together, on the 3rd component press i get the error code on:

  File "C:\Users\*****\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\*****\Desktop\melee-python\cogs\locations.py", line 216, in handle_dungeon_inputs
    await interaction.followup.edit_message(interaction.message.id, embed=difficulty_embed, components=components)
  File "C:\Users\*****\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1467, in edit_message
    data = await adapter.edit_webhook_message(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\*****\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 191, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook