#discord-bots
1 messages · Page 330 of 1
if after: will still log mutes etc
we're assuming that after = after.channel
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
Same result
I only want count events related to joining or switching voice channels and leaving voice channels
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
!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.")
For which condition?
i think that should be fine but might be better to be explicit
So how would you do it?
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
Thanks
hey guyss, can someone please tell me whats wrong with my code
Your indentation in the cog is wrong, and you can't be editing your database like that in the __init__
can you please help me with that, im learning db like 3 days and this is first time adding db to cog, im so confussed
This has nothing to do with SQL. You need to deindent your commands inside the cog by 1 level, and you're trying to use asynchronous functions without awaiting them
okayy, i actually fixed it like this
do you this its good solution or no?
what's the point of it
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
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?
That's not what on_ready does
ohh, than im sorry, i so confussed ._.
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
the event is called/triggered when the client has finished preparing data that is received from discord.
oh okayyy, so is there any better way to connect db to cog?
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))
tickets2 needs to have a setup function that executes commands.Bot.load_cog()
I'd view the docs for information on how to create cogs/extensions
you don't as he is importing it normally, right
Oh yeah the naming messed me up
Seems like it’s unable to import ticket2 from wherever he’s running it
I fixed it already
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.
You mean sending a message at 12:00 PM?
mhmm
Just make the bot check for that time with a async function and when the time comes, send the GIF
!d discord.ext.tasks.loop
@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).
note the time kwarg
Thanks!
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?
!d discord.Client.wait_for
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**...
send the questions and wait for the message events
how? smth like on_message?
# 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
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')
Сигма
@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?
yeahh that's what i was about to say haha
i was going to try the decorator
but i've had no luck with those.
you can do
role = discord.Object(id=)
'function' object is not iterable - this is what i got
or you can do
for role in user.roles:
if role.id == YOURID|
i'll give it a go
and at the end of the if statement add a break statement so it wouldnt go for long
that didn't work either sadly
hmm
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)
role = ctx.guild.get_role(role_id)
if role is None:
await ctx.send("Role not found.")
return
# Check if the user has the specified role
user_has_role = any(r.id == role_id for r in ctx.author.roles)
try this]
you can also use an if statement
why are you giving me gpt resposnes dawg.
it helps
sometimes if you are stuck
sigh, if i wanted gpt i would've gone there myself
ok then lemme get one from my brain
the decorator works @app_commands.checks.has_role(1189185186789851187)
but it's not outputting any errors
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
if you look at my code, it's practically the same
is on_command_error an event?
alr one sec
@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
i think its an event
see the one i did
works like a charm
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?
yours is for regular commands, mine is for slash commands
its for hybrid
i got ths for GPT
@bot.command()
async def get_user_colors(ctx, user: discord.User):
nitro_user = user.premium_since is not None
banner_color = user.accent_color
if nitro_user:
theme_color = user.color
await ctx.send(f"{user.name} has Nitro! Theme Color: {theme_color}")
else:
await ctx.send(f"{user.name} does not have Nitro. Banner Color: {banner_color}")```
wait lemme check the docs rq
it does work
ty
its same for both
okay fair, mine still is not working haha
@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
yeah that didn't work either
bruh
that's what i said
it should work
it doesn't 
see
Since never. That code won’t work
!rule GPT
Using ChatGPT is not helpful
it is helpful miltiple times
No it isn’t, and you don’t know what you’re talking about
ok then my bad
Yes, because you’re using prefixed commands. OP is not
i use hybrid
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
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.
i've fixed that <3 thank you anyways
@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?)
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).
I’m getting None instead of the hex color
Read the note as well as the description of the attribute
rx = user.accent_color or (await self.bot.fetch_user(user.id)).accent_color
I did
its required for the user to set an accent color
- no banner
did you check anything else?
Ok this have Administrator role
and its in my server, but my bot just work in Private Message
Can you send a screenshot of the whole thing please
What i should do
what
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
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.
??
this is something else entirely
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)
Intents is different from scopes.
Ok lets say
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?
Follow what the error says.
You shared an error above.
yes you said "Intents is different from scopes." and i understand the error.
but the main error now is, why my bot work only in private messages and not in my server with invite
You need the message_content intent.
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
dude
Do you get an error message?
nah , the bot just doesnt replies with anything
can you help me
where
anyone ?
can you help me
?
I want to learn programming
freecodecamp
discord a few years ago introduced the message content intent which prevents your bot from receiving the .content of messages unless you have it enabled (or you mention the bot/direct message it), so you'll need to enable it in the dev portal and in your code to have it work normally
you'll find it here in the dev portal
Hey
i dont now
finally omg thank you so muhc
thank you soo much kind sir
its working now , ive learnt
thats a good website
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?
everyone sees the same thing, so you might want to filter those users in the callback or interaction_check
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!
Do you still need help?
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
make it a command
hard to parse irregular text like that without AI or language learning models
make a regex
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
Ahhh, that sucks, but I appreciate it
I’ll talk with the server owner, see if it’s feasible still!
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
And in context of financial operations bot such mistakes are not tolerable so yeah command is the ONLY way
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!
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)
You self host on what and what db are you using
i self host it
and im using postgres but at this point any db works for me
!rules
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.
no way this breaks the rule 😭 (╯°□°)╯︵ ┻━┻
its literally about how to connect db to my bot
are you looking for cloud database or you're trying to use local host?
local host
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
Cloud db will use more data
then i will go with local host then
but idk how to set up postgresql locally
i tried using the postgres app but its just too complicated (its called pgadmin3 if not mistaken)
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
u have any tutorial vid or guide for it?
i tried finding it but cant find any
thanks!
https://aiomysql.readthedocs.io/en/stable/
This is aiomysql the async version
if you understand how to use the normal MySQL it shouldn't be hard to learn this
its similar enough
you also need to learn the SQL language to run sql commands
https://www.w3schools.com/sql/
Local host doesn't say anything, what is the OS
ik this dw thanks anyways
window
what is this
How much ram you got
Well for basic docker bot hosting see this https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
but docker needs money
You don't need github actions, just the docker part
You can run mysql inside docker as well
but what does it do
You can run a whole operating system inside docker
You can go to website and read ☺️
i read it
but my bot is not that big so its fine
It doesn't matter lol
ok whatever
lemme try using it
thanks :D
Trust me docker is a tool worthy to learn
its for running it for 247 isit
You can shutdown it any time
i see ok
how to setup coustom status
Where to learn just Interaction commands.
For bot you can set "watching" or "streaming"
Cuz discord doesnt allow prefix commands no more ig
They do but you need messages content intent
"As prefix commands are not blacklisted the message content intent will not be granted for bots still using prefix commands."
Thats basically saying they will not give me my intent until i switch
Anyways answering original question, I think this is the guide since it's still pinned https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
404
Well if you are using intent for something other than prefix commands you can easily get it
Ight that's a pity
Yeah, but if they know you are using prefix commands... can't they just fully deny you at all costs?
I don't know up-to-date guide for discord.py, but can give you one for disnake
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
ew
No they can't (unless you lied (they actually don't care))
Bruh
Why such reaction 😤
They were complaining so hard in the emails istg
maybe cuz i only mentioned hybrid 
but besides the point!!
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
Yeah had to rewrite that first bot to slash commands, ended up gathering international team from this server
Well make them slash 😏
So they would still give the intent if i just mention something else based on the intent? instead of mentioning the hybrid?
Ion wanna learn interaction bro 😭
thats another 10 years of my life down the drain atp 😭
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
It's not that different (if you use disnake, for dpy it's very different and bad)
rn trying to get my fucking presence Intent
L disnake
W disnake
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 
Easiest one of the 3 imo
Imagine typing interaction.response.send_message can't relate, can just inter.send 😜
ite bro
Ok just be honest to deez cord 😔
I am tho 
i have a card n everything 😭
not the best, but thats besides the point 
But what do you needed presences for
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 = ''
elif 'dnd' in status:
status = ''
elif 'idle' in status:
status = ''
elif 'offline' in status:
status = ''
```
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
Watching
"The bot requires presence intent to provide better experience to its users. For instance, it automatically configures notifications level based on current user status, adjusts general experience. It is worth mentioning that presence data is not stored and does not get passed to third parties."
W mans
But actually is it really needed
Cause I personally wouldn't care if bot showed my status (like cmon I set it by myself)
"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
One way to do that is pass activity kwarg to Bot constructor
Proof for one.
!d discord.ext.commands.Bot see constructor params
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.
other things I cant really prove XD
Well what purpose does that feature serve? User can easily access status info from discord
I'm kinda saving you time from discord asking same question
It makes it look cool 😭
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
Ok wdym by "be bothered"
Gn
Bot can not bother user
bro what is your status 💀
phub
Does it spontaneously mention users without their consent
Totally bro 😭
insane
real
it has features like with most of my commands it will send a message to the user if blah blah blah
like if warned, or banned, or this or that
thats something my bot would do
which if on dnd, we will pass
Real
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
W bot
send link?
sent
ive stopped developing it for a while now
so there are some unfinished features
Bro actually made the bot
I was joking, I thought u were too 😭 not adding it in any servers tho
No offense, but it just has admin for its only perm ya know 😭
lmao
Fair enough
not looking forward in promoting the bot anyway
kinda buggy and unfinished
In py?
yea
using pycord lib
i mean its similar enough
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
I've heard next cord is good? But idk atp, I think dpy is best imo
except bridge commands i think
idk ive heard it was buggy? Maybe it's not so now
Who knows
who knows
I was gonna use next cord before I found hybrid commands
But then I found hybrid commands :)
Lmao
bye
Gn
night
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
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.
from discord_webhook import DiscordWebhook
ModuleNotFoundError: No module named 'discord_webhook'
i installed it it says its installed but it doesnt work
What do you need this module for
so basically it reloads the cog at a specific interval?
No, reload is initiated from external function
https://paste.pythondiscord.com/HAHA lmfao what a paste code
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
Ye ig
i have no clue what your code does but shit looks overly complicated

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 💀
hmm iirc importlib.reload is only when u import the stuff as a module like import abc instead from abc import d
still quite useful
@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
I know discord bot's banner color it's according the avatar
But i dislike the color
Is it possible to change in code?
Nope
Okay
Whats the point of app_commands when you can use hybrid commmands is there an advantage for using app_commands
app_commands for those who strictly wants their bot to be slash only and they might remove hybrid anytime soon
That's precisely what it's there for
It reloads modules and not extensions
Cause reloading extensions apparently doesn't reload modules it depends on
That happens cause of dynamic update
my question why you are using a hybrid command but disabling using it as slash command
I'm disabling parent command other child commands are not disabled as slash
how do i make a app command thats a question cause i was just using hybrid but now i am thinking about moving to app command only cause idk
u mean extensions as in cogs? i was just giving a general remark
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
this is depreciated
They’re not going to remove hybrid commands lol
What gave you that idea
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
@final iron This
hybrid commands were released alongside app commands in v2.0, so should we expect app commands to disappear too?
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?
pick a library like discord.py and read their documentation to get started, and also check out the examples on their repository to get a general feel for how the library can be used
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.)
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?
Not sure what he was referring to as slash commands and prefixed commands will not be leaving any time soon
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
This channel is for discord bots
You’ll be better off trying your luck in a telegram specific server
what would you lose if you help me and answer my question? THANK YOU FOR YOUR GREAT HELP
Nothing lol
I’m saying you’re not going to find many people with telegram knowledge in this channel, as its for discord bots
ok, sorry for being mad at you.

😂
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?
So you want 3 separate options, with these restrictions?
yes, if at all possible
I'm willing to change frameworks as well, this bot is solely for this command
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
I can work with that
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
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...
Oh it does allow floats
Yeah, so you’ll use Range for the integer and float. That’ll get you all three
absolutely perfect, thank you so much for that!
How can I format member.created_at to something like
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?
Probably just subtract created_at from the current date time then format the resulting timedelta however you want
ephemeral kwarg
what line of code should I put ?
InteractionResponse.send_message() has an ephemeral kwarg
make it true by default ong
Well, it’s very often that you want other users to see the output, to true by default is a pain
How do you handle number of days in a month that can vary?
Discord handles it
thank bro
Oh wait if you wanna not deal with that just pass created_at to utils.format_dt with the 'R' format if I recall correct
<t:123:R>
I don't want to use utils.format_dt because it's not the format I'm looking for
Can you show me an example of that?
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
dose any one know how can i create a time out command ?
Why? People can just do it through the discord UI, and it properly shows up in the audit log
idont know when like some one leves u can timeout him with the id
You can't time people out if they're not in the server
nice im out of date now ]
Save their id somewhere when the command is used and time them out when they re-join
?
This was never possible, even since timeouts were implemented
It just doesn't make sense
i have allready done this
i didnt use discord.py sen 2021
Then I don't understand what your question is
What you're asking has never been possible
The Discord API doesn't allow it
How do you send a link/url without the big ass thing that popsup again?
nvm figured it out 😄
fwiw that “popup” is called an embed
.topic
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
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?
Ig, if mysql doesn't have pools
You need to use sql placeholders instead of f strings
oh no here comes the nightmare
Otherwise you're vulnerable to sql injections, not in this concrete case tho
what does this mean tho
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
i have to do that in every file? 😭
Utility to open connections as you need
In what files?
command file
You just gotta write queries correctly
make it a bot var?
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
i have a database app installed
cuz i did a school project with that
and im lazy to download another one
Sqlite doesn't require you to install anything
https://docs.python.org/3/library/sqlite3.html check sync builtin lib for basic understanding
Don't use it with bot tho, you will need aiosqlite
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)
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)
See one of my projects https://github.com/Exenifix/birthday-bot
How can I format member.created_at to something like
No, this one is not using utils.format_dt
this in main.py
then i can use this anywhere right?
Sure, as long as you have bot instance
wait shouldnt i just go await bot.execute...
why do i need to data = await box.execute
Because SELECT query returns stuff
If you execute something like INSERT or DELETE you obviously don't
oo i dont need select
What about just using divmod?
By converting seconds into years, months, weeks etc
but im using mysql tho and i dont think mysql syntax look like this 😭😭😭
You can of course, up to you
Although personally I wouldn't waste my time writing those functions and just use ready module
I can't find any attribute for pendulum that does that for me
Second, imma check
Interval.in_words()
Gonna look like
(pendulum.now().naive() - o.created_at).in_words()
i tried to modify the syntax for mysql
but its not working 😭
Mysql is different since it's server db
And yeah constructions vary from lib to lib
Why do you need mysql tho?
but how do i install aiosqlite
pip install aiosqlite
how do i create db tho
cuz it has no interface or stuff
If there's no file path present it will automatically create new
ok thanks
It got no interface because it's file-based database
i see
thanks!
where do i do sql query tho (i want to create table)
do i need to create a file and run it
or i can just do it in terminal
For queries can use external soft like sqlite studio, db visualizer, some IDE extension, or cli tool like aoi from sarth (iirc it's called that)
what is cli tool
CLI is command line interface
DAMN SARTHAK MADE IT
ive seen $python blah blah
but idk where to find it
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 "")
Looks ok but that's 8 lines
Up to you how to do this anyways since you seem to really want to do own implementation
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
can you use normal discord.ext.commands.Cog for app_Commands?
thanks
but how i add it to the discord.client since i am not using the discord.ext.commands.Bot
u cant use cogs with client u need bot iirc
but i want to make it only on app_commands
is there a way i can make discord.ext.commands.Bot only for app_commands
yeah
dont register any message commands
u can also remove the default help command
and u can disable message_content intent
Error says all, no need to assign a new command tree if you already have one
how do i handle an exception if the original message of a thread in the forum channel is deleted by the user?
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
i tried all of these and when I try catching a general exception and print it says 404 Not Found (error code: 10008): Unknown Message.
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?
How are you handling the error?
i tried catching specific exceptions of NotFound and HTTPException, but they didn't work. so I caught general exception as e that sends an embed
but I'd actually written that for instances when a particular command is used outside of thread channel
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
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?
Show the full traceback
What discord.py version are you using
how to check?
pip show discord
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
self.options.append(channel.name for channel in self.channels) you've appended a generator to the options, but Select(options=) is supposed to take a list of SelectOption instances
hmm
e.g. options = [discord.SelectOption(label="Hello...", value="world!")]
(see also https://discordpy.readthedocs.io/en/stable/interactions/api.html#selectoption)
i dont know what you mean by that
options = [discord.SelectOption(label=channel.name ,value=channel.id) for channel in guild.text_channels]
will this work?
Try it and see
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
i scrapped the plan and deleted all the code so yea
i can just do py f"{channel.id}"
Do some have the discord.py server? If so, please dm
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
The problem is, i need to get in contact with a staff, can not join the server…
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
Of course, but isnt there a way to get a unban?
Appeal, and this server is not made for that
You can DM mods, and obviously Danny is probably the one everyone knows about..
Yeah won't get unbanned for that 
I know, do they even have appeals?
Wow, so unban is impossible?
You know that?
Think twice
Considering you were DMing multiple people advertisements, yes lol
Sometimes common sense is not really common
.. Ooh, there is no appeal form?
No
no
It is getting rarer every day
You were justifiably banned. Why would they unban you
I could try at least, obvously i have learned something from it..
No, but it’s legitimately common sense
ye i see, i thought regardint the fact you had picture of it
Only mod I believe you can get into contact with is Leonardo
Thanks a lot
But your not a mod there, since you had picture of the reason?
Is Leonardo the username, cause he is not accepting friend request
You can search on discord ids and that ban command was sent in general
Also dont expect anyone to accept a friend request from a guy they banned
What do you recommend to do?
Take the ban
= Give up
Correct
Equals the opposite to my philosophy
Unfortunately this is out of your control
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])
You certainly didn't make it more readable
Ye, i will do what i can
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
Are you saying that there are no comments?
!pep 8
if you're interested in a tool that checks if you follow various conventions you can also look into
!pypi ruff
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
im new but i just had this issue, try adding _ between the name and cog like
class Example_Cog(commands.Cog, name ="Example Cog):
and then load on main, under on_ready like this
await bot.add_cog(Example_Cog(bot))
but also it takes some time for commands to update if you starting and restarting your bot alot, i also learned that recently
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
what library is that?
I would get rid of whatever tutorial you're following, as it's about 2 years out of date
but also it takes some time for commands to update
This isn't true
thats what i read in the documentaion, could take up to 15 minutes for bot tree to sync. let me see if i can find it again
globally up to an hour. guild is faster.
This isn't documentation
Nor is it correct
then show me whats correct please
Prefixed commands don't need to be synced at all
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
Why not just use on_presence_update
It's an event
oh
!d discord.on_presence_update
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...
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
its
@client.event
async def on_presence_update(before, after):
code
yea but what do i put in before, after
just before and after they are Member objects before and after the change
example?
u can acess attributes using before.status
@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
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
but how do i get before, after
to tell me when a member goes from offline to online
a specific member
!d discord.Member.status
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.
ik but how do i encorporate this w/on_presence_update
before = member.status == discord.Status.offline??
yeah when before.status is offline and after.status is online
just use a if condition
!d discord.Status
class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) ‘s status.
if before.status == discord.Status.offline and after.status == discord.Status.online:
print("member is now on")
wait
how do i define before
is before a discord.Member
and how do i define after
like
before = guild.get_member(id)
after = guild.get_member(id)
i mean in the function
yeah it's passed as a param you don't need to define it yourself
so before is automatically a discord.Member
yes
but how do you know which member
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id)
read the docs
no
then how does one do it
already defined
in the parameters
?
you define the user in the parameters
cus how does it know which user i wanna check for, where do i tell it
i think its better you learn a few python basics before trying discord bots
.
in the if condition
ohh
what do i need to learn
OOP
Functions
Classes
How to read and interpret docs
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
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
also asyncio
and before.id == whatever_id
He hasn’t sent anything that shows he doesn’t understand it
i don't understand it
well i can use it within discord.py (sorta) but i never learned it properly
Do you understand what before and after are?
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?
Do you know what an instance of a class is?
sort of
oh yea i do
can i define before.id = id before the if statement
oh nope i get an error
Which of the following 2 is creating an instance:
classroom = SchoolBus
classroom.students
classroom = SchoolBus()
classroom.students
the second one i think
Good
cus you pass params inside
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?
No autocompletion, so that's making it more difficult for you
@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
replit has autocompletions iirc
i use codespaces or vsc sometimes
guild = client.get_guild(id)
member = guild.get_member(id)
before.id = member.id
after.id = member.id
Why are you doing this?
This'll be a lot easier in VSC
idk where to pass the member id
maybe ill write the code in VSC and copy it back
That'll make it easier
should i do like
if before.status == discord.Status.offline and before.status == discord.Status.online and before.id == member.id and after.id == member.id:
code
ye lol i forgot why, i just explained how i got there
this code doesn't do anything
for some rsn
if before.status == discord.Status.offline and before.status == discord.Status.online
This will never be true
a user cannot be offline and online at the same time
oh bruh what
You also don't need to check the after ID as it's impossible to change
i thought that was after
wait no that was a dumb question
now it's dming me twice
but it works
thanks
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()
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()
All this can be simplified into 2 lines
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
^^^
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
the [] specifies that it's optional
so it's supposed to be aoi -c "your db path"
Shouldn't be nesting functions like that
i just realised that and im trying to do the db path thanks!
why not, also thats not why it's DMing twice right
or is it?
cus it's been DMing twice the whole time
It's bad practice and complicates things. Functions are supposed to be individual containers
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
You take the items you need inside the function as parameters
what about the DM twice thing
Has it been double messaging the entire time
yea lol
fyi your function actually complicates things, it can be done simply in 1 line
might just be replit being replit
how
i created a table with this
but what do i write here now
cuz there is no name for this database
^
What's the point of aoi
Why are you using it
thats an in memory db so session is persisted in ram ideally u want it connected to a file
More than ideally lol
.
Or just do it normallly 
so what do i do 😭😭😭
pretty sure vscode has extensions to visualise tables
await execute("your query here")
and databases
is it easier to just restart sometimes when you changed a bunch of sutff and now keep getting errors?
There's a ton of database visualization apps you can use
would restarting make a diff
jsk will allow you to easily run queries in real time
How many errors are there
the problem im going through now is connecting to the database
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
iirc dosent sqlite create a local db file that u connect to what's wrong with that
What stuff did you change?
What issue are you having?
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
What are the errors looking like
but i cant find it
i cant find the db file that i can connect to
Have you created one?
wait so the one i created in bash is just in a memory not a file?
Do you mean terminal?
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')
ya the git bash in terminal
.
lemme create a file then
just make it blahblah.sql??
looks kinda weird tho
.db
What what does duration look like if you print it?
thanks
let find out
sqlite3 database_name.db
im doing this correctly?
It's a weird name but if it connects, it connects
why are u on onedrive? also try not to have spaces in filenames and path names
idk but if it works it works 😭
i wil try to remove the spaces
look at the project name 😂
;-; im trying to do explosive kittens on discord
ok wow, the duration printed to what i entered as the title and not the duration. thank you. now i have a direction
sure 💀
WHAT 😭😭😭
just jk
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
i dont understand 😭
is this what u mean/
ok thanks
i dont understand the docs at all 😭😭😭
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
Maybe you can use a context manager for it?
