#discord-bots

1 messages · Page 330 of 1

sick birch
#

the first one could probably just be condensed down into if after:

young dagger
sick birch
#

if not, if after.channel will work

#

just a shorthand so I didn't have to type out after.channel and before.channel a million times here

young dagger
sick birch
#

hm, i see what you're saying

#

your original idea should be fine

young dagger
#

I only want count events related to joining or switching voice channels and leaving voice channels

young dagger
# sick birch your original idea should be fine
if before.channel and after.channel is None:
   # They left a voice channel, nothing else

if before.channel is None and after.channel:
    # They joined a voice channel, nothing else

if before.channel and after.channel and before.channel != after.channel:
    # They switched voice channels, nothing else
unkempt canyonBOT
#
The or-gotcha

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
sick birch
#

You're using and but it's the same concept - common mistake

#

oh i think i misread

young dagger
sick birch
#

i think that should be fine but might be better to be explicit

young dagger
sick birch
#
if before.channel is not None and after.channel is None:
   # They left a voice channel, nothing else

if before.channel is None and after.channel is not None:
    # They joined a voice channel, nothing else

if before.channel is not None and after.channel is not None and before.channel != after.channel:
    # They switched voice channels, nothing else
#

just more readable imo

brazen geyser
#

hey guyss, can someone please tell me whats wrong with my code

final iron
brazen geyser
final iron
brazen geyser
#

do you this its good solution or no?

final iron
#

Tables only need to be created once

#

It's also clear you don't actually know what on_ready does

#

I'd check the docs to clarify

brazen geyser
# final iron what's the point of it

on_ready responds to when the client is ready to use, this should connect to the database and create the table if it is not created, or am i wrong?

brazen geyser
slate swan
#

How can i make second part of user's link after command variable?
example: https//blabla.com/games/nameofgame?privateserver125-081295-8325- well i want to make that ?privateserver1241902570235 variable so i can put it in result that bot is gonna return back
BTW: that part of link always starts same (with ?privateserver) if that helps

blazing condor
brazen geyser
graceful ermine
#

Hey, how can I fix this issue?

Tickets2 is a local file

Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'tickets2'

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

Traceback (most recent call last):
File "/home/container/main.py", line 361, in load
await bot.load_extension(f"cogs.{ext[:-3]}")
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.tickets' raised an error: ModuleNotFoundError: No module named 'tickets2'```




```py
import tickets2

owner_role = 'AN | Owner' 
co_owner_role = 'AN | Co-Owner'

mod_role = "AN | Moderation Staff"
high_staff_role = 'AN | Administration Staff' 


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

    @app_commands.commands.command(name="tickets", description="ticket launcher")
    @app_commands.checks.has_role(owner_role)
    async def ticket_launcher(self, interaction: discord.Interaction):

        embed = discord.Embed(
            title="**Support Ticket**",
            description=":tickets: Support Contact\n > Staff for Help or Questions regarding about in game issues or discord issues.\n :handshake:Partner\n > Ask to partner\n :exclamation:Report\n > Report members of the discord or bugs.",
            color=discord.Color.blue()
        )

        embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1071584233736392886/1157780763777957938/IMG_5309.png?ex=6599bc5c&is=6587475c&hm=7a3df4737910ec45eafdc0ed5ee63b84bdafa450a66528dbd5c9a381230840d7&")
        embed.set_footer(text=f"{interaction.guild.name} • Tickets")


        await interaction.response.send_message(embed=embed, view=tickets2.ticket2.support_tickets(timeout=None))
final iron
#

I'd view the docs for information on how to create cogs/extensions

dreamy dune
final iron
#

Seems like it’s unable to import ticket2 from wherever he’s running it

graceful ermine
blazing condor
#

i had this idea to create an event for new years, but unsure how to go about it, i would like to get the last 10 seconds of the time and once that time is up it will send a gif URL of some sort to the channel, how would ya'll go about this.

midnight oracle
blazing condor
midnight oracle
# blazing condor mhmm

Just make the bot check for that time with a async function and when the time comes, send the GIF

sick birch
unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
sick birch
#

note the time kwarg

blazing condor
#

Thanks!

rugged shadow
#

i think there's a scheduler in dpy

#

let me read the docs

#

yeah

old vine
#

i am trying to make a command where it sends 5 questions and then once the user replies to the message with the answers, it checks the db with the answers if they are correct, the user gets the role

#

how do i make it?

rugged shadow
unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError) for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple) containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
rugged shadow
#

send the questions and wait for the message events

old vine
rugged shadow
#
# Send questions
...

# Wait for answers
def check(m) -> bool:
    return m.author.id == player.id and m.channel.id == ctx.channel.id
answers_msg = await bot.wait_for("message", check=check)

# Do something with it
void mauve
#

Can somebody tell me why does discord rate limits the bot? Is it because I switch channel names?
So basically it says WARNING:discord.http:We are being rate limited. PATCH https://discord.com/api/v10/channels/1189155879434600458 responded with 429. Retrying in 541.85 seconds. in the callback after I press the button to close the ticket

Here is the callback itself:

    async def callback(self, interaction: discord.Interaction):

        channel = interaction.channel
        guild = interaction.guild

        await interaction.message.delete()

        from package.bot.modules.view.admin_control_ticket import AdminPanelView

        user_id = await db.select_user(session, channel.id)
        user = await guild.fetch_member(user_id)

        await channel.remove_user(user)

        await db.decrease_user_ticket_amount(session, user_id)
        await db.update_ticket_status(session, channel.id, 'idle')

        new_name = 'closed' + '-' + channel.name.split('-')[-1]

        await channel.edit(name=new_name)

        await channel.send(embed=CreateEmbed(
                title='Тикет закрыт!',
                description=f'Пользователем {interaction.user.mention}'
            )
        )

        await channel.send(
            view=AdminPanelView(self.lang)
        )

        await log.send_log(interaction=interaction, action='close')
candid flume
#
  @app_commands.command(name='snipe', description='Add A Snipe')
    async def snipe(self, interaction:discord.Interaction, type:Literal['Legit', 'Blatant'], screenshot:discord.Attachment, player1: discord.Member, player2: Optional[discord.Member], player3: Optional[discord.Member], player4: Optional[discord.Member]):
        try:
            role = discord.utils.get(interaction.guild.roles, id = 1189185186789851187)
            if role in interaction.user.roles:
                try:
                    if type == 'Legit':
                        chan = self.bot.get_channel(1189008868869681203)
                    elif type == 'Blatant':
                        chan = self.bot.get_channel(1189011172092022875)

                    players = []

                    player1 = [players.append(f"<@{player1.id}>") if player1 else None]
                    player2 = [players.append(f"<@{player2.id}>") if player2 else None]
                    player3 = [players.append(f"<@{player3.id}>") if player3 else None]
                    player4 = [players.append(f"<@{player4.id}>") if player4 else None]

                    embed = discord.Embed(description=f'''**Type:** {type}
    **Players:** {', '.join(players)}
        ''', color=0xfc8c03)
                    embed.set_author(name=f'New Snipe')
                    embed.set_image(url = screenshot.url)
                    embed.set_footer(text=f'GROOP! | With ♥ By Doare')

                    await chan.send(f"{', '.join(players)}", embed=embed)

                    await interaction.response.send_message(f'Snipe added.', ephemeral=True)
                except Exception as e:
                    print(e)
            else:
                await interaction.response.send_message('You do not have the permissions to use this command.', ephemeral=True)
        except Exception as e:
            print(e)

I'm trying to check if user has a specific role, i'm probably doing it wrong is there any way to check if they have it?

fiery girder
#

you can do

if role in user.roles:
  commands....
#

you did that alr my bad

candid flume
#

i was going to try the decorator

#

but i've had no luck with those.

fiery girder
#

you can do

role = discord.Object(id=)
candid flume
fiery girder
candid flume
#

i'll give it a go

fiery girder
#

and at the end of the if statement add a break statement so it wouldnt go for long

candid flume
#

that didn't work either sadly

fiery girder
#

hmm

candid flume
#

okay managed to get the decorator to work, but it doesn't send an error message

#
@app_commands.command(name='snipe', description='Add A Snipe')
    @app_commands.checks.has_role(1189185186789851187)
    async def snipe(self, interaction:discord.Interaction, type:Literal['Legit', 'Blatant'], screenshot:discord.Attachment, player1: discord.Member, player2: Optional[discord.Member], player3: Optional[discord.Member], player4: Optional[discord.Member]):
        try:
            if type == 'Legit':
                chan = self.bot.get_channel(1189008868869681203)
            elif type == 'Blatant':
                chan = self.bot.get_channel(1189011172092022875)

            players = []

            player1 = [players.append(f"<@{player1.id}>") if player1 else None]
            player2 = [players.append(f"<@{player2.id}>") if player2 else None]
            player3 = [players.append(f"<@{player3.id}>") if player3 else None]
            player4 = [players.append(f"<@{player4.id}>") if player4 else None]

            embed = discord.Embed(description=f'''**Type:** {type}
**Players:** {', '.join(players)}
''', color=0xfc8c03)
            embed.set_author(name=f'New Snipe')
            embed.set_image(url = screenshot.url)
            embed.set_footer(text=f'GROOP! | With ♥ By Doare')

            await chan.send(f"{', '.join(players)}", embed=embed)

            await interaction.response.send_message(f'Snipe added.', ephemeral=True)
        except Exception as e:
            print(e)

    @snipe.error
    async def snipe_error(self, interaction:discord.Interaction, error):
        if isinstance(error, commands.MissingRole):
            await interaction.response.send_message('You do not have the permissions to use this command.', ephemeral=True)
fiery girder
#

maybe it gives some other error

#

make a global on_error and make it print an error

fiery girder
#

you can also use an if statement

candid flume
#

why are you giving me gpt resposnes dawg.

fiery girder
#

sometimes if you are stuck

candid flume
#

sigh, if i wanted gpt i would've gone there myself

fiery girder
#

ok then lemme get one from my brain

candid flume
#

the decorator works @app_commands.checks.has_role(1189185186789851187)

#

but it's not outputting any errors

fiery girder
#

oh yea cause it dont even let the user run the command if the role is not there

#

it will output in a global command error

#

something like this

#

i have this setup for most of the errors it can occur

candid flume
#

if you look at my code, it's practically the same

fiery girder
#

but its not a global command error

#

its only for one command specificly

candid flume
fiery girder
fiery girder
#

like on_message or on_ready

candid flume
#

alr one sec

fiery girder
#

async def on_command_error(self, ctx, error):

#

it gives a ctx and error

candid flume
#
@commands.Cog.listener()
async def on_command_error(self, error, interaction:discord.Interaction):
    try:
        if isinstance(error, commands.MissingAnyRole):
            await interaction.response.send_message('You do not have the permissions to use this command.', ephemeral=True)
    except Exception as e:
        print(e)

i've updated it to this, yet no errors

fiery girder
#

i think its an event

fiery girder
#

works like a charm

slate swan
#

Hello, is there a way to check if a user is a nitro user, then fetch their primary profile theme color, else grab their banner color?

candid flume
fiery girder
fiery girder
slate swan
#

ity's always been inaccurate

fiery girder
slate swan
#

ty

fiery girder
candid flume
#

okay fair, mine still is not working haha

fiery girder
#

@candid flume you dont need an interaction you need a (ctx, error)

#

ctx comes first error secound

#

then you need an exception

#
elif isinstance(error, commands.MissingPermissions):
            await ctx.reply(
                embed=Embed(
                    title="Error",
                    description=f"You Do Not Have The Required Permissions To Use This Command \nPermissions Needed:{error.missing_permissions} ",
                    color=Color.red(),
                )
            )
``` THEN YOU NEED THIS
#

just use MissingRole intead of Permission

candid flume
#

yeah that didn't work either

fiery girder
#

bruh

candid flume
#

that's what i said

fiery girder
#

it should work

candid flume
#

it doesn't shrug

fiery girder
#

works like a charm for me

fiery girder
final iron
unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

final iron
#

Using ChatGPT is not helpful

fiery girder
#

it is helpful miltiple times

final iron
#

No it isn’t, and you don’t know what you’re talking about

fiery girder
#

ok then my bad

final iron
fiery girder
#

i use hybrid

final iron
#

Which is still a prefixed command…

#

@candid flume
You’ll need to subclass app_commands.CommandTree and overwrite the on_error method, then pass that tree into your bot constructor

#

!d discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).

The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.

To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command) should be used.
candid flume
vague junco
#
    @hybrid_command(name="roll", description="Roll a dice.", hybrid_command=True)
    async def _roll(self, ctx, betweens: Optional[int] = 100, type: Optional[str] = "int"):
        try:
            if type == "int":
                if betweens <= 0:
                    betweens = 100
                return await ctx.send(random.randint(1, betweens))

            if type == "float":
                if betweens <= 0:
                    betweens = 100
                return await ctx.send(random.uniform(1, betweens))

            if type == "bool" or betweens == "bool":
                return await ctx.send(random.choice([True, False]))

            return await ctx.send("Type must be int, float or bool.")

        except Exception as e:
            await ctx.send(f"An error occurred while executing the command: {str(e)}")

Is this how it should be?)

slate swan
#

how to get the hex color of a users profile?

#

!d discord.User.accent_color

unkempt canyonBOT
#

property accent_color```
Returns the user’s accent color, if applicable.

A user’s accent color is only shown if they do not have a banner. This will only be available if the user explicitly sets a color.

There is an alias for this named [`accent_colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.accent_colour).

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
slate swan
#

Read the note as well as the description of the attribute

slate swan
#

I did

shrewd apex
#
  • no banner
slate swan
#

how to solve

#

why this is empty

sick birch
slate swan
#

and its in my server, but my bot just work in Private Message

sick birch
#

Can you send a screenshot of the whole thing please

slate swan
#

What i should do

sick birch
#

it looks cropped. Also the redirect url only shows up if you choose some other stuff

#

if you just choose bot it's not supposed to show up

slate swan
# sick birch if you just choose bot it's not supposed to show up

raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is
not possible, then consider disabling the privileged intents instead.

Discord Developer Portal

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

#

??

sick birch
slate swan
#

hm?

#

i'm trying to make my bot can check messages from my server and not for only pv

#

the first problem is solved (create a url gen)

final iron
slate swan
#
intents = discord.Intents.default()
intents.message_content = True
intents.guild_messages = True``` for a ping pong system
#

its enough?

#

because with py intents = discord.Intents.default() intents.all() is working only in pv and not in my server

#

how to solve?

final iron
slate swan
#

dont have more errors

#

its just dont working in my server

#

only pv

final iron
slate swan
#

but the main error now is, why my bot work only in private messages and not in my server with invite

final iron
#

You need the message_content intent.

indigo flicker
#

dude

#
import discord

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

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('hahahha')
#

whats wrong here its a basic code

#

but still

#

aint running , pls ignore the client.run part

slate fractal
#

dude

raven jetty
#

Do you get an error message?

indigo flicker
#

nah , the bot just doesnt replies with anything

slate fractal
#

can you help me

slate swan
indigo flicker
#

anyone ?

slate fractal
#

can you help me

indigo flicker
slate fractal
#

I want to learn programming

indigo flicker
#

freecodecamp

hushed galleon
#

you'll find it here in the dev portal

rapid forge
#

Hey

slate fractal
slate swan
indigo flicker
#

its working now , ive learnt

formal ginkgo
ashen notch
#

When it comes to buttons in Discord, is it possible to show a button as disabled for some user but enabled for others? Or is it just globally disabled or enabled?

hushed galleon
ashen notch
#

Yeah, that's what I'm currently doing. Someone just mentioned it off hand and I didn't know if it was a thing

#

Cheers!

nova junco
final iron
compact ivy
#

Quick question, it does regard discord, but I'm not sure where else to put this, so please direct me if needed

In a discord server, we have a channel where people buy/sell a crypto. I'm looking to scan for when a message contains the words WTC or WTB, then I need to scan for the price they put
Only issue is that people format their messages differently.
Examples:

WTB 1k FBX 0.1
WTB 50,000 FBX $0.1
WTB 100,000 at 0.075 / Dms are open to offers
wtb 5k or 10k for 0.1 
wts 0.2

etc

Is there a sane way to check a message for the number, or am I better off setting it to a command?
I'd rather not make it a command, as that adds complexity to something that needs to be as simple as possible

sick birch
#

hard to parse irregular text like that without AI or language learning models

rugged shadow
#

make a regex

sick birch
#

turns out regular expressions doesn't work so well on irregular expressions 😄

#

I can think of many ways users would word this where the regex would get confused

compact ivy
#

Ahhh, that sucks, but I appreciate it

I’ll talk with the server owner, see if it’s feasible still!

final iron
#

Yeah, as previously mentioned regex and or/and an AI model might work, but it's not guaranteed

#

Something like a slash command would be a lot easier to parse

vale wing
compact ivy
#

The operations themselves won’t go through the bot, it’s only for reference

However, after talking with the owner, a command is possible to be used!

loud junco
#

anyone has any resource on how to self host and connect database to self host discord bot? (i tried to do this with documentation but its not working)
thanks😭 (a vid or a full guide will be best)

vale wing
loud junco
slate swan
#

!rules

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

loud junco
#

no way this breaks the rule 😭 (╯°□°)╯︵ ┻━┻

#

its literally about how to connect db to my bot

finite salmon
loud junco
#

i dont have a wifi
will cloud database consume more mobile data than local host?

#

if cloud database consumes less than i will prefer cloud database

finite salmon
#

Cloud db will use more data

loud junco
#

then i will go with local host then

finite salmon
#

you should check out some async postgresql libraries

#

lile aiopg

loud junco
#

i tried using the postgres app but its just too complicated (its called pgadmin3 if not mistaken)

finite salmon
#

i havent used postgres on local machine so idk but if you're just doing it locally maybe you could try out some other database

#

like mysql or sqlite

#

but the async version

loud junco
#

u have any tutorial vid or guide for it?
i tried finding it but cant find any

finite salmon
#

for mysql

finite salmon
#

if you understand how to use the normal MySQL it shouldn't be hard to learn this

#

its similar enough

finite salmon
# loud junco thanks!

you also need to learn the SQL language to run sql commands
https://www.w3schools.com/sql/

vale wing
loud junco
vale wing
#

Best option is docker

#

Can even run postgres inside docker

loud junco
vale wing
#

How much ram you got

loud junco
#

how much does it need

#

idw to use too much ram for it 😭

vale wing
loud junco
#

but docker needs money

vale wing
#

You don't need github actions, just the docker part

vale wing
#

You just install it

loud junco
#

wait why do i need docker

#

why dont i just use mysql with my bot

vale wing
vale wing
loud junco
#

but what does it do

vale wing
#

You can run a whole operating system inside docker

vale wing
loud junco
vale wing
#

It doesn't matter lol

loud junco
#

ok whatever
lemme try using it
thanks :D

vale wing
#

Trust me docker is a tool worthy to learn

loud junco
vale wing
#

Yeah

#
  • safe environment and don't need to flood your pc with databases installations
loud junco
#

but im not going to host it 247

#

im using a laptop

vale wing
#

You can shutdown it any time

hardy geyser
#

how to setup coustom status

hardy geyser
#

anyone know?

#

nobady ?

vale wing
#

So basically

#

You don't

vapid parcel
#

Where to learn just Interaction commands.

vale wing
vapid parcel
#

Cuz discord doesnt allow prefix commands no more ig

vale wing
vapid parcel
#

Thats basically saying they will not give me my intent until i switch

vale wing
vapid parcel
#

404

vale wing
vale wing
vapid parcel
vale wing
#

I don't know up-to-date guide for discord.py, but can give you one for disnake

vapid parcel
#

Thats an idea I had was to just use it on something else, but since they kinda know... then I can't really do much

vale wing
vapid parcel
#

Bruh

vale wing
vapid parcel
#

They were complaining so hard in the emails istg

#

maybe cuz i only mentioned hybrid GoofySkull

#

but besides the point!!

vale wing
#

When I was verifying first bot they requested that I would delete all user data that's stored more than 600 days or smth do you think I did that

#

I actually did

vapid parcel
#

My bots verified

#

its just the fucking intents 😭

#

asking for to much 😢

vale wing
#

Yeah had to rewrite that first bot to slash commands, ended up gathering international team from this server

vapid parcel
#

😭

#

I have hybrid

vale wing
#

Well make them slash 😏

vapid parcel
#

So they would still give the intent if i just mention something else based on the intent? instead of mentioning the hybrid?

vapid parcel
#

thats another 10 years of my life down the drain atp 😭

vale wing
#

If you say smth like "my bot needs access to messages content intent because it has function of filtering blacklisted expressions" and then attach some screenshot

vale wing
vapid parcel
#

rn trying to get my fucking presence Intent

vale wing
#

W disnake

vapid parcel
#

not changing everything tbh

#

to much work imo

#

I have Server members Intent, which is easy to get, just have a on member join event n on member leave event

#

then they will accept that GoofySkull

#

Easiest one of the 3 imo

vale wing
#

Imagine typing interaction.response.send_message can't relate, can just inter.send 😜

vapid parcel
#

ite bro

vale wing
vale wing
#

But what do you needed presences for

vapid parcel
#

profile command

#

n imma make it to where if you are on dnd, bot wont bother you

#

adding some other shit to it too.

#
        if 'online' in status:
            status = '![1514onlineblank](https://cdn.discordapp.com/emojis/1170981283191599214.webp?size=128 "1514onlineblank")'

        elif 'dnd' in status:
            status = '![4431dndblank](https://cdn.discordapp.com/emojis/1170981286358306916.webp?size=128 "4431dndblank")'
        
        elif 'idle' in status:
            status = '![5204idleblank](https://cdn.discordapp.com/emojis/1170981169211379772.webp?size=128 "5204idleblank")'

        elif 'offline' in status:
            status = '![6610invisibleofflineblank](https://cdn.discordapp.com/emojis/1170981245572886558.webp?size=128 "6610invisibleofflineblank")'
        ```
#

heres one :)

#

cant really do that unless you have presences

#

also gonna add to see what platform they are on. Pc or Mobile when using the command

hardy geyser
vale wing
vale wing
#

But actually is it really needed

vapid parcel
#

Yes

#

ill show u

vale wing
#

Cause I personally wouldn't care if bot showed my status (like cmon I set it by myself)

vapid parcel
#

"We require the usage of the Presence Intent for the "profile" command to display a user's status, We show the user's status with emojis which are in the Testing Server, But to use the correct emoji, We need the usage of the Presence Intent to fetch their status."

This is what I had tho, I added more, didnt copy it tho

vale wing
vale wing
#

!d discord.ext.commands.Bot see constructor params

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
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.
vapid parcel
#

other things I cant really prove XD

vale wing
#

I'm kinda saving you time from discord asking same question

vapid parcel
#

adding things that look cool are awesome :)

#

plus i need the dnd thing, if they are on dnd they cant be bothered

#

so thats another feature, but my head hurts cuz ive been up all night, so imma sleep XD

vale wing
#

Ok wdym by "be bothered"

vapid parcel
#

Bot can not bother user

finite salmon
vapid parcel
vale wing
#

Does it spontaneously mention users without their consent

vapid parcel
finite salmon
vapid parcel
vapid parcel
#

like if warned, or banned, or this or that

finite salmon
vapid parcel
#

which if on dnd, we will pass

vapid parcel
finite salmon
#

made a human trafficking bot where you can buy members from your servers people get annoyed since every second one or the other user gets bought and pinged

finite salmon
#

fr

#

dms

vapid parcel
#

BET

#

Welp gn, thanks for helping @vale wing

finite salmon
#

ive stopped developing it for a while now

#

so there are some unfinished features

vapid parcel
#

Bro actually made the bot

finite salmon
#

fr

#

do .tutorial to get started with it

vapid parcel
#

I was joking, I thought u were too 😭 not adding it in any servers tho

finite salmon
#

crasy

#

idm

vapid parcel
#

No offense, but it just has admin for its only perm ya know 😭

finite salmon
#

lmao
Fair enough

#

not looking forward in promoting the bot anyway

#

kinda buggy and unfinished

vapid parcel
#

In py?

finite salmon
#

yea

vapid parcel
finite salmon
#

using pycord lib

vapid parcel
#

Nvm

#

:)

#

I was gonna offer to help.. but yeah nvm

finite salmon
#

i mean its similar enough

vapid parcel
#

😭

#

I've only ever used dpy

#

So idk

finite salmon
#

yeah even I used to use dpy long back and i didn't like it so much so i switched to pycord

#

and the transition wasn't too hard either

#

cuz they both have almost the same structure

vapid parcel
#

I've heard next cord is good? But idk atp, I think dpy is best imo

finite salmon
#

except bridge commands i think

finite salmon
vapid parcel
#

Who knows

finite salmon
#

who knows

vapid parcel
#

I was gonna use next cord before I found hybrid commands

#

But then I found hybrid commands :)

finite salmon
#

I see

#

Alr ill go now

vapid parcel
#

Lmao

finite salmon
#

bye

vapid parcel
#

Gn

finite salmon
#

night

vale wing
#

I actually have a question 🧐

#

For first time in century

#

I made automatic cog reload system, but the problem is my loops stay running and duplicate even though I stop them in cog_unload

#

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

vale wing
#

In line 19 it used to be loop.stop()

round maple
#

from discord_webhook import DiscordWebhook
ModuleNotFoundError: No module named 'discord_webhook'

#

i installed it it says its installed but it doesnt work

vale wing
finite salmon
vale wing
#

No, reload is initiated from external function

finite salmon
#

i made something similar to that in pycord

for cog in config_values["cog_list"]: # path to the cogs
    self.client.reload_extension(cog)
#

All of this inside an admin command

#

I think something similar should be there in dpy too

#

Basically this right? @vale wing

vale wing
finite salmon
#

i have no clue what your code does but shit looks overly complicated

shrewd fjord
#

Ah wait a sec, lemme debug something

#

No luck, working perfectly, @vale wing tried using @tasks.loop(..) normally ? Just for debugging

#

Ikr 💀

#

Just saying, for debugging purpose try using @tasks.loop instead of own loop deco

#

Any shit happens, i remember a code was working today then died tomorrow, literally no change in code, then again working the day after that 💀

shrewd apex
#

still quite useful

latent pier
#
@commands.hybrid_group(name='Antinuke', with_app_command=False, description='Server security module', aliases=['an', 'security'])
@commands.is_owner()
async def antinuke(self, ctx):
        if ctx.subcommand_passed is None:
            embed = discord.Embed(description='''working''')
            embed.set_author(name=f'Security for {ctx.guild.name}', icon_url=ctx.guild.icon_url)
            await ctx.send(embed=embed)
#

Comamnd isn't executing for some reason idk

stark nexus
#

I know discord bot's banner color it's according the avatar

#

But i dislike the color

#

Is it possible to change in code?

latent pier
stark nexus
#

Okay

fiery girder
#

Whats the point of app_commands when you can use hybrid commmands is there an advantage for using app_commands

latent pier
vale wing
#

It reloads modules and not extensions

#

Cause reloading extensions apparently doesn't reload modules it depends on

vale wing
dreamy dune
latent pier
fiery girder
shrewd apex
final iron
#

What gave you that idea

hushed galleon
#

if you're willing to maintain two different versions of your commands, then sure, use hybrid commands, but of course you have to keep in mind how interactions work differently from message commands

latent pier
#

@final iron This

hushed galleon
#

hybrid commands were released alongside app commands in v2.0, so should we expect app commands to disappear too?

hot gorge
#

hi guys i have basic knowledge of python, sql, and async and i want to learn discord bot dev. any recommendations of how to learn it?

hushed galleon
#

and if you find something you don't know, try to look for its corresponding documentation

#

you can also look at the discord api docs if you want an idea of what discord.py does internally (receiving real-time events from the gateway, registering application commands, etc.)

sour flicker
#

guys i want to learn how to make a telegram bot using python, can you recommend me a good tutorial/course on youtube/ elsewhere for free?

final iron
#

Slash commands will realistically never be removed, and the only way to remove prefixed commands is to remove the message_content intent, which tens of thousands of bots rely on

final iron
#

You’ll be better off trying your luck in a telegram specific server

sour flicker
final iron
#

I’m saying you’re not going to find many people with telegram knowledge in this channel, as its for discord bots

sour flicker
final iron
sour flicker
#

😂

compact ivy
#

I'm attempting to make a slash command for my bot, with a few restrictions
3 options
1: string equaling either "A", or "B"
2: a positive integer
3: positive float

I can't seem to find how to add any sort of limiters to the options in the discord.py docs, does anyone have any pointers?

final iron
compact ivy
#

yes, if at all possible

#

I'm willing to change frameworks as well, this bot is solely for this command

final iron
#

The first 2 will be easy, but im not sure if the 3rd will be possible on client side

#

You might just have to accept the value and parse it

compact ivy
#

I can work with that

final iron
#

So for the first one you can use choices

#

!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...
final iron
#

For the second one you can use Range

#

!d discord.ext.commands.Range

unkempt canyonBOT
#

class discord.ext.commands.Range```
A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.

During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) so type checkers understand the intent of the code.

Some example ranges...
final iron
#

Oh it does allow floats

#

Yeah, so you’ll use Range for the integer and float. That’ll get you all three

compact ivy
#

absolutely perfect, thank you so much for that!

young dagger
#

How can I format member.created_at to something like

limber falcon
#

hello Could someone tell me how to make my bot send a response similar to this one, so that the user is the only one to see it?

slate swan
limber falcon
final iron
slate swan
#

make it true by default ong

compact ivy
#

Well, it’s very often that you want other users to see the output, to true by default is a pain

young dagger
final iron
slate swan
#

<t:123:R>

young dagger
young dagger
slate swan
#

You can choose from many formats and click it to show the exact datetime.

#

I don't know the best way to format a timedelta oneself, if it were me I'd probably do some maths to extract the number of years/days/hours/minutes and ignore months altogether

#

In fact years are also ambiguous. I would just display the datetime when they joined and forget about all that "X years, Y days, ... ago" stuff

slate swan
#

dose any one know how can i create a time out command ?

final iron
slate swan
final iron
slate swan
slate swan
final iron
#

?

#

This was never possible, even since timeouts were implemented

#

It just doesn't make sense

slate swan
slate swan
final iron
#

The Discord API doesn't allow it

drifting arrow
#

How do you send a link/url without the big ass thing that popsup again?

#

nvm figured it out 😄

final iron
#

fwiw that “popup” is called an embed

merry cliff
#

.topic

lament depotBOT
#
**What commands/features are you proud of making?**

Suggest more topics here!

merry cliff
#

I copied the dank memer reddit commands when I was first learning how embeds worked

#

And then I made an xkcd command for my friends before they added their own one

compact ivy
#

I see that discord doesn't allow editing a channel description from a bot more than 2 times in 10 minutes

I'm trying to find a way to show some live-updated (or close to it) information in a chat without spamming the chat, since this could update on every message somebody sends

Does anyone know of a way to do this sanely, without spamming messages?

loud junco
#

is this how u connect db?

#

1 and 2 is outputted but 3 is not
no error

vale wing
vale wing
loud junco
vale wing
#

Otherwise you're vulnerable to sql injections, not in this concrete case tho

loud junco
unkempt canyonBOT
#
SQL & f-strings

Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also

  • Python sqlite3 docs - How to use placeholders to bind values in SQL queries
  • PEP-249 - A specification of how database libraries in Python should work
loud junco
#

i have to do that in every file? 😭

vale wing
vale wing
loud junco
vale wing
#

You just gotta write queries correctly

loud junco
#

i have one command in one file

#

but idk how to connect the db thats the problem

vale wing
#

You are not saving the connection actually

#

They are local variables

loud junco
#

make it a bot var?

vale wing
#

Either declare them as global or use botvars

#

And yeah in case you are beginner in dbs why don't you just start with sqlite? Much less complicated

loud junco
vale wing
#

Sqlite doesn't require you to install anything

#

Don't use it with bot tho, you will need aiosqlite

loud junco
#

i understand the basic

#

i just dk the syntax to connect

#

i worked with psg before dw (or pg i forgot, its the one with elephant logo)

vale wing
#

Well syntax is quite easy except you better subclass the bot instead of using botvars

class MyBot(commands.Bot):
    con: aiosqlite.Connection

    async def setup_hook(self):
        con = await aiosqlite.connect("yourdb.db")

    async def execute(self, query, *args) -> aiosqlite.Cursor:
        cur = await self.db.cursor()
        cur = await cur.execute(query, args)
        await self.db.commit()

        return cur
#

Then you can like

data = await bot.execute("SELECT * FROM users WHERE id = ?", user_id)
young dagger
#

How can I format member.created_at to something like

vale wing
#

You mean discord timestamp?

#

Like <t:0:R>

young dagger
#

No, this one is not using utils.format_dt

vale wing
#

Check out pendulum

#

!pypi pendulum

unkempt canyonBOT
loud junco
vale wing
#

Sure, as long as you have bot instance

loud junco
vale wing
#

If you execute something like INSERT or DELETE you obviously don't

loud junco
young dagger
vale wing
#

How is divmod even related to timedeltas

#

Ah you wanna do that low-level way

young dagger
loud junco
vale wing
#

Although personally I wouldn't waste my time writing those functions and just use ready module

young dagger
vale wing
#

Second, imma check

vale wing
#

Gonna look like

(pendulum.now().naive() - o.created_at).in_words()
loud junco
vale wing
#

And yeah constructions vary from lib to lib

#

Why do you need mysql tho?

loud junco
vale wing
#

pip install aiosqlite

loud junco
vale wing
#

If there's no file path present it will automatically create new

loud junco
#

ok thanks

vale wing
#

It got no interface because it's file-based database

loud junco
#

i see
thanks!

loud junco
vale wing
vale wing
vale wing
loud junco
#

DAMN SARTHAK MADE IT

loud junco
young dagger
# vale wing `Interval.in_words()`

What do you think about:

    now = datetime.utcnow().replace(tzinfo=timezone.utc)
    created_at = member.created_at.replace(tzinfo=timezone.utc)

    difference = relativedelta(now, created_at)

    time_components = [
        ("year", difference.years),
        ("month", difference.months),
        ("day", difference.days),
        ("hour", difference.hours),
        ("minute", difference.minutes),
        ("second", difference.seconds),
    ]

    non_zero_components = [(unit, value) for unit, value in time_components if value > 0]

    # Display a maximum of 3 time components
    displayed_components = non_zero_components[:3]

    formatted_components = [f"{value} {unit if value == 1 else unit + 's'}" for unit, value in displayed_components]

    # Join all components with commas, except the last one which is joined with "and"
    ago_text = f"{member}'s account was created " + ", ".join(formatted_components[:-1]) + (f" and {formatted_components[-1]}" if len(formatted_components) > 1 else "")
vale wing
#

Up to you how to do this anyways since you seem to really want to do own implementation

tepid dagger
#

how would you get the online status of a discord.User

#

could you convert discord.User to discord.Member and go from there?

#

cus im using client.get_user to get the user, how can i go from there to get their online status if discord.User doesn't have a user.status

#

^^^

#

oh wait nvm

fiery girder
#

can you use normal discord.ext.commands.Cog for app_Commands?

fiery girder
#

thanks

fiery girder
# shrewd apex yeah

but how i add it to the discord.client since i am not using the discord.ext.commands.Bot

shrewd apex
#

u cant use cogs with client u need bot iirc

fiery girder
#

but i want to make it only on app_commands

fiery girder
shrewd apex
#

yeah

#

dont register any message commands

#

u can also remove the default help command

#

and u can disable message_content intent

fiery girder
#

i am getting this error

slate swan
#

Error says all, no need to assign a new command tree if you already have one

fading granite
#

how do i handle an exception if the original message of a thread in the forum channel is deleted by the user?

shrewd fjord
#

Use discord.NotFound or discord.HTTPException and if neither of them are correct them just catch any exception and check whats the source of the error

fading granite
#

and other bots like dyno also say command failed. i guess this is probably because the bots are not getting where the commands are getting executed. is there a way to handle this?

fading granite
#

but I'd actually written that for instances when a particular command is used outside of thread channel

final iron
fading granite
# final iron How would this throw an exception?

the original message in the thread is deleted by the user. when the user tries to execute any command in that thread, it throws 404 Not Found (error code: 10008): Unknown Message this exception

final iron
#

That’s strange, unless you’re trying to perform any operations on that message then it shouldn’t be interfering

#

Can you show the entire traceback?

fiery girder
#

can anyone tell whats this error is about

#

!paste

final iron
fiery girder
#

sure just a sec

final iron
fiery girder
#

how to check?

final iron
#

pip show discord

fiery girder
#

2.3.2

#

it is the latest version i think

final iron
#

I got no clue

#

To be completely honest

fiery girder
#

ok lol

#

i got it working i just scrapped the whole Select meny thing

#

so i just used the bot.waitfor to check for messages

hushed galleon
fiery girder
#

hmm

hushed galleon
fiery girder
#

oh

#

so i do it for all for them?

hushed galleon
#

i dont know what you mean by that

fiery girder
#
options = [discord.SelectOption(label=channel.name ,value=channel.id) for channel in guild.text_channels]
#

will this work?

final iron
#

Try it and see

hushed galleon
#

cant recall if dpy automatically converts values to strings, but i suggest you cast the channel ID to one since discord's API expects it to be a string

fiery girder
fiery girder
smoky anvil
#

Do some have the discord.py server? If so, please dm

slate swan
#

A two second Google search that you would do would've given the same answer

#

Or just reading this channel's description

#

Either way DMing is pointless

smoky anvil
slate swan
#

If you got banned, muted or whatever there's a reason.

#

And this server is not an appeal server so you can already forget about it

smoky anvil
slate swan
#

Appeal, and this server is not made for that

#

You can DM mods, and obviously Danny is probably the one everyone knows about..

slate swan
#

Yeah won't get unbanned for that kekw

smoky anvil
smoky anvil
smoky anvil
slate swan
#

Think twice

final iron
slate swan
#

Sometimes common sense is not really common

smoky anvil
slate swan
#

No

final iron
#

no

split fog
final iron
#

You were justifiably banned. Why would they unban you

smoky anvil
final iron
#

I guarantee you will not be unbanned

#

Free to try I guess

smoky anvil
#

In that server?

final iron
#

No, but it’s legitimately common sense

smoky anvil
#

ye i see, i thought regardint the fact you had picture of it

final iron
#

Only mod I believe you can get into contact with is Leonardo

smoky anvil
#

But your not a mod there, since you had picture of the reason?

#

Is Leonardo the username, cause he is not accepting friend request

split fog
#

Also dont expect anyone to accept a friend request from a guy they banned

smoky anvil
split fog
#

Take the ban

smoky anvil
split fog
#

Correct

smoky anvil
final iron
young dagger
# vale wing Looks ok but that's 8 lines

I changed it to 4 lines:

    difference = relativedelta(datetime.datetime.utcnow().replace(tzinfo=None), member.created_at.replace(tzinfo=timezone.utc))

    time_units = [("year", "years", difference.years), ("month", "months", difference.months), ("day", "days", difference.days), ("hour", "hours", difference.hours), ("minute", "minutes", difference.minutes), ("second", "seconds", difference.seconds)]
    time_units = [(singular if value == 1 else plural, value) for singular, plural, value in time_units if value != 0][:3]

    account_created_at = ', '.join([f"{value} {name}" for name, value in time_units])
vale wing
smoky anvil
vale wing
#

Implementation is up to you

#

My advice is to use pendulum and not reinvent the wheel, but you are free not to follow this advice and write your own

young dagger
glad cradle
unkempt canyonBOT
glad cradle
#

also you can use Black to format your code to make it more readable

#

!pypi black

unkempt canyonBOT
glad cradle
#

if you're interested in a tool that checks if you follow various conventions you can also look into

#

!pypi ruff

unkempt canyonBOT
#

An extremely fast Python linter and code formatter, written in Rust.

slate swan
#

main.py

import discord
from discord.ext import commands
from dotenv import load_dotenv
import os

# Load environment variables from .env
load_dotenv()

# Grab the bot token from environment variables
TOKEN = os.getenv('DISCORD_TOKEN')

# Check if the token is missing
if not TOKEN:
    raise ValueError("Discord bot token not found in .env file")

# Define intents
intents = discord.Intents.all()

# Create an instance of the bot with a command prefix and intents
bot = commands.Bot(command_prefix='!', intents=intents)

# Load all cogs in the 'cogs' folder
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        cog = f'cogs.{filename[:-3]}'
        bot.load_extension(cog)
        print(f'Loaded {cog}')


# Event: Bot is ready
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')
    print('------')

# Run the bot with the grabbed token
bot.run(TOKEN)

ping.py

from discord.ext import commands

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

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

def setup(bot):
    bot.add_cog(ExampleCog(bot))

this gives this error

discord.ext.commands.errors.CommandNotFound: Command "ping" is not found```
#

por why

timber lotus
#

dont forget to under the import but before the on_ready
Example_Cog = ping.Example_Cog

#

but now im looking and what you put seems to load all cogs? got me thinking if i should use that now so disregard my messages hahha

final iron
final iron
timber lotus
#

globally up to an hour. guild is faster.

final iron
#

Nor is it correct

timber lotus
final iron
tepid dagger
#

how could i make a while loop that is always checking for a user to be offline/online but only do something when their online status changes,

if i use while True: it'll spam so how can i do this without spam and only when the Member.status changes

final iron
tepid dagger
#

can you show an example

#

idk how to use that

#

and also i did not know that existed

final iron
#

It's an event

tepid dagger
#

oh

final iron
#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.

This is called when one or more of the following things change:

• status

• activity

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

so it's just

#
@client.event
async def on_presence_update(offline, online)
#

how does it work

#

ill read the docs first tho hold on

#

im getting an error

#
@client.event
async def on_presence_update(member.status.offline, member.status.online):
  code

why doesn't this work, it says it's a syntax error

shrewd apex
tepid dagger
#

yea but what do i put in before, after

shrewd apex
#

just before and after they are Member objects before and after the change

tepid dagger
#

example?

shrewd apex
#

u can acess attributes using before.status

tepid dagger
#

wdym

#

can you fully write out what i could put in before, after

shrewd apex
#
@client.event
async def on_presence_update(before, after):
  print(before.status, after.status)
#

u need to acess the attributes in the code not parameter

tepid dagger
#

Oh

#

so you actually just write before, after

shrewd apex
#

yeah u can write anything a, b, c, d whatever u want which is a valid identifier

#

then do like a.status or b.status

tepid dagger
#

but how do i get before, after

#

to tell me when a member goes from offline to online

#

a specific member

shrewd apex
#

!d discord.Member.status

unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str) instead.
tepid dagger
#

ik but how do i encorporate this w/on_presence_update

#

before = member.status == discord.Status.offline??

shrewd apex
#

yeah when before.status is offline and after.status is online

#

just use a if condition

tepid dagger
#

to do what

#

what would i use an if for

shrewd apex
#

!d discord.Status

unkempt canyonBOT
#

class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) ‘s status.
shrewd apex
#
if before.status == discord.Status.offline and after.status == discord.Status.online:
   print("member is now on")
tepid dagger
#

wait

#

how do i define before

#

is before a discord.Member

#

and how do i define after

shrewd apex
#

yes

#

u don't it's passed as a param

tepid dagger
#

like
before = guild.get_member(id)
after = guild.get_member(id)

tepid dagger
shrewd apex
#

yeah it's passed as a param you don't need to define it yourself

tepid dagger
#

so before is automatically a discord.Member

shrewd apex
#

yes

tepid dagger
#

but how do you know which member

shrewd apex
unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id)
shrewd apex
#

read the docs

tepid dagger
#

yea

#

so i define before and after like this right

shrewd apex
#

no

tepid dagger
#

then how does one do it

shrewd apex
#

in the parameters

tepid dagger
#

?

#

you define the user in the parameters

#

cus how does it know which user i wanna check for, where do i tell it

shrewd apex
#

i think its better you learn a few python basics before trying discord bots

tepid dagger
#

.

tepid dagger
#

ohh

tepid dagger
final iron
tepid dagger
#

yea idk how to read docs, but im better than i used to be do not read the old stuff i used toa sk

#

where do i learn how to read docs

tepid dagger
# shrewd apex in the if condition

bro am i blind where do i define the member,

@client.event
async def on_presence_update(before, after):
  guild = client.get_guild(id)
  member
 = guild.get_member(id)
  
  if member.status == discord.Status.offline and member.status == discord.Status.online:
    stuff

i also tried

@client.event
async def on_presence_update(before, after):
  guild = client.get_guild(id)
  member = guild.get_member(id)
  
  if before.status == discord.Status.offline and after.status == discord.Status.online:
    stuff

but that didn't work

shrewd apex
final iron
tepid dagger
#

i don't understand it

#

well i can use it within discord.py (sorta) but i never learned it properly

final iron
tepid dagger
#

no

#

lol

final iron
#

They are both instances of discord.Member, the first being the old information, the second one being the new one with the updated presence

#

Do you understand that?

tepid dagger
#

yea

#

so ik i need to define the before and after

final iron
#

Do you know what an instance of a class is?

tepid dagger
#

sort of

#

oh yea i do

#

can i define before.id = id before the if statement

#

oh nope i get an error

final iron
# tepid dagger sort of

Which of the following 2 is creating an instance:

classroom = SchoolBus
classroom.students
classroom = SchoolBus()
classroom.students
tepid dagger
#

the second one i think

final iron
#

Good

tepid dagger
#

cus you pass params inside

final iron
#

Well it's actually because you initialize the class with (), but anyway

#

Share your current code and we'll work from there

#

Also, which IDE are you using?

tepid dagger
#

replit bc idk where to host stuff

#

😢

final iron
#

No autocompletion, so that's making it more difficult for you

tepid dagger
#
@client.event
async def on_presence_update(before, after):
  guild = client.get_guild(id)
  member = guild.get_member(id)
  before.id = member.id
  after.id = member.id

  
  if before.status == discord.Status.offline and after.status == discord.Status.online:
    stuff
rugged shadow
#

replit has autocompletions iirc

tepid dagger
#

no replit has autocompletions

#

but they are really bad

#

so i just don't use them

tepid dagger
final iron
final iron
tepid dagger
#

idk where to pass the member id

tepid dagger
final iron
#

That'll make it easier

tepid dagger
tepid dagger
tepid dagger
#

for some rsn

final iron
#
if before.status == discord.Status.offline and before.status == discord.Status.online
#

This will never be true

sick birch
#

a user cannot be offline and online at the same time

tepid dagger
#

oh bruh what

final iron
#

You also don't need to check the after ID as it's impossible to change

tepid dagger
#

i thought that was after

#

wait no that was a dumb question

#

now it's dming me twice

#

but it works

#

thanks

tepid dagger
# final iron You also don't need to check the `after` ID as it's impossible to change

why is it DMing me twice instead of once

@client.event
async def on_presence_update(before, after):)
  guild = client.get_guild(guild)
  member = guild.get_member(id)

  async def send_text():
    await user.send('text')

  before_offline = before.status == discord.Status.offline
  id_check = before.id == member.id
  
  if before_offline and after.status == discord.Status.online and id_check:
    await send_text()
final iron
tepid dagger
#

ik

#

but why is it Dming me twice

#

i just like the variable and function declars because it makes the code easier to read

#

for me, and it's also less stuff to type if i gotta check more conditions

#

i could prob make a function that legs me plug in conditions

#

or a class

tepid dagger
loud junco
#

@vale wing am i doing this wrongly

#

am i doing it wrongly 😭😭😭

tepid dagger
# final iron ```py guild = client.get_guild(guild) member = guild.get_member(id) async...

i simplified it to this:

@client.event
async def on_presence_update(before, after):
  user = client.get_user(id)
  special_message_list = ["one","two", "three"]

  async def online_conditions(special_condition, index):
    if before.status == discord.Status.offline and before.id == id and special_condition:
      await user.send(text)
      await user.send(special_message_list[index])

  await online_conditions(after.status == discord.Status.online, 0)

  await online_conditions(after.status == discord.Status.idle, 1)

  await online_conditions(after.status == discord.Status.dnd, 2)

  if (before.status == discord.Status.online or before.status == discord.Status.idle or before.status == discord.Status.dnd) and after.status == discord.Status.offline and before.id == id:
    await user.send(text)

it still DMs twice for some rsn

#

the code actually works though

rugged shadow
#

so it's supposed to be aoi -c "your db path"

final iron
loud junco
tepid dagger
#

or is it?

#

cus it's been DMing twice the whole time

final iron
tepid dagger
#

can i define them outside but use them inside, is that a more conventional practice

#

cus i don't wanna write the same lines 3 times

final iron
#

You take the items you need inside the function as parameters

tepid dagger
#

what about the DM twice thing

final iron
#

Has it been double messaging the entire time

tepid dagger
#

yea lol

final iron
#

fyi your function actually complicates things, it can be done simply in 1 line

tepid dagger
#

might just be replit being replit

loud junco
#

i created a table with this

#

but what do i write here now

#

cuz there is no name for this database

final iron
#

What is aoi

#

!pypi aoi

unkempt canyonBOT
tepid dagger
final iron
#

Why are you using it

shrewd apex
final iron
#

More than ideally lol

final iron
#

Or just do it normallly shrug

loud junco
#

so what do i do 😭😭😭

shrewd apex
final iron
#

await execute("your query here")

shrewd apex
#

and databases

timber lotus
#

is it easier to just restart sometimes when you changed a bunch of sutff and now keep getting errors?

final iron
#

There's a ton of database visualization apps you can use

final iron
#

jsk will allow you to easily run queries in real time

loud junco
timber lotus
# final iron How many errors are there

its not that im gwetting alot of errors, im just getting errors on stuff that was working perfect before and i feel maybe from debugging, ive changed so much that now the original error is still there plus other stuff

#

and im so lost lol

shrewd apex
final iron
timber lotus
# final iron What stuff did you change?

well i everything working perfectly (giveaway commands for a discord bot) originally i didnt realize i was storing the data internally and was resetting on bot restarts so i switched to a sqllite 3 database, thats when i started getting errors. i finally got everything working and tried adding a couple more commands and save some stuff in the database and now im getting invalid integers for duration when that was working perfect before. and im just lost now

final iron
loud junco
final iron
loud junco
final iron
timber lotus
# final iron What are the errors looking like

its just printing this to console --
11 line 75
Error: 'duration' must be a valid integer value: Invalid integer value for duration
1 line 76
Failed to create giveaway: 'int' object has no attribute 'days'

i traced it back to a section of code. but no idea why --i
print('11 line 75')
time_left = 0
try:
if isinstance(duration, int):
time_left = datetime.timedelta(hours=duration)
else:
raise ValueError("Invalid integer value for duration")
except ValueError as e:
# Handle the case where duration is not a valid integer
print(f"Error: 'duration' must be a valid integer value: {e}")
print('1 line 76')
time_left_str = self.format_timedelta(time_left)
print('2 line 79')

loud junco
loud junco
#

lemme create a file then

loud junco
final iron
#

.db

final iron
loud junco
timber lotus
shrewd apex
loud junco
final iron
#

It's a weird name but if it connects, it connects

shrewd apex
#

why are u on onedrive? also try not to have spaces in filenames and path names

loud junco
shrewd apex
loud junco
#

;-; im trying to do explosive kittens on discord

timber lotus
shrewd apex
loud junco
shrewd apex
#

just jk

loud junco
#

1 is outputted but not 2

shrewd apex
#

what's the error

#

i dont see u defining self.db

#

i setup_hook u need to do self.con = await aiosqlite.connect

#

and then use the self.con instead of self.db

#

also u can just use self.con to execute directly

loud junco
#

i dont understand 😭

loud junco
shrewd apex
#

@loud junco

#

check the docs link above

loud junco
#

ok thanks

loud junco
shrewd apex
#
self.db = await aiosqlite.connect(...) # in setup hook

# in execute
cursor = await self.db.execute(query, args)
await self.db.commit()
return cursor
#

note: the cursor can be used to execute stuff too

#

just be consistent

halcyon magnet
#

Maybe you can use a context manager for it?