#discord-bots
1 messages · Page 174 of 1
See here for more information https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#bool
also one more doubt i have a configuration bot that basically works on the json file and a main bot which works on everything and everytime i like use a command of configuration bot it just throws an error in the main bot saying that xyz variable is Refrenved before assignment. The reason being for a split second the data inside json file is deleted and a new data is dumped. Any way to overcome it?
i will, tysm
I don't think the "variable" being referenced has to do with how writing to JSON works
Can you give us more information?
I think the library is called intersphinx. Refer to the @unkempt canyon source code to see how it was used. I don't know the details well.
I'll give more updates about it in the morning its almost 4 for me rn and I'm heading to bed. I'll open the lappy up in mrng and send you some snippets. My main problem as of now is resolved, thanks to you.
I get the error:
AttributeError: 'Guild' object has no attribute 'category'
What do I do?
What are you trying to do?
perhaps you meant categories?
Does seems like he wants a specific one.
I want to test if a category exists
if "category name" in [category.name for category in guild.categories]:
...
i figured it out it was categories not category
How do I create a channel in a certain category?
still gets the bots author if i do it like this
I seem to be misunderstanding you then.
So your bot is taking the post of another person and reposting it in another channel?
Code
cursor.execute(f"SELECT user FROM liked WHERE id = {user1.id}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO liked(id, user) VALUES(?, ?)")
val = (user2.id, user2)
cursor.execute(sql, val)
db.commit()
elif result is not None:
query = ("DELETE from liked WHERE user = ?")
params = [user2.id]
cursor.execute(query, params)
db.commit()
Error
cursor.execute(sql, val)
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.```
anyone knows what i need to do ?
Can i send my code to you in dm or do i just put it here? So maybe then u get what i mean?
Add the user ID to the footer of the new Embed, you will be able to access it from there as needed.
At this point it's up to you where to store the ID, I would pick footer because it's the simplest right now. Not unless you want to start learning databases.
Remove it.
With that there it's blocking all the code under it from running.
And how do i get it from the embed?
🤨
lol
message.embeds[0].footer id assume
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
ya
there we go
How can I fix this?
discord.ext.commands.errors.MemberNotFound: Member "29455219532952935" not found.
@client.command()
async def warn(ctx, member: discord.Member = None, *, reason: str=None):
if reason is None:
await ctx.send("You must provide a reason for the warning.")
return
if member is None:
await ctx.send("Could not find that member. Please try again.")
return```
How do I delete a category and everything in it in a button?
pls help
If you want to get an attachment like image or video ect from a message try "ctx.message.attachments[0].url"
someone?
explain a bit more
whats the pastebin link?
huh ?
for the python discord whats the pastebin
for python discord ?
I'll figure it out some day
!pastebin
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I was almost there
xd
i didnt understand
https://paste.pythondiscord.com/sawepaxezu
This is the code, It needs to delete the category, the text channel, and the voice channel
What you are asking for is not really what we do in this channel.
yep already put it there
but it is about discord bots so it can be both
What did they have to say?
me ?
Sorry, that's not how this works.
well to late
Good luck then
thanks
are you able to help me based on the code i sent?
What do you have so far?
@crimson mauve
with a button ? you said
looking over it
try
@discord.ui.button(label = "Create a Suite", style = discord.ButtonStyle.blurple, custom_id = "PlasmaBotsuite_button")
async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer()
suiteCategory = utils.get(interaction.guild.categories, name = f"{interaction.user.name}'s Suite")
how do I delete the category? Because it is not a channel. Also how do I delete the voice channel?
import discord
from discord.ext import commands
from discord import app_commands
bot = commands.Bot(command_prefix='!', intents= discord.Intents.all())
@bot.event
async def on_ready():
print(f"We have logged in!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command")
except Exception as e:
print(e)
@bot.tree.command(name="hello", description="say hello")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(f"Hello {interaction.user.mention}!")
bot.run(12345)# I know that is not the bot token. ````
\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 672, in connect
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.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
does anyone know how to fix this
!d discord.CategoryChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Did you activate the privileged intents on the developer portal?
i can't find it
That works! How do I search for the voice channel because the voice channel is named General and I am worried about deleting other voice channels named General?@crimson mauve
Yes
it is already enabled
i am rly confused bc it is checked it has admin perms and has no errors and it still is broken
Try this
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
like this?
Yes. Does it work
no same error
How do I add a message if memebr is not found?
discord.ext.commands.errors.MemberNotFound: Member "29455219532952935" not found.
@client.command()
async def warn(ctx, member: discord.Member = None, *, reason: str=None):
if reason is None:
await ctx.send("You must provide a reason for the warning.")
return
if member is None:
await ctx.send("Could not find that member. Please try again.")
return```
I haven't worked with tree yet so idk. It's probably tied to that
ok should i just ask around to see if anyone knows
How many commands do you have on your bot @dull basalt
1 bc i am trying to find the issue
You can grab it by ID
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
also your annotations arent correct
How do I find the channel id?
Maybe a try exception block?
What do you mean?
I would reccomend just switching to slash commands now
Now that depends.
lighgeb it is on slash commands
why did you define a command prefix
when adding default values you must provide the type of the default value if its not the same as the one being expected
TL;DR you must be explicit with default values
e.g
# Wrong
def foo(bar: Bar = None) -> None:
...
# Correct
def foo(bar: Bar | None = None) -> None:
...
You mean like this?
async def warn(ctx, member: discord.Member = None, *, reason: str=None):```
Because ZippyIstheBest* Is objectionably the best way to start any command.
Since you made an edit, my last statement is not valid anymore. No, please give a look at the annotations of arguments on both function definitions, look at both of the parameters of both functions
how
@real badger wdym
@dull basalt wdym wdym
It's still not showing any message if member not found
Don't have them both named General
then grab by name
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
I named it something different and it works
Why doesn't the "except discord.ext.commands.errors.MemberNotFound:" work for this code? https://paste.pythondiscord.com/bufayayesi
Because when an argument to a command is invalid, discord.py will not execute the code in the command - it will raise an error before it gets to that point.
If you want to have custom error handling, have a look here https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#error-handling

Thank you
How can I make my bot play song from youtube with youtube_dl ?
Downloading videos is against YouTube ToS.
It doesn't have to do with downloading videos
I just have !play command and next to it I add the youtube url and then I want my bot to play the video
youtube_dl
Command-line program to download videos from YouTube.com and other video sites
Hmmmmm
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
We won't help with projects that breach terms of service here, sorry
Ok is there another way for doing the thing I want?
Find a service that allows you to use their content in such way. Or play media files that are stored locally.
if u are just practicing u could use anime and movie websites
if i have a users authorid in a variable called id so how can i send direct messages to the player using the id variable?
await message.id.send
does not work, dunno if it's even supposed to work
await bot.get_user(id).send("Hello, world!")
so, i wanna check an arbitrary error against a bunch of dev-defined errors that might arise
however, i came upon this: https://stackoverflow.com/questions/42378726
should i worry about it?
This is mostly for iterables
Checking for errors should be pretty fast
alr cool
not sure if this is against the spirit of async in & of itself, but i want the bot to print out when it's finished syncing
print("Syncing commands globally...")
await bot.tree.sync()
print("Synced commands!")
however, this obviously doesn't work
Kick error does not get bot to send the missing perms message, instead the error just shows in the terminal
@bot.tree.command(name='kick', description='Kicks a member from the server')
@has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
guild = interaction.guild
await member.send(f"You have been kicked from: ***{guild.name}*** | {reason}")
await member.kick(reason=reason)
embed = discord.Embed(title=(f'***{member} has been kicked*** | {reason}'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":redTick: You don't have permission to use this command!")
else:
raise error```
Hey
for some reason
my welcome message don't work
and it does not have a error
when a member joins
async def dm_all(ctx, *, message = None):
if message != None:
members = ctx.guild.members
for member in members:
try:
await member.send(message)
except:
pass
else:
await ctx.send("Please provide an message!")``` I can't seem to figure out where i messed up on the indentation. error states: ``` File "/root/roof.py", line 30
except:
IndentationError: unexpected unindent``` help.
hello i created a bot
and when i write in my server i get blank strings
printed out
not the actual messages
If anyone is up to help, it would be appreaciated, im up at 1am trying to figure this issue out for 3hrs now
...
Hard to tell by looking at it, so I rewrote all the indents. Try this ```py
@client.command()
async def dm_all(ctx, *, message = None):
if message != None:
members = ctx.guild.members
for member in members:
try:
await member.send(message)
except:
pass
else:
await ctx.send("Please provide an message!")
Also, don't use except:. Catch the actual exceptions you expect to be raised.
At a minimum use except Exception:, but even then you should try to be more specific
Can you specify what you mean by "doesn't work"?
thank you
This is because on_command_error only picks up prefix commands, while you have a slash command
i mean it sends "syncing finished" almost immediately after the first message
But did it sync?
wait uh dumb question
when await is called, it does not wait for it to finish right? does it like start a new process & move on or smth?
So how can i adapt MissingPermission errors to slash commands?
@kick.error
async def kick_error(ctx, error):
...
should still work
Only the coroutine is blocked
Would anyone know why printing message.content returns an empty string aka an empty line is printed everytime i write something in my server with the bot in it
But await does await for the task to finish
That's the whole point
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
what's the coroutine here?
hard to tell since I don't have context as to what function it's in
on_ready, maybe? setup_hook perhaps
Is there a way I can make it apply for every command? Or do I haev to rewrite the code for each command
But i did nextcord.Client() which should make all intents true by default, no?
.
async def on_error(...):
...
bot.tree.on_error = on_error
No
You need to specify which intents you want
message_content is the one that gives you the content to the message
@pulsar kettle see here for documentation details https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=on_error#discord.app_commands.CommandTree.on_error
Ive enabled message content in the discord portal website so i dont know if its a problem
Have you enabled it in your code as well?
No
Do that as well
How could i do that, im quite new to this
see here
Kk
So basically i have to make the intents into code, alr will do and update u in a minute
I tried this for individual commands but it still doesn't work:
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":redTick: You don't have permission to use this command!")
else:
raise error```
I'll keep experimenting
IT WORKS
THANK YOU SO MUCH!!!
I can finally go sleep now
Tmrw is school 💀
Good luck!
hey @shrewd apex , i'm taking another look at ur pagimation and got a question.
you have assert isinstance(items, list) so if I define list as a class elsewhere in the code, whatever data is in the list, it can return that as items then right?
Add a print statement to see if it's being called at all
What do I print? (I'm being smoothbrain rn sorry)
anything
"test" , "success", "called"
Anything really
We just want to see if the function is being called at all
I usually just print 1 lol
works ¯_(ツ)_/¯
def test() -> None:
print("Robin called me")
So like this?:
@kick.error
async def kick_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send(":redTick: You don't have permission to use this command!")
print("success")
else:
raise error```
just after the function definition
Now can you print(type(error))?
oi, can anyone help me with my bot, i posted in python help
<class 'discord.app_commands.errors.CommandInvokeError'>
Task exception was never retrieved```
Ah, that's why
Is it not a missing perms thing?
The missing permission error is wrapped inside a CommandInvokeError
@kick.error
async def kick_error(ctx, error):
error = error.original if isinstance(error, app_commands.CommandInvokeError) else original
...
This will unwrap the nested error from out the CommandInvokeError container
app_commands and original "is not defined Pylance"
tbh, should just use getattr, since there are multiple error other than CommandInvokeError that wraps the error
Yeah you'd have to import it
getattr is a better approach, yeah
error = getattr(error, "original", error)
@pulsar kettle use
instead
A global error handler would probably be better then
See here for how to bind an on error to your tree
Aight, I’ll try it out 👍
can someone help it keeps saying TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'
how do i delete an application command? No matter what I try, i get every status code but 204
that happens when you pass a value which cannot be converted to an integer to int
!e py non_integer_value = {"key": "value"} as_an_integer = int(non_integer_value)
@civic fractal :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: int() argument must be a string, a bytes-like object or a real number, not 'dict'
.http_status 204
204 is not bad
does anyonne know how to make a timed mute command? i have a mute command, i just wanna make it so you can control how long they're muted for
@client.command(description="Mutes the specified user.")
@commands.has_permissions(timeout_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
await member.add_roles(mutedRole, reason=reason)
await ctx.send(f"Muted {member.mention} for reason {reason}")
await member.send(f"You were muted in the server {guild.name} for {reason}")```
cant you use datetime?
yeah thats what im trying to get..
is this the right code?
import requests
from btoken import TOKEN
url = 'https://discord.com/api/applications/903765373181112360/commands/1061192774742966342'
headers = {
'Authorization': f'Bearer {TOKEN}'
}
response = requests.delete(url, headers=headers)```
You're registering slash commands by hand?
im deleting it because it still exists for some reason even when i removed the code for it multiple days ago
Did you sync?
if this counts as syncing
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
do i need to make it global
I have a working GPT chatbot and im looking for some assistane 1. Use our current chatGPT bot build a canned response chatbot on top of it that uses a database for responses. 2. Design and implement two databases: --A "canned" database for storing previous questions and answers that have been asked at least three times. --A "live" database for storing current questions and answers that have not yet been canned. 3. Write code to interface with the GPT API and the Discord bot. When a message is received: --Check the "canned" database for a matching question. --If a matching question is found, choose one of the previous responses at random (with a 1/3 chance for each) and send it to the Discord server. --If a matching question is not found, submit the question to the GPT API and save the question and answer to the "live" database. 4. Implement an accuracy system using difflib. If a question is similar (e.g., 95% similar) to a previous canned question, choose the corresponding answer for the most similar question. 5. Create a separate process that sorts through the "live" database and populates the "canned" database with any questions that have been asked at least three times. 6. As the "canned" database grows, consider lowering the temperature and max_token values and potentially using a different model such as Curie to improve the chatbot's responses. Overall, the goal of this chatbot is to create a community database of questions and answers that can be used by future developers to reduce token costs by avoiding unnecessary API calls. The chatbot will save on token costs by using previously asked questions and answers from the "canned" database when possible, while still providing a sense of randomness and organic conversation by choosing responses at random. As the "canned" database grows, the chatbot's responses will become more cost-effective.
it refers to the main instance of your subclass, for example ```py
class Hello(discord.Client):
def run(self) -> None:
# "i overrided this method"
super().run("...")
`super()` here would be the original discord.Client() instance that Hello wraps
ohhhh
ty
how to fix
huh? you're trying to do something that is impossible
the solution is to not do that
kinda like if you said your calculator gave you an "error" when you tried to divide zero by zero
the way to "fix" it is to not try and divide zero by zero
no lol i have multiple paginators handed down so thats for typehint purposes for my typechecker
then i'm lost on how I can use it 😢 i cant just add this data and have a command include the embed i'm guessing?
for member in ctx.guild.members:
self.DataPost[f"Member: {member.name} Member.ID {member.id}\n"] = None
for role in ctx.guild.roles:
self.DataPost[f"Role: {role.name} Role.ID {role.id}\n"] = None
for category in ctx.guild.categories:
self.DataPost[f"Category: {category.name} Category.ID {category.id}\n"] = None
for channel in ctx.guild.channels:
self.DataPost[f"Channel: {channel.name} Channel.ID {channel.id}\n"] = None
or
list = []
for member in ctx.guild.members:
list.append((member.name, member.id))
for role in ctx.guild.roles:
list.append((role.name, role.id))
for category in ctx.guild.categories:
list.append((category.name, category.id))
for channel in ctx.guild.channels:
list.append((channel.name, channel.id))
cause everything i've tried, keeps giving errors unless i'm supposed to just import this into another .py, idk what else to try ;.;
is there a way to hide a bot cog from the general public? like it won't even show up in the autocomplete in non-authorized servers?
in a help command?
https://discord.com/channels/267624335836053506/1061809135303266305
can anyone help?
You can ping me here and tell me if u know, thx
You're not responding fast enough to the interaction
!pastebin
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
wdym, and how can i fix it?
either defer or respond faster 🤷
So would I have to put it at the start of the function?
defer doesn't work for my code
Because I'm trying to edit msg with a view
and I don't think you can followup edit msg unless there is
you can edit_original_response
But if i defer, I can't put the view there of making it (the button) disabled
interaction. edit_original_response?
sure
Just finished fixing the handling error portion, however even though a member without kick_members cannot kick a member, the bot still sends the kick DM to the person without kicking them. I assume it has something to do with the way I put the DM before the kick since my bot cannot DM someone it does not share a server with, so how can I fix this?
@bot.tree.command(name='kick', description='Kicks a member from the server')
@has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
guild = interaction.guild
await member.send(f"You have been kicked from: ***{guild.name}*** | {reason}")
await member.kick(reason=reason)
embed = discord.Embed(title=(f'***{member} has been kicked*** | {reason}'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
@kick.error
async def kick_error(interaction: discord.Interaction, error):
error = getattr(error, "original", error)
await interaction.response.send_message("You do not have permission to use this command!")```
Not much you can do here honestly
Either you send the message after the kick and risk having the message not be delivered or you put up with with the message being sent regardless
Wait I just realised using the kick command kicks the member but the bot responds with "You do not have permission to use this command!" even tho the kick was successful
And it also didn't DM the member
How can I show the timestamp using the format?
timestamp = infraction["timestamp"]
field_name = f"{infraction['type']} • <t:{timestamp}:f>"```
Doesn't look too good as you can tell
aight it worked, thx a lot!
You're welcome!
@sick birch sorry for ping but any thoughts?
timestamp appears to be an object? probably a datetime object?
So I need to convert it first?
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Or that
Wait now it works wha
edit: ok nvm when I have the line await member.kick(reason=reason) BEFORE await member.send(...) the bot always responds with "You do not have permission to use this command!"
However it still kicks the member
There's already a built-in kick command
Oh yeah I remember this one.
timestamp = infraction["timestamp"]
fmt_time = discord.utils.format_dt(timestamp, "f")
field_name = f"{infraction['type']} • {fmt_time}"```
Yeah but from what I know it doesn't dm the user
sure, in both help commands, & slash command autocomplete
!d discord.ext.commands.CogMeta you can pass a dictionary with its key as hidden and value as True to command_attrs
class discord.ext.commands.CogMeta(*args, **kwargs)```
A metaclass for defining a cog.
Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the [`abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "(in Python v3.11)") metaclass.
For example, to create an abstract cog mixin class, the following would be done...
Then you can filter commands in your help command and autocomplete
no direct way to do it, but you can use CogMeta.command_attrs, and set hidden to True, if all commands are hidden, it wont show up in the help command, but if you want this dynamic, you should use Cog.cog_check, help command calls each checks on a command
where do i use this CogMeta?
!d discord.ext.commands.CogMeta.command_attrs
A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:
class MyCog(commands.Cog, command_attrs=dict(hidden=True)):
@commands.command()
async def foo(self, ctx):
pass # hidden -> True
@commands.command(hidden=False)
async def bar(self, ctx):
pass # hidden -> False
this example in particular, you dont really "use" the cogmeta, the cogmeta is already with the commands.Cog
Trying to send a list of items to a typing.Literal converter using a function that calls the needed items from an external text file, but I've hit a dead end.
async def funtTags(): # Function Defining
async with aif.open((directory + '\\' + 'list.txt'), 'rt') as file: # Opens the list file
tags = await file.read() # Reading file
tags_dict = ast.literal_eval(tags) # As the file is a dictionary, I have to convert it
x = tags_dict['tags'].keys() # Get the keys
return x # Returns x
And the actual command
@client.tree.command(name='add_note', description="Save a quick note for instant access to it later!")
async def create(interaction: discord.Interaction, title: str, tags: typing.Literal[funtTags()], source: str = None): # <- Calling the function here
print('Success')
Any ideas?
Why
You will have to create your own converter class. typing.Literal does not support dynamically specifying multiple values.
It's.. complex 
Or just perform the validation within the function
How'd I do that? for the latter one?
I still have yet to learn how to do either <.<;;
!e
import inspect
import typing
attrs = {0: None, 1: None}.keys()
def cmd1(para: typing.Literal[attrs]):
pass
print(inspect.signature(cmd1))
attrs = (0, 1)
def cmd2(para: typing.Literal[attrs]):
pass
print(inspect.signature(cmd2))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | (para: Literal[dict_keys([0, 1])])
002 | (para: Literal[0, 1])
Either way, you shouldn't be doing this 🐈
Oh, so the trick is just to use a tuple instead of a list
Why so?
I'll switch to using a database if need be
async def my_command(...):
if arg != what_is_allowed:
raise BadArgument("some error message")```
If the file you're reading does not change, then you should cache its content to avoid reading it every time the command is invoked
Attempting to code a purge command, however upon running the command I always get the error discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction which I suspect is because the purge deletes the command message so it cannot reply. How can I work around this?
@bot.tree.command(name='purge', description='Deletes a specified number of messages from a channel')
@discord.app_commands.checks.has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
await interaction.channel.purge(limit=limit)
await interaction.response.send_message(embed=embed)
@purge.error
async def purge_error(interaction: discord.Interaction, error):
error = getattr(error, "original", error)
await interaction.response.send_message("You do not have permission to purge messages!")```
Like this?
async def purge(interaction: discord.Interaction, limit: int):
embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
await interaction.response.defer()
await interaction.channel.purge(limit=limit)
await interaction.response.send_message(embed=embed)```
Because if so now I get the error discord.errors.InteractionResponded: This interaction has already been responded to before
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
Triedinteraction.followup.send, but bot doesn't send Purged {limit} messages and I still get the error discord.errors.InteractionResponded: This interaction has already been responded to before
async def purge(interaction: discord.Interaction, limit: int):
embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
await interaction.response.defer()
await interaction.channel.purge(limit=limit)
await interaction.followup.send(embed=embed)```
what if u wanted to disable the kick command? 
How I can make a line break for each embed.add_field(name=field_name, value=field_value, inline=False)?
like a divider between each embed?
No same embed, between each infraction
Oh, strange.
Just use interaction.channel.send() instead
Is there any way to add new lines with (\n) in field_name?
Cool, bot now send Purged {limit} messages 3 seconds after the interaction, however the bot deletes {limit} - 1 messages, so if I input 5 it actually deletes 4 (excluding the initial command)> How can I fix that?
like for a list? ye
Each infraction is listed in field_name and field_value, same embed. I want to add a line break for each one of them
You can just add 1 if you'd like
So Purged {limit + 1} messages?
Yeh
I tried to add it there but it didn't add a new line for next infraction
I want each entry to have a space in between
for this, i think u'd be better off doing 3 embeds inline=true. so then u have 3 columns
I would like to have them separated and not inline
@discord.app_commands.checks.has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
command_message = interaction.message
await interaction.channel.purge(limit=limit)
embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
await command_message.channel.send(embed=embed)
@purge.error
async def purge_error(interaction: discord.Interaction, error):
error = getattr(error, "original", error)
await interaction.response.send_message("You do not have permission to purge messages!")
try this
STOP SPOONFEEDING
whats that
im trying to help someone out?
it was resolved in dms, if i did something wrong i apologise
giving out code without explaining what you did
im new to this server and will get inline with the rules
i apologise again, wont happen again
no it's fine it's fine lol
thanks for explaining that rule to me, ill take it into consideration next time
don't apologize smh
I'm just saying that you should explain things first
🛐
Trying to code my own AFK feature for my bot, but I am completely unsure on how I can get the bot to check if any mentioned user has "[AFK]" in their name, and if they do, the bot sends a message. Can anybody please help me out? (I will definitely need explanations because I have little idea on what I'm doing lol)
@bot.tree.command(name='afk', description='Sets an AFK status to display when you are mentioned by another member')
async def afk(interaction: discord.Interaction, reason: str=None):
if interaction.user.nick == None:
await interaction.user.edit(nick=(f'[AFK] {interaction.user.name}'))
embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
else:
await interaction.user.edit(nick=(f'[AFK] {interaction.user.nick}'))
embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)```
So far I've only got the first part of the code working which adds [AFK] to somebody's username
You'd check message.mentions inside an on_message
Loop through each Member in message.mentions, check if "[AFK]" in mentioned_member.nick
tbh a database would work much better here but yeah you can do this as a shortcut
cons would be that bot won't be able to set afk for users with higher roles
or if a user changes their nickname themselves the afk will be removed
I'm fine with that since if the AFK member sends a message it would be removed anyways
Ideally
for a decorator check like this:
def is_registered():
async def predicate(ctx: commands.Context) -> bool:
if not dm.is_registered(ctx.author.id):
raise UserNotRegistered
return True
return commands.check(predicate)
```i have to call it like so:
```py
@is_registered()
```this is a question that pertains more to python in general, but is there a way to code decorators so that parens aren't needed?
you can use the @decorator syntax but im pretty sure this syntax is not supported by Python since version 2.4
dont quote me on that though
Probably completely wrong but:
@bot.listen()
async def on_message(message):
if message.mentions:
for member in guild:
if "[AFK]" in mentioned_member.nick:
await message.channel.send(f"This person is currently AFK.")
What do I need to fix in this
!e ```py
def dont_need_to_call(callable):
def wrapper():
print("...")
return wrapper()
@dont_need_to_call
def foo(): ...
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
...
given that a check requires a context, this won't be valid for discord.py checks
but yeah you can use decorators without calling them over function
for member in message.mentions:
if "[AFK]" in member.display_name:
# member is afk
``` you don't need to iterate on each guild member
And then do I use ctx.send('...') to get the bot to send a message?
@bot.listen()
async def on_message(message):
if message.mentions:
for member in message.mentions:
if "[AFK]" in member.display_name:
await ctx.send('This user is currently AFK')
else:
return
else:
return```
Works great! Now is there a way for the bot to check if someone with [AFK] in their name sends a message, and when they do the bot replies to them and removes the [AFK] from their nick?
if i set a button to disabled with button.disabled = True,
how do i update it if is in a slash command response?
this wont work await interaction.edit_original_response(view=self)
property children```
The list of children attached to this view.
use on_message event
check if "[AFK]" in message.author.display_name
if it is, use message.channel.send/message.reply to respond
and message.author.edit to change nickname again
like this?
for item in self.children:
item.disabled = True```
this will disable all buttons yeah
yeah that works but how do i update the button for this to take effect
i agree w/ this
Bot now responds to the AFK user's message, but now how can I only remove the [AFK] part of their nickname if they have a nickname set that is different to their username?
Also the bot responds to it's own message with This user is currently AFK when they reply to the AFK user
Guys how can I keep my discord.py bot on 24/7? For free
cuz the bot mentions them lol, just add a check to return if message author is a bot ```py
if message.author.bot: return
Replit You gotta pay for hosting but there's free packages by various hosting services. Checkout #965291480992321536 @snow trench
assuming member to be the message author ```py
await member.edit(nick=member.display_name.replace("[AFK]",""))
i love the new syntax highlighting
!d discord.Member.edit is it nick or nickname
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
nick yeah
i wish it was on mobile too
The newer colors are brighter as well
Returns error: UnboundLocalError: cannot access local variable 'member' where it is not associated with a value
@bot.listen()
async def on_message(message):
if message.author.bot:
return
if message.mentions:
for member in message.mentions:
if "[AFK]" in member.display_name:
await message.reply('This user is currently AFK')
else:
return
if "[AFK]" in message.author.display_name:
await message.reply('Welcome back, I have removed your AFK status')
await member.edit(nick=member.display_name.replace("[AFK]",""))
else:
return```
On this line: await member.edit(nick=member.display_name.replace("[AFK]",""))
Indent issues prolly
assuming member to be the message author
define the variable first
Jsut noticed indents yeah
you should also continue, not return in the second if statement
ok
Everything's working as intended now, final question (sorry): If I want to put the AFK reason in User is currently AFK | {reason}, how can I pull the variable from:
@bot.tree.command(name='afk', description='Sets an AFK status to display when you are mentioned by another member')
async def afk(interaction: discord.Interaction, reason: str=None):
if interaction.user.nick == None:
await interaction.user.edit(nick=(f'[AFK] {interaction.user.name}'))
embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
else:
await interaction.user.edit(nick=(f'[AFK] {interaction.user.nick}'))
embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)```
that's where the "you should be using a database" point comes from
not possible without a database or a cache
the cache will be lost everytime the bot restarts
so database is the only dependable choice
Is it difficult to implement?
Not if bot.on_error helps u
using a database is much easier than making a bot, so you can assume 🤷♂️
depends on what database you use, but yeah it's easy
I see, because this discord bot I'm working on is sort of my first "real" entry into coding since the stuff they taught in my schools was either irrelevent or extremely simple
Kinda just learning as I go along aha
well databases are a nice to know about, it will be useful in any case related to storage
for the basics 3-4 lines of sql query is all you need to learn
Are there any notable guides I could follow that would work with my bot + others if I decide to branch out?
well first choose a database, there's mainly sql and nosql database
and both categories have flavours of own
for starters i'll suggest sqlite3 as it's inbuilt in python too, doesnt need a server setup ( it just uses a file in your project ) and doesnt need much effort to learn
20-30 minutes is all you'll need to put to learn basics
Aight I'll look into it, tysm for you help <3
Wait what, I've been using mongo, I need to look into that
For sql you can use sqlbolt
a github repo for bots?
?
thats it. thank you
how do you make slash command input suggestions like so:
discord.Option(discord.Role, 'Choose a Role')
thanks
what's your issue
i just need an example to start from but i cant find any good ones on the internet
https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-redirect-url-example
there;s examples in the docs, on the top of it i'll suggest using hikari instead, it has proper integrations for oauth and stuff
ay thank you
that is quite helpful
mmmm ┬─┬ノ( º _ ºノ)
what pls help me
?
how do i detect if the message author is a webhook or not
!d discord.Message check attributes and find out, that's how you use docs
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
i didnt find any think related to webhook there
.
oo webhook_id
should i fetch the webhook by channel.fetch_webhook?
oo got it client.fetch_webhook
@light violet, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
@light violet, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
@vale wingwhy am i getting the url after fething as discord.com/api/webhooks/1061921432981995531/None
none as token?
wtf
cant get the url by myself also how the heck
its blocked
@sick birch im making a premium user command or admin command, so that the only people i add in the bot can use the command, now when i type -config_addadmin <id> It adds the id to the config file but doesnt work until i reload the json. Any way to solve that?
you need to open the json every time you want to access the data
while everytime i call on_message
im calling with open('config.json') as f:
etc
and loading the owner_id too
pls help me also
can you show a bit of your code around here?
yea
idk why that would be happening really
why don't you load the file using json.load(f) though, I think that is easier than opening the json file and extracting content as a string and then turning it into a json object
oh
I'll try
i fixed it, it was taking a global variable as the config file. I changed its variable to smth else and works now tysm ash
nice
why is it
hiya, how would I run an async function in the background? I need to run a while loop to check the time but want to be able to use other functions concurrently
just use the inbuilt task loop by discord.py
check perms
it has admin even i am getting that button blocked
also lol dont share webhook anyone can use it to spam the channel
that copy url button
idc
@shrewd apexsee this
how is it
?
i have a bit of experience in dpy
whats the problem
nvm u sent the code
from my memory that should work?
if your code is running you're on an ancient version of discord.py
update discord.py, the code for sending message is wrong
or theres a possibility its a self-bot, considering that error has been given a lot with selfbots using embeds
im not familiar with selfbot libraries so idk
yeah no client.send_message is not a thing
you can make them on discord.py
not anylonger
discord has discontinued the api version that self bots need, even if you selfbot you won't be able to read messages without fetching
someone tried that lol
why dont you try ctx.send(embed=embed)
well it works for me
no need to define mess ch
You are not allowed to use that command here. Please use the #bot-commands channel instead.
shut
have u updated ur dpy
reinstall dpy
why was it an older version anyway?
try that line and gimme the error
did u reinsall?
see the console log the lines with error and show me
so your randomjoke command has some flaws ig
you read that right
could you put this in
!paste
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
yea complex
red flag
hmm
YT is one of the shitties ways of learning this kind of library
mostly because this library changes quickly and tutorials get outdated
most tutorials on yt are incorrect anyways
use official documentation and learn that way
^this is also important
can you edit a interaction.response and include a file?
TypeError: InteractionResponse.edit_message() got an unexpected keyword argument 'file'
yes, the kwarg is attachments=...
just edit
edit_message is the internal command function 😉
why did u del my msg
I didn't...
who did it lmao
the bot most likely
hmm
like attachments=discord.File()?
hello, how to make bot (AutoShardedBot) react to message (to be exact using custom emojis)
try and see ( it needs a list though, so just put 1 element in there)
add_reaction is a method you can call on a message...
can i send a modal with ctx?
how?
not sure, I haven't worked with v2 stuff
check the docs
hm
is it the same way for the embedded one?
embedded one? what're you talking about?
adding a reaction to something can be on any message
oh ok
oh wait does it need to be a link
or can it be a directory
code:
await interaction.response.edit_message(content=f"{self.name}'s {mode} session:", attachments=[f'{os.getcwd()}/assets/{mode}_{self.session}.png'])```
error:
```python
AttributeError: 'str' object has no attribute 'to_dict'```
if you can prove to me you've read the docs (by linking it to me ). I'll help you
spoiler: ||a string to a file in your directory will not work, you need to pass a file OBJECT||
no, the edit_message method
Welcome to coding, just a heads up, making a bot with Discord.py is very intense as your first project. you might be better off starting on smaller projects to learn with then come back to the bot making.
if you're being honest, you just typed "attachment" in the discord py search in documentation & clicked the first link...
whats a variable
yes thats what i looked at before
Like I said, smaller project first.
Can you humor me real quick? What's a String?
that's the incorrect link though, as suggested earlier, understanding the basics is key on progressing
women underwear
That was cringe.
technically correct
In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).
thank you, google
Thank you Luca.
I Am GOOOOOOOOGLE
BTW who is Luca?
The person I was asking......
luca||'t my balls||?
Well im not Luca
HAHHAHHAHAHAHAHAH* He says sarcasticallly
Damn, I would have never guessed......
if i were u, me neither
Need anything?
Just some braincells
Actually, u being my friend
Pass
NOooo, I will now eternally live under a rock thinking about how u rejected me as a friend, How could u do that to me!?
Easy, any level of self respect.
alright, i admit, that was a good roast
lol, glad you took it with good humor.
So you wanna be my friend now?
Why would you put yourself though that?
what, are u a bad friend?
through*
You there bro?
Sup
my blood pressure, how about you?
Me good :))
Awesome, anything we can help you with?
Zippy, cool name 🙂
Nah
I am actually here to help ppl 🗿
But there is no one 🤧
It's still early/late for most people.
okay then, why isnt this removing the select box:
async def on_timeout(self):
self.clear_items()```
!d discord.ui.View.clear_items
clear_items()```
Removes all items from the view.
This function returns the class instance to allow for fluent-style chaining.
Calling self. does nothing, you need to have a message object.
if pass in the message object, the on_timeout function doesnt get called
Show code.
I get it, just a troll.
Your "Python is not a real language." bait is telling me otherwise.
its for the funny
Funny is for people that know you, I don't know you.
but I find it funny
Cool, and it makes you look like a troll to me.
define 'troll'
This
like the thing under the bridge or...
Yup, I was right.......
Did you get an error?
Message can't be empty.
Not correctly it seems.
Check the code herehttps://paste.pythondiscord.com/nanukebaxu
Sorry it was my mistake maybe
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
How I can make a line break for each embed.add_field(name=field_name, value=field_value, inline=False)? Each infraction is listed in field_name and field_value, same embed. I want to add a line break for each one of them. https://paste.pythondiscord.com/zokuputubu
@slate swan https://paste.pythondiscord.com/edowecifiw try this
Are you sure that's the entire traceback?
Where does one host a discord bot 24/7 for the sake of development (free) besides replit?
Your computer.
. Gitlab
@slate swan whats the ping? There
@slate swan what is your bot ping in discloud
Which one? My phone or my nonexistent laptop/desktop? 🥲
U can use glitch if u arent coding in dpy
How doyou code on phone 💀
I code on my phone
pro 🛐
I also code on mobile and got my bot verified
There's a python ide app for Android called pydriod
bro
I meant that it's kinda hard to code on phone

ok and
your code?
Do I need to sign up with credentials?
Ya, kinda useless without the full traceback telling us where it went wrong.
Right. Perfect since my credentials expired
Replit keeps installing dependencies everytime I run my code. So annoying.
Attempting a timeout command for my bot, and I know I've definitely got some things wrong. Can anyone help out please?
@bot.tree.command(name='timeout', description='Times out a member')
@discord.app_commands.checks.has_permissions(moderate_members=True)
async def timeout(interaction: discord.Interaction, member: discord.Member, time: int=None, reason: str=None):
if reason == None:
reason = "No reason provided"
guild = interaction.guild
await member.send(f"You have been timed out in: ***{guild.name} for {time}*** | {reason}")
await member.timeout(time, reason=reason)
embed = discord.Embed(title=(f'***{member} has been timed out for {time}*** | {reason}'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)```
Error: ``discord.app_commands.errors.CommandInvokeError: Command 'timeout' raised an exception: TypeError: expected None, datetime.datetime, or datetime.timedelta not int``
Whos code is this? Who did you copy it from?
await send_message(message, user_message, is_private=True)
the errors says it as much
are you trying to get the number of seconds?
average
I want to be able to input smth like 5s for 5 second or 24h for 24 hours but idk how to do convertors or apply them in discord.py itmeouts
ofc?
they copied it from youtube
ofc stand for of fucking course right?
OFC was the channel then?
Either way, your code is a mix of stuff from now and from years ago.
1. Follow the Python Discord Code of Conduct.
???

ok?
Isn't ofc just shortened version of "of course"
What's that got to do with anything?
A better way would be to just have different arguments for them
I'm relativel ynew to coding so how would I go about doing that?
But back to the real topic, your code ain't going to work because it's a mix of versions.
def command_(self, interaction, days, hours, minutes...)
like that, easy stuff
await send_message(message, user_message, is_private=True) has not been used in like, 3 years?
There was a converter library the way you're wanting to do but I forgot the library name 
got it -> https://pypi.org/project/HumanTime/
And it no longer works that way.
Kinda.
Welcome to coding.
If you do it right.
Hello, Im currently new to python and asking how are indentations work? i have been having problems
My bad, I'll be sure to not say anything from now on then.
good luck 
!Indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
what just happened
I do think I provided the solution in the very beginning
but ok
idc
He is just thanking you dude
assuming genders in 2023
Knew u were gonna say that
Indents are how python tracks flow logic
four spaces show that the code under something is meant to run when something is done, such as a successful test or a function call.
I've fix that but now i've encountered this, upto 4 spaces its still the same but different error its exepected expression or unexepected unident
!Indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
ok
Another attempt at a timeout slash command, now I get the error discord.app_commands.errors.CommandInvokeError: Command 'timeout' raised an exception: TypeError: unsupported type for timedelta minutes component: NoneType. Any ideas on how to fix/optimize this?
@bot.tree.command(name='timeout', description='Times out a member')
@discord.app_commands.checks.has_permissions(moderate_members=True)
async def timeout(interaction: discord.Interaction, member: discord.Member, reason: str=None, days: int=None, hours: int=None, minutes: int=None, seconds: int=None):
if member.id == interaction.user.id:
await interaction.response.send_message("You can't timeout yourself!")
return
if member.guild_permissions.moderate_members:
await interaction.response.send_message("You can't do this, this person is a moderator!")
return
duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
if duration >= timedelta(days = 28): #added to check if time exceeds 28 days
await interaction.response.send_message("I can't mute someone for more than 28 days!", ephemeral = True) #responds, but only the author can see the response
return
if reason == None:
await member.timeout_for(duration)
await interaction.response.send_message(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{interaction.user.id}>.")
else:
await member.timeout_for(duration, reason = reason)
await interaction.response.send_message(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{interaction.user.id}> for '{reason}'.")```
for first look
duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
if duration >= timedelta(days = 28): #added to check if time exceeds 28 days
await interaction.response.send_message("I can't mute someone for more than 28 days!", ephemeral = True) #responds, but only the author can see the response
else:
reason = reason if reason != None else None
await member.timeout_for(duration, reason = reason)
await interaction.response.send_message(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{interaction.user.id}> for '{reason}'.")
Where are you defining minutes at?
I see
you can make the time in total seconds
You are defaulting it to none and not passing anything through for it when you call the function.
So how would I go about fixing the code? (I'm new to discord.py so smoothbrain)
This ain't a discord.py thing, it's basic python function call.
Fixed it all but why am i getting this? This code was just working earlier?
Sorry should have also specified, my discord bot is my first project in coding ever, so I'm learning everything as I go with no prior experience aha
You are calling for a variable before telling the computer what that variable is.
Ya, you and 90% of the people that come though here. Everyone wants to fly before then can even crawl ¯_(ツ)_/¯
Yeah makes sense
So when you call timeout, what more do you say when calling the command?
So you want me to call
mines = int(mines)
spots = int(spots)```
after the assignment?
You kinda have to, that's how coding in python works.
then im getting this :/
im so used to on js lol
Welcome to compiled vs interpreted.
Why the list?
not the spots = int(spots)
cuz without that not_good wouldnt work.
I mean, what is the list for, what are you doing with it?
its for a game
Because you still need to define what spots is.
your list is calling for spots, not defining it.
its already defined it was working fine earlier, after i put this mines int etc wouldnt work anymore
Your traceback is flat out saying that spots is not defined.
It's not me saying that, it's your computer.
Now it works i put mines int etc at top ey
Also, you don't need to define data types in python like you do in other languages.
Int = 89734598734
String = "34905835"
L
You going to survive?
Hi!
What's the best way to carry out scheduled events in a discord bot?
For example, every day at 12 am the bot should be posting a message in a channel...
I know a while loop can be run and compared with the current datetime and the scheduled datetime, but is this an efficient method to do it? Any suggestions?
Hm yeah, but can those be scheduled at a specific time?
!d discord.ext.tasks.Loop.time
property time```
Read-only list for the exact times this loop runs at. `None` if relative times were passed instead.
New in version 2.0.
yes
Oh
Whot
You just had a big L, you going to be ok?
!d datetime.timedelta @white perch
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
Oh i just realized that tasks have a time parameter
No worry Mike.
Was the before or after I send the docs lol.
How to handle this in case our bot is customizable?
Like any server can set any time for sending the message
after
Work with databases yet?
!d discord.ext.tasks.Loop.change_interval
change_interval(*, seconds=0, minutes=0, hours=0, time=...)```
Changes the interval for the sleep time.
New in version 1.2.
You'd need to create a new class with a loop inside that is customizable.
Oh um
I'll try coding that, will ask if i don't manage to logically get the code right
Lmao its so big that it touches the ceiling now.

See ya later then Mike.
This one
what? 
Which one
I just randomly typed it that time btw what did you mean
How can i have the same @commands.group() in 2 cogs. Can someone help? @crimson mauve im back xD

why two cogs 
You can use the start multiple times on a loop. It just differs on how you want to customize their data. The hardest part also would be to let's say; what if the bot restarts? Etc..
No idea, I never use groups.
based
Yeah thats the thing
Idk how Dyno handles this
Have all commands of one group in one cog, that's the best practice too
Dyno & carl bot, etc they somehow do it customizably for each server
It's a decorator so.. yes? Not too sure what you are doing here.
By saving data in a database most likely.
Yes saving into database part is not difficult
Ash is right, if it's all for the same stuff the best idea is to put all that into the same cog.
im here bc im getting the error The command ... is already an existing command or alias.
How to evaluate the event logically at the time without using a while loop is difficult according to me
its not for the same stuff, they just have the same group name
A while loop would take too much cpu resource
How new are you to coding?
Well what do you have trouble understanding then? If you use a database you're basically half way there.
I started python in December 2019
Wdym by while loop? You're using tasks.
Um yeah tasks i meant but still I think it's going to be little difficult to get the code right logically
How so?
If it's only for one server then it's easy to get it coded
Anyway i will try to code it now- let's see if it goes well
Why is it easier for one server? If you use a database any server can execute it.
Finished my server lockdown command which correctly locks every channel and sends the embed, however idk why it still says "Bot is thinking..." even though the command is complete. Any thoughts? (no error messages in VSC)
@bot.tree.command(name='lockdown', description='Puts server into lockdown')
@discord.app_commands.checks.has_permissions(manage_channels=True)
async def lockdown(interaction: discord.Interaction):
embed = discord.Embed(title=(f'The server is now on lockdown'), color=0xf6ff00)
await interaction.response.defer()
for channel in interaction.guild.channels:
await channel.set_permissions(interaction.guild.default_role, send_messages=False)
await interaction.channel.send(embed=embed)```
Use follow-up.
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
Works now, I must have copied the interaction.channel.send from the wrong bit of my code, thx for the help
just edit the original response lol
do y'all go to the gym
Popcorn.gif
lol
it's funny to be jacked as a programmer
Cool story bro.
do you know where I am rn
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
!topic
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
The channel names change every night at midnight UTC and are often fun meta references to jokes or conversations that happened on the server.
See our off-topic etiquette page for more guidance on how the channels should be used.
what
In the wrong server? lol
oh .topic
Suggest more topics here!
You ok? having a bad day? need to talk to someone?
still voice receiving
beautiful day!
Then what's wrong?
if this is all you have to say, I would prefer the silence.
did you know discord.py still doesn't have voice receiving
but I do
Such as?
At that point why do you need Discord?
no relation whatsoever
I wonder if voice reception events get triggered by on socket raw receive
I mean, Speech to text is fun and all but unless you have to time/recourses to toss at it you are just going to be upset with the results.
Even Google and Amazon still suck at it.
do discord.py perfect voice receiving and get a job at google
No, I would be leasing my tech, not giving it away.
also smart
But ya, you need any help?
just to be clear this was a sentence starter and the followup would've been that I might as well try implementing it but didn't finish it
How can I get this code work?
@modlogs.error
async def modlogs_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send(f"I could not find the user {error.member_str}")```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'MemberNotFound' object has no attribute 'member_str
It's error.argument
Oh that makes sense, thanks
can embeds be stored in database directly as discord.Embed object and later re loaded directly?
I try not to ask this.
But why?
Customizable Embeds feature
But why would you store them and not make them as you need them?
- embed elements input by user
- embed stored in database with some user inputted
name - user does
$load_embed {name} - bot sends their embed
That's what im upto
Ok, I get you now.
Depends on the DB, but generally they don't work well with custom objects like that. You would have to break it up into parts.
mongo allows storage of dict structures convert the embed to dictionary and store it
Just to be sure that i'm not wasting my time writing all that code manually
The more you fail, the more you learn.
Rightly said
!d discord.Embed or you look at the api reference to get your answer
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
aight
Find it?
found it man
Awesome
Any time Mike.
So does sql by saving it as a string
Then eval it lol
u know a free sql host?
sqlite 
Random old laptop in a drawer
u can afford to host a bot but not sql?
Tru
heh
Just host a vps with a postgresql
Or a docker container
I'm looking forward to the first person that gets their hands on alien tech also gets it to run doom as a proof of concept.
am i doing smth wrong? the appeared one works fine the congratulations doesn't
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
Whats wrong?
Btw python v4.12 mans from the future
If one then not the other.
When that first if statement goes though, the elif is ignored and not even checked.
the bot version 😭
should i change to if?
Wait, I'm just being dumb and only seeing what I'm thinking about
what's the sol
You are going to want to look into __contains__
https://www.askpython.com/python/string/python-string-contains
marvelously fixed it
Hey @onyx rapids!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
So I just started with my bot, host is setup but my bot is not responding. Anyone able to help? https://paste.pythondiscord.com/yeporazifi
on_message
wait, where do I put that then?
where it shows you.
Figure it out?
didnt work
Ah crap, what did I say this time?
still doesnt work
@client.event
async def on_message(message):```
Can't have 2 functions with the same name.
I'm only one person.
So what? lol, dude I'm spending my time here helping people for nothing but my time.
you aren't doing an amazing job at it to be honest
If you're gonna help people then help people
And? you think programming is my job, I went to school for this?
This is what I do for fun, and people like you make it not fun.
tfym atleast he comes here everyday helping at as best as he can 😭
Have you ever considered that "figure it out" isn't helpful? If you do this for fun then you should realise that might be why others are here xD
then step the fuck up and HELP.
flippin ChatGPT is better help than that
+1
Could you guys take this to #ot2-never-nester’s-nightmare?
i came in here to ask a question then figured the answer out myself
I'd rather just ignore it all and act like it never happend.
That one there was a violation 💀
That's ok too, It's a public server, try to keep it cool here.
You want to take over for a bit panda? I think I'm going to work on my own stuff for a bit now.
I just keep this channel on my second screen and coding a long the side :3
Keeps my mind busy and doing something else on ever now and then to avoid doing the same for 10 hours straight.
But as for your question, you put the listeners at the end, take out the event you are already using.
So which one do I have to remove?
is there a point using a vps for a private bot in a 20 member server
no. if its for commercial use aimed to get bigger then yes
no it's just for this one server
then no use host on repl or local machine
If we're still talking about https://paste.pythondiscord.com/ositaqarix.py; then you need to also apply listener to the event below. However since you are using discord.Client you don't have listeners. As Zippy pointed out as well you can't have 2 functions with the same name in the same file.