#discord-bots
1 messages ยท Page 172 of 1
i mean yes a db would be a very big good thing to do, also changing it from having author in footer and description, you can clean it up by removing the bot name from the top, seeing as the bot sends the message
i don't even have the bot made yet
good
oh lmfao i thought that was yours
how do I add a description to an argument of a slash command?
that's just a reference
which library...?
yeah i got ya
disnake
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
that's for dpy
what about disnake?
๐คท
forgot
how can i get the value of total iv using regex?
discord.gg/disnake if you don't get help here though
@whatever.#6421slash_command(description=xxx)``` ?
my b g
He said argument
for an argument
man its early for me
yeah that's from a private user unwilling to share reference code, i was originally just going to fix the issues for him, but cause yk, i'm jus going to make an alternative
For loop or regex 
ill be functioning soon ๐ฎโ๐จ
you checked docs?
ah, docstrings i guess
https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#docstrings
its much simpler ```py
async def command(inter, argument: str)-> None:
"""
Command Description
Parameters
----------
argument: talk about using decorators lmfao
mhm nice nice
you could use add_option too ๐
discord.py can use(s) the same for the record
for loop?
let's not talk about that
don't like that style , they could have either made the complete argument using decorator ( like lightbulb does ) or complete argument based options ( function signature )
let's see, now that I'm starting to use slash_commands, I'll finally have more knowledge about them
i mean it doesnt look that complex
wouldnt be a hard recreate, maybe just a bit tedious
lmao
@naive briar can you elaborate on how can i use for loop? 
it's not but it is, ian really used db's that much, and i haven't programmed anything in 4+ months.
for element in elements:
...
you just need an iterable ๐
MY CODE
c.execute(f"INSERT INTO auctions (name, offer, seller, channel) VALUES ({data[0].value}, {data[2].value}, {interaction.user.id}, {channel.id})")
THE ERROR
Ignoring exception in modal <__main__.AuctionModal object at 0x000001FE0F4EEDD0>:
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "c:\workspace\python\Bots\marketplace\main.py", line 69, in callback
c.execute(f"INSERT INTO auctions (name, offer, seller, channel) VALUES ({data[0].value}, {data[2].value}, {interaction.user.id}, {channel.id})")
sqlite3.OperationalError: no such column: aaa
i have a modal where i can type something
in this example i typed in "aaa"
which doesnt exist
no i meant how can i use that to get totla iv?
and now where i try to insert it into a database it says that the column doesnt exist?
"aaa" is just the value i want to insert into the table
how can it "not exist"?
Read the error will tell you
Don't use f-string in SQLite queries
oh okay
Use placeholder, or something I forgot
should i use ?
!sql-fstrings yes
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
โข Python sqlite3 docs - How to use placeholders to bind values in SQL queries
โข PEP-249 - A specification of how database libraries in Python should work
?, ?, ?, ?
thank you ๐
and you too
if they are the only columns in the table you dont even need to mention them at all
btw, is that pfp from adventure time? ๐
yes true i just did that because i thought that caused the error
Is there a way to run code when the bots is shutting down?
I want to edit the name of a voice channel when the bot stops running
async for ban in guild.bans():
banList = ""
for ban in banList:
if ban[1] == member:
title = f"Member Banned"
desc = f"{member} has been banned from the server for {ban.reason}"```
still something wrong :3
banList is empty?
nah
Depends on how you shut it down.
just anyway
if ban[1] == member:
ban is a discord.Member object you can't index it
im trying to make a status channel and it needs to change to off if the bot isnt online
Well not really then, since using the "X" on the console or killing it will result in a unproper closure.
i am trying to get the member that just got banned to send that msg
can you run 2 clients in one code?
why would you do that
!d discord.on_member_ban
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
Yes.
k ty
U probably could override Bot.close. Make sure to call await super().close()
It's an embed..? If you have some text I could write it up for you.
Issue is that most of the time that event doesn't get reached.
well wont this and on_member_leave send double msg for that event?
That's why I suggest to use only this.
at the end of he code i have
discord.run('token') (discord client)
client.run() (second client)
Oh it doesnโt? I thought it was in a try finally block
.run is blocking
then what about the event when the member leaves and not banned?
it let me start only 1 client
You could use .start with asyncio.gather
i am tryng to to use on_member_leave to send a msg when the user gets banned and in the same event when the member leave it sends a seperate msg
Why are you trying to run 2 bot instances in the same time anyway
It will get blocked, you'd need sub proessing.
how
Gather would expect a value to return.
i cant code lol
.wait maybe?
Just use create_task.
I'm already to forget stuff about asyncio
can any one send me a little template

just use if member in ban_list: then.... nothing else is needed
yea its an embed ;-;
hi
me again
so i cant use f strings in sql statements. but what about {} and .format()
does that work?
I
Do not:
cursor.execute("SELECT * FROM table_name WHERE value = {}".format('peepeepoopoo'))
Do:
cursor.execute("SELECT * FROM table_name WHERE value = ?", ('peepeepoopoo',))
Consider: if a command accepts user input, and they input True; DROP TABLE table_name- The resultant query with format is:
SELECT * FROM table_name WHERE value = True; DROP TABLE table_name which has obvious results.
Utilizing your SQL library's sanitization methods prepares the statement and exclusively inserts the values, without editing the query.
Note asyncpg uses $1, $2, ... for value substitution, mysql-connector, %s, so make sure you know your DB library!
https://xkcd.com/327
neither
any kind of string interpolation should not be used
any help?
how can i keep track of how many times a command has been ran by each person?
Store to a database
from the embed? regex isnt always the solution
you can just do "the stats field value".split(":")[-1]
async def on_member_remove(self, member):
guild = str(member.guild.id)
name = member.name + "#" + member.discriminator
id = str(member.id)
try:
print("logid")
id = self.guildchannels[guild]["logs"]
except:
print("no id")
return
print("logchannel")
logChannel = self.bot.get_channel(id)
print(logChannel)
title = None
print(title)
banList = [ban async for ban in guild.bans(limit=2000)]
print(banList)
for ban in banList:
if member in banList:
title = f"Member Banned"
desc = f"{member} has been banned from the server for {ban.reason}"
else:
print("log left")
title = "Member Left"
desc = f"{member} has left the server"
print(" log embed formed")
embed = discord.Embed(title = title, description = desc, color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())
embed.set_thumbnail(url=member.display_avatar)
print("log author")
embed.set_author(icon_url=member.display_avatar, name=name)
print("log footer")
embed.set_footer(icon_url= member.guild.icon, text = f"{member.guild}")
print("log embed sent")
await logChannel.send(embed = embed)```
it prints till` 'print(title)'`
someone help losing my mind lol
print doesn't print None object
I have the problem that when i want to start the discord client it dosent work, it showes me this in the promt:
โข Fortnite Client ready as FlJILeaks
โข Discord Client ready as None
im working on a fortnite bot that u can controll through discord, but for this i need to run 2 clients and its only run 1
any ideas?
it prints None
!e
print(None)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
that
Nvm
What's the actual problem with this
something with banList is wrong
you should never need to run 2 clients in the same script
And what is it
that idk
i need,
- The Fortnite bot (in the game)
- Discord bot
i dont rly know what you mean
how did you start the discord client and what value are you actually printing?
!self
Class instance
When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.
class Foo:
def bar(self):
print('bar')
def spam(self, eggs):
print(eggs)
foo = Foo()
If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.
Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').
Why is this useful?
Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.
Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.
any idea?
told ealier, check recent pings
discord.run('1234') it starts the fortnite bot but not the discord one
discord.run is not a thing
start or what
if member in banList; did it
your client object has the run method and it's blocking, any code after it wont get executed
is there a way to fix it
and after that? i just sent the condition you need to do what you want to do in the condition ๐คจ
how can i make a program wait a certain amount of time before doing something?
its like client.run but i changed discord = discord.client()
im so bad lmao
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
what did you actually print?
wym
to get that result
banList = [ban async for ban in guild.bans(limit=2000)]# here is the ban list ///// the code still stucks here
print(banList)
for ban in banList:
if member in banList: # here cehck if the member is in the ban list
title = f"Member Banned"
desc = f"{member} has been banned from the server for {ban.reason}"
else: # here if the member isnt in the ban list
print("log left")
title = "Member Left"
desc = f"{member} has left the server"
print(" log embed formed")```
@slate swan
hey i have narrowed it down to
['**hp:**', '80', 'โ', 'iv:', '30/31\n**attack:**', '73', 'โ', 'iv:', '12/31\n**defense:**', '122', 'โ', 'iv:', '25/31\n**sp.', 'atk:**', '65', 'โ', 'iv:', '26/31\n**sp.', 'def:**', '31', 'โ', 'iv:', '5/31\n**speed:**', '51', 'โ', 'iv:', '10/31\n**total', 'iv:**', '58.06%']
now what shall i do to get the last percentage?
It's like the first thing you will encounter in asynchronous programming
print(Fore.LIGHTCYAN_EX + ' โข ' + Fore.RESET + 'Discord Client ready as ' + Fore.LIGHTCYAN_EX + f'{discord.user}') but it dosent start the dc bot
!e
ml = ['**hp:**', '80', 'โ', 'iv:', '30/31\n**attack:**', '73', 'โ', 'iv:', '12/31\n**defense:**', '122', 'โ', 'iv:', '25/31\n**sp.', 'atk:**', '65', 'โ', 'iv:', '26/31\n**sp.', 'def:**', '31', 'โ', 'iv:', '5/31\n**speed:**', '51', 'โ', 'iv:', '10/31\n**total', 'iv:**', '58.06%']
print(ml[-1])
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
58.06%
yo.tysm

If it's static then I guess
static?
what if like the hp attack values change?
ah , ty i'll try
.user won't be available until the bot is started and running, you can't print it immidiately
Eh, I was about if the embed formatting will stay the same
ik but thats not the problem
If they move the percentage position then it will break
it dosent run the discor bot
You should use regex, way neater
the percentage position stays the same the values change
is the fortnite bot another discord bot?
no
or some other app
Then you should be good
its a bot in a game
i am not familiar with it, any example?
alr
show code
I'll try tysm
import asyncio
from discord import Client, Intents
loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
class BaseClient(Client):
def __init__(self) -> None:
super().__init__(loop=loop, intents=Intents())
async def on_ready(self) -> None:
print(self.user.name)
async def close() -> None:
await super().close()
panda = BaseClient()
bird = BaseClient()
async def run_panda() -> None:
async with panda:
await panda.start(token)
async def run_bird() -> None:
async with bird:
await bird.start(token)
if __name__ == "__main__":
loop.create_task(run_panda())
loop.create_task(run_bird())
loop.run_forever()
it has over 1k lines
!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.
tysm
ill try
it works tysmmm
also when i am using this how do i et the reason the user was banned for?
It hasn't got task shutdown tough but it works and it's an idea.
TypeError: 'module' object is not callable
whats thati just started with py thats why im not good
discord = discord.client() TypeError: 'module' object is not callable
loop on the ban list, if ban's id is same as member's id, check the reason attribute of ban
Python attributes are case sensitive
!d discord.Client Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
can i do discord = discord.Client(intents=intents)
You are overriding discord module
means?
Change the var name to client or bot
kk
Or anything that's not overriding something important
bot = discord.Client(intents=intents) NameError: name 'intents' is not defined
im so sry when its to easy but im to dumb ๐ฆ
command_prefix=prefix, NameError: name 'prefix' is not defined lmao
How do I edit this command? This command doesn't exist in my current code.
its default help command, just make a help command and remove the default in the constructor
@rare echo How do I remove it from the constructor?
good morning/afternoon/evening,
I'm trying to create a global connection to my database so I can use it across different events. Right now, Google lead me to something like this:
db_con = None
@bot.event
async def on_ready():
if db_con is None:
db_con = await aiosqlite.connect("strava.db")
conn = await db_con.cursor()
But I keep that db_con is referenced before assignment. I assume this means that on_ready() is happening before anything else?
My other idea is just to open/close the connections in each command as needed, but that feels tedious.
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
this gets triggered only once, before the bot runs
!d help
help()``````py
help(request)```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
i have a code with a if else statement this if else statement gives me a percentage value now i wish to use this value outside of this if else statement
how can i do that?
how to label it as a global variable ;-;
if ...:
percentage = "69%"
else:
percentage = "6969%"
print(percentage)
learn about scopes
!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.
don't use global here though
the print is inside a different function tho
Hello, has anyone here ever worked with attachments for message.edit()?
Embed = discord.Embed(title=f"hello")
TempFile = discord.File(f"{FilePath}\\TEMP.png", filename="TEMP.png")
Embed.set_image(url=f"attachment://{FilePath}\\TEMP.png")
await message.edit(embed=Embed,attachments=TempFile)
I know it's not right because attachments expects an iterable. I'm just not sure how to make what it's expecting.
I'm reading through the documentation and I'm a little lost as to how to implement this. I'm googling to find examples, but coming up blank. Sorry to be a bother, but how exactly do I use this?
easiest way would be ```py
@bot.event
async def setup_hook():
do your thing
make it a list or a set or a tuple
[TempFile]
raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed
cmd promt shows me that error
I feel like a clown.
lol, thanks.
Ya, it works now.
any help?
nvm got it
loop policy, actual error is a bit higher.
That's what I figured and after some tinkering I think I've got something. I assume, since it's a function, that I should be returning my db connection variable to use, and then calling the setup_hook function first thing in on_ready?
I feel like these questions are silly, but this is a whole new world for me
you are trying to set up a task that runs every so X seconds?
you dont need to call it it will get triggered automatically
before your bot is online
No, I'm trying to have 1 global connection open to my database that different commands can access.
Before I was opening connections in each command and then manipulating the database that way. But I'd like to just have 1 open connection and then use that in different commands.
With sqlite3 I could define the connection globally and then use it to create cursors as needed. But with aiosqlite it doesn't work, so I'm trying to figure that out.
But if I don't call it, how do I access the connection? I know that the database is being created, because each time I run the code it makes the file, but then it crashes when it gets into on_ready and tries to use the connection variable to create the tables
oh snap, I think I figured it out and I feel silly
Sorry that I'm a little late joining in, but what DB are you running?
instead of making it some random variable I tried using the bot object.
Originally I was using sqlite3, but I was recommended to swap to aiosqlite to prevent blocking
Have you heard the words of our lord and savior sqlalchemy?
i dont think that really solves his issue just suggesting something else lol
Yeah, briefly. But isn't that just an ORM?
yup
It also solves your problems with just defining and calling an engine object.
would it prevent my blocking issue, though?
i create a function that i call in bot.loop.run_until_complete to create db connection by creating a pool. defined as self.db then called using bot.db
honestly, I have no idea. let me look into that setup_hook
So far, I think I've managed to get it to work by using bot.db_con instead of saving it into a random variable
wait are you having blocking issues using aiosqlite?
I pulled this from the discprd.py examples folder on github
import discord
import asyncio
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self) -> None:
# create the background task and run it in the background
self.bg_task = self.loop.create_task(self.my_background_task())
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def my_background_task(self):
await self.wait_until_ready()
counter = 0
channel = self.get_channel(1234567) # channel ID goes here
while not self.is_closed():
counter += 1
await channel.send(counter)
await asyncio.sleep(60) # task runs every 60 seconds
client = MyClient(intents=discord.Intents.default())
client.run('token')
It might not be exactly what you are asking for but it's the function in action.
No, sqlite3. Well, technically I wasn't having issues. But it was recommended that I swap over to aiosqlite while everything is still small and getting built. Better to have it set up properly before things get too big and annoying.
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

yeah what zippy sent probably would work for u
Anyone know why this command isnt working? @client.command() @commands.has_permissions(ban_members=True) async def ban(ctx, member: discord.Member, *, reason=None): await member.ban(reason=reason) await member.send(f"You were banned from the {ctx.guild.name} server for the following reason: {reason}") await ctx.send(f"{member.mention} was banned for reason: {reason}")
Getting an error?
no bot runs fine. The command was working as of December 13th but stopped working a couple weeks ago.
what about role hierarchy?
is your bot higher than them?
its at the top and has admin.
Did you change your command prefix?
no.
has anything changed within the bot or server?
nah
and you double checked everything?
yes
i havent changed the command at all
Are things wrapped in a try/except:pass?
i change the ! in client = commands.Bot(command_prefix='!', intents=discord.Intents.all())?
nah
Ya, that is how you call commands.
im using discord.py if you couldnt tell
do u have a error handler?
or catching errors at all
So you did change that?
even with prefix changed still doesnt work.
alr
Precisely.
Getting a no command error?
Took me a bit, but I think I've implemented all your suggestions. Much, much appreciated.
Is..... is the bot in that server?
Glad to hear ๐
i have a auto role that requires the bot to not send a message which works fine but the other commands dont work
ofc it is im not that dumb
do any of your cmds work?
nah jus auto role
oh
they was all working the other day
well there u go
something has clearly changed
I got paid $200 to drive 2 miles and plug in a printer before. You would be surprised.
when i had auto role it was working.
is that a cmd ?
no
it runs whenever a memebr joins
yea that working has nothing to do with ur cmds not being processed then
ohhhhhhh, on_message is eating your commands
!pastebin @slate swan can you pastebin your entire code please?
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.
yh hold on
Thank you
# Logs
@client.event
async def on_message(message):
print(f'{message.author} sent a message in {message.channel}: {message.content}')
yea this will solve ur issues. @slate swan
TL;DR use @client.listen() instead of event
alr
Don't worry, there ain't too many moon logic pitfalls in discord.py
that one has to be the worst.
thank you.
It's not their fault, it's actually the fault of youtube tutorials which show about the making of commands using on_message and not the commands extension
That's the most reason people end up using events instead of listeners
Reminds me of trying to learn it and not knowing there had been a top down re-write.
Pity on those who pick up discord.py as the first thing to learn with.
i somehow skipped dpy in my journey to discord bots lmao
I've never used dpy after that one time I discovered it's so bad ๐
I like it, it does what I want so far. Its support team on the other hand. I'll just keep my mouth shut.
yeaaa i started with nextcord and ended with disnake when they released slash commands
lmaooooooooo so true
worst staff in existence
I started with dpy, moved onto disnake, then hikari ๐
i tried helpig someone one time and the staff person told me to shut up, timed me out then procedded to give them exactly what i did
Ok, honestly glad to know I'm not just some bitter asshole.
Understandable, Even I got denied for helping and got temporarily banned ๐
My inner voice mostly?
๐ฟ r1 for helping in .gg/dpy
provide the shortest help statement ever with a rtfm command
nice
well i was ab to say i cant deal w hikari docs but i just looked and it seems they have changed them
lmaooo
hey ash, how i'm stumped on the deta still. am i getting close to making this work?
https://paste.pythondiscord.com/olosazohup
I haven't made a discord in a while so idk what's going on with libs
I don't even know the changes made to discord.py slash commands to keep the gist updated ๐
dw even discord.py docs dont know what's going on there
their docs are so bad.
^
lmao
the commands extension docs are foinu, but Interaction docs suck
yup
they barely exist
what issue are you facing?
wait, there are alternatives to discord.py? Ph man
there's many easier and advanced ones
no
that's my current error and client wont actually get retrieved.
Know what a POST Request is?
instead of deta.Client you have to do deta.Deta
would be cool if they named it deta.Base ๐
imagine using mongo
in a fundamental way, yes.
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
my tabs are never ending.
ok, that fixed one error... ty again...
project_key and base_name are the only things i see as far as credentials... but theres a token you can make in settings? I'm assuming i only need my project name(default) as the base_name and the project key is self explanatory. right?
you only need your project_key and your base name
you won't have to get into any other mess
also I just realized
You're putting your images inside a database
shouldn't you be using drive for that? or does it work with that too?
i was just going to do a test command w/ my alt acct to have a template to go off of.
i figured if this can append them, it should be able to insert them as well as a test
i'm now realizing that i've been doing the wrong function to insert them tho... ๐คฃ
i am learning to code and the first little project i want is to make a simple discord bot, but i can't find anywhere how to do that.
can somebody give me the code (only to let the bot go online)
if you are learning to code i wouldn't start with a discord bot or else you will be in for a long ride
Yeah, this damn bot has been a bigger challenge than I expected, honestly. But it's been fun
I can't personally recommend Discord bots as your very first project, but I do believe there is a quickstart example on the discord.py docs that can give an idea of how a bot might look in Python
client.run() bot.start() <- Discord
how can i run 2 clients at the same code
its one in fortnite (in game bot) and one discord
You run them as seperate files
no, both are in main.py
Separate them out then
and how can i run them? i run with .bat
python discord_bot.py
python fortnite_bot.py
yo is it possible that a discord bot takes control of a discord account and do a slash command from the discord account?
Self-botting is against Discord's terms of service and we won't help with that here
yes ik it's again tos i won't do it xd i just want to know if it's doable
in any case ill do it
I don't have the skills, the time and the desire
Bots can't invoke slash commands so even if you tried it'd be a no
ok
wtf
ph since 18hours
bro let ur dick to rest
๐
ty, but how can i combinate them, the bot i wanna make should be controlled trough discord, yk?
You want to control the fortnite bot via your discord bot?
right
What sort of IPC or other communication pipeline have you set up?
wym ๐ im not so good in py
It's going to be a bit complex if you want to bots to communicate with each other
So set up some sort of communication pipeline
i have one in js
Oh and the bots are written in different languages too?
Hey guys Iโm trying to code a bot that will send alerts to discord if stocks have a cross of Exponential Moving Averages. Iโm brand new to coding and have never done this before. Any help or where to start or what the code would look like would be helpful. Iโve already made the server and the bot. Just dont know what to code in python to make it actually scan and send alerts to discord.
Thanks!!
start with basic python control flow learn functional programming then oop the async programming and a bit of knowledge on apis and webscraping will help too
How's it going so far, figuring it out?
@naive briar how can i get only the top value? and ignore the rest? ur code the one u gave with regex works fine but gives all values
Iโm just researching how to even start the code so it scans markets. This is my first time coding and Iโm only doing it cause I couldnโt find any premade ones on the internet๐ so I figured Iโll just try it myself.
So Iโm just googling how to start any of it right now
Can i use one commands.group in two different cogs? If yes, then how? Because im getting the The command ... is already an existing command or alias. error.
Alright, so this is not what you want to hear. Making a Discord bot is not a starter project.
But, that never stopped alot of us, just expect to hit your head on the wall alot.
Can someone help ?
Using the same command in more than one cog?
not command but group
anyone have suggestions to get around this?
Invalid Form Body - In content: Must be 2000 or fewer in length.
@bot.group()
async def ...
Base64, you can compress it with encoding. but if you post just that it will be useless.
Could upload a .txt file
useless how?
Maybe i need to make the bot find the group from the other cog somehow ?
It just looks like a jumble of text
ohh
What information are you displaying?
i'm trying to make a list of information like the roles / channels / categories i have. and i had each neatly organized w/ a \n for each line.
I'll be honest, I never even use group so I'm not going to be much help here.
More than one post
Do you know how to do it with a command? Maybe it will be the same
how can i have it automate the responses to divide each 2k cap line into a new message w/o possibly getting the bot or me limited by discord itself?
You just trying to make a normal command?
Yes?
.len() will tell you how long something is.
What data type are you working with? Just a long string or?
@commands.command(aliases=["OtherCommandNames"])
async def CommandName(self, ctx):
yeah its a string setup like this role_list = "\n".join([f"[{role.name}]({role.id})" for role in guild.roles])
await ctx.channel.send(f" ||\n md\n[Guild](Roles:)\n\n{role_list}\n- - - - - - - - - - - - - - - -\n \n||")
the md is just to put it in fancy colors. to help me read
Have you worked with dictionary's yet?
not really...
i found another solution. But still thank you for spending time on helping me ;D
c# yes. python, no.
can I see your code?
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.
you need self.
Ok thanks lmao
Any time
still looking though it
ur fine

File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 272, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\bot_info\cog.py", line 187, in stats
await self.universal_log_embed_slash(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\bot_info\cog.py", line 50, in universal_log_embed_slash
log_channel = await self.get_log_channel(interaction.guild.id)
TypeError: BotInfo.get_log_channel() takes 1 positional argument but 2 were given```
async def get_log_channel(guild_id):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT guild_id FROM setup WHERE guild_id = ?', (guild_id,))
guild_exists = await cursor.fetchone()
if guild_exists is None:
raise check_error__logchannel_not_found
else:
await cursor.execute("SELECT log_channel FROM setup WHERE guild_id = ?", (guild_id,))
log = await cursor.fetchone()
return log[0]```
async def universal_log_embed_slash(self, interaction, **kwargs):
command_mention = nextcord.utils.get(interaction.client.get_all_application_commands(), name=interaction.application_command.name)
embed = nextcord.Embed(description=f"{interaction.user} used a command", colour=config.blurple, timestamp=nextcord.utils.utcnow())
log_channel = await self.get_log_channel(interaction.guild.id)```
self.get_log_channel()
u did something like self.get_log_channels?
ah yes in get_log_channel do (self, guid_id)
i didn't wanna use the discord interface to grab everything one by one. so i just wanted to make it easier with this, plus i can mess around w/ the setup of the "streaming presence" next after I organize my discord id's and stuff.
i'm guessing it would be role_list = "\n".join.len([f"[{role.name}]({role.id})" for role in guild.roles]) for the specific one in question.
Without interaction.guild.id?
Because he needs it or not?
async def get_log_channel(self, guilf_id):
So you are trying to map out a server? Make a list of all the channels, roles, users in the server?
definitely gonna error out
Yeah, just to test the waters thats where i was starting
I'm just assuming it's in a class because of the indentions.
remove the .len
cool, I'll help you make that and walk you though it.
ty! take ur time tho, i'm in no hurry ๐
I'm going to take
channel_id = ()
member_list = {}
role_list = {}
category_list = {}
channel_list = {}
member_list_data = {}
role_list_data = {}
category_list_data = {}
channel_list_data = {}
``` and see what I can do about compressing it into one dict.
i was thinking that or make something like this
#discord-bots message
and just have pages for ea, idk. just spitballing
the formatting shouldn't be too hard.
the_info={}
[Guild][Users]
[Roles]
[Categorys][Channels]
So, I know the schema can look confusing.
that's good. The only thing that I can't stand is having them side by side and 1 color, my dyslexia can't handle that. which is why i did the md color coding.
just a little 
use ansi
discord supports ansi encoding
about like 7-8 colors and a few backgrounds iirc total like 16
i'd have to convert it into async functions right?
okie dokie, ty for the help ๐
not really its just a string
Code: await interaction.response.send_message("Anonymous message sent.", ephemeral = True, delete_after = 2)
Error: InteractionResponse.send_message() got an unexpected keyword argument 'delete_after'
Reference: https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message
I have Discordpy 2.1.0a
Is delete_after not working on send_message()?
why does: "python3 -m pip install -U discord.py[voice]" not work?
why are u using delete_after and ephemeral?
What error do you get?
zsh: command not found: python3 -m pip install -U discord.py[voice]
dosent make sense its prone to error
Cause I want it to show for 1 user and delete it after a moment.
I will try this right now:
await interaction.response.send_message("Anonymous message sent.", ephemeral = True, View = View(timeout = 2))
do u have python installed?
yes
Try python -m pip install -U discord.py[voice]
zsh: no matches found: discord.py[voice]
python -m pip install -U "discord.py[voice]"
yes that works ty
np
its not worth it its better to let the user dismiss it u are just wasting api requests one for sending one for deleting and meantime if someone dismisses it will raise NotFoundError
ohhh i see now. ty
My code doesn't delete it. Letting the user dismiss it will just make the command annoying because they will use it multiple times.
cool
also I had a question.
so nightbot, for twitch integration has this in their docs...
Nightbot does not sync subscribers. Discord has a built-in subscription integration with Twitch and YouTube, so the role selection for Subscribers is only used to identify existing subscribers in the server.
So if this is built-in as their docs say, how can I get that information?
i am not fully sure u can delete an ephemeral response from the discord api
Mhm, in this case I will just leave an ephemeral. Is there anyway to close the slash command without sending a message or anything like that? I see defer() only makes the bot wait for an answer and doesn't really close the slash command.
probably from the ui discord api dosent have any such endpoints as far as i am aware
not really u need to send a response
I see
https://discord.com/developers/docs/change-log#delete-ephemeral-messages you indeed can and it works just like a normal message
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
delete_after was added in 2.1 so you are out of date
I have 2.1.0a
2.1 is full release so alpha version probably doesnt have it
does your linter show the delete_after kwarg? try to hover your mouse over the method to see the pop up documentation
You're right, the alpha version didn't have it. I upgraded Python and it's working now.
Didn't check but now it's working
how to fix it?
looks like I have to run before I can do all of it
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = discord.Client(intents=intents)
class DataGrab(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.TheData = {}
self.Page = 0
self.DataPost = {}
@commands.is_owner()
@commands.command()
async def PartyLikeTheCIA(self, ctx):
# this Guild object holds all the info you want, now we just need to sift though it.
self.TheData = ctx.guild
Embed = discord.Embed(title=self.TheData.name,
description=f"This Server has \n {len(self.TheData.members)} Users \n {len(self.TheData.roles)} Roles\n and {len(self.TheData.channels)} channels in {len(self.TheData.categories)} categories"
)
DataMessage = await ctx.send(embed=Embed)
self.DataPost[DataMessage] = {"User": ctx.author}
async def setup(bot):
await bot.add_cog(DataGrab(bot))
it's ok! thank you so much for the help
Hello I have created a test website for my bot configuration,I want to ask what is the best way to make everything work correctly, for example: I have a button on my website [Setup Category], how exactly do I make the bot create a category in a guild, it should again run the bot 2nd time (ie two token connection's)?.
but what I was going to do is make it so that you can walk though page by page, using reactions to turn the page. Each page would only have X amount
Before I go.
Discord.py right?
My main bot is on discord.py
I'm looking how I will connect it with the website
What is the site made with?
Can i dm you?
The more eyes that see it the more that can help you.
Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced with python and want to learn how to make websites flask is the right to...
You don't need to overcomplicate it that much
Just send a POST request to the appropriate endpoint
It's maybe 5 lines of JS
Yea but need to run my bot 2 times? One for the main bot and one for the site requests?
You can send the request directly from the site via fetch API
No need for anything extra
There is any example? Video?
Not that I know of
They all overcomplicate things by bringing in IPC or discord-oauth
But it shouldn't be very difficult
Crosspost Message
POST/channels/{channel.id}/messages/{message.id}/crosspost
Something like that?
Post your code and we can help you connect B to C.
Which endpoint is this?
Looks like I got up for nothing, figuring anything out?
There is no reason to post code
As I Said I'm trying to understand how works
I found this here
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Right. The only URL parameter is the channel ID
everything else goes in the request body
That's make sense
It all comes down to your back-end, if you are doing things in flask its as easy as importing the right thing. if you are using other stuff you might need to mess around with webhooks.
Requests are using discord account authorization?
You need to provide your bot's token yeah
In the form of
{
"Authorization": "Bot YOUR.BOT.TOKEN.HERE"
}
Ok
FYI this needs to be in the HEADERS
The actual message content and whatnot goes in DATA
๐
What's going on with line 420 then?
send the full traceback please
doesn't look like it?
the actual error is missing
it does...?
lol
your issue occurred in on_interaction apparently, not on_check
but I guess we won't know unless we get the entire log.
not really ;.; i've been trying to understand the structure for this. also, is_owner won't work. the bot is on an alt account and in my server ๐
so i edited that portion
anyone know why i keep getting this error? Traceback (most recent call last): File "c:\Users\jonah\Downloads\test.py", line 4, in <module> from discord_components import Button, Select, SelectOption, ComponentsBot, interaction ModuleNotFoundError: No module named 'discord_components'
I'm pretty sure this package was deperecated and removed off the pypi index
alr
What part are you stuck on?
any suggestions for making ticket system in discord.py?
Dictionaries are your friend.
elaborate.
They are more than likely where you will be storing/accessing your data about the ticket.
๐
Hiya! I'm trying to create a command that adds a role to a member but:
- Currently executing the command gives the error
discord.app_commands.errors.CommandInvokeError: Command 'role' raised an exception: TypeError: object Role can't be used in 'await' expression - How can I implement code so it checks if a user has that role and it removes it instead?
Here's the code:
@bot.tree.command(name='role', description='Adds a role to a member')
@has_permissions(manage_roles=True)
async def role(interaction: discord.Interaction, member: discord.Member, role: discord.Role):
await discord.utils.get(member.guild.roles)
await member.add_roles(member, role=role)```
utils.get is not a asynchronous function
So what do I change it to?
You don't need that 4th line
well when the function returns its trying to do await Role
You already have the role (from the function definition)
As it's part of the slash command
All you need is await member.add_roles(role)
To check:
if role in member.roles:
# user already has that role...
Aight, add/remove role works great now, thanks guys!
One more quick question: can you tag roles in embeds? Or would I have to keep it as plaintext in the embed?
slowly figuring it out. first pagimation i've done. ๐
i do have a question for embeds. how would i repeat this layout for another project i'll end up doing
looks like an author, description, image, and a broken thumbnail
mentions will render correctly in the description and field values but they wont ping the respective users - for that it has to be part of the regular content
What about in the embed title?
Aight thx for your help <3
quick question:
Is it good practice to save datetime values in an aiosqlite database as text? Searching through Google told me that aiosqlite doesn't have a datetime or timestamp data type, so I'm thinking I'll just save it as text?
this is a better question for #databases, but the sqlite3 module supports converters/adapters for custom types (and it seems aiosqlite provides the same functions) so you can just write your own to handle automatically parsing DATETIME/TIMESTAMP columns for you
https://docs.python.org/3.12/library/sqlite3.html#how-to-adapt-custom-python-types-to-sqlite-values
I figured I'd ask here because I'm specifically trying to use aiosqlite to prevent any blocking in the bot. But I can pop over there too
sure, i can elaborate further in that channel
Creating a purge command, it works, but it doesn't send the response (like it says !Application did not repsond)
@bot.tree.command(name='purge', description='Deletes a specified number of messages from a channel')
@has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
await interaction.channel.purge(limit=limit)
embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
does it give you a 404 Not Found error in your terminal?
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
that means you've exceeded the 3 second time limit for responding to the interaction
you can defer() it before doing the purge, and then use the .followup webhook to respond afterwards
What number did you pass in for purge?
Liek how many messages did I purge? I tested 5
that seems unusually slow
Hm. That shouldn't be taking more than 3 seconds
If I purge 2 or more messages, the application doesn't respond
hey wait a minute im noticing the same delay too
Can you also not purge 2 or more messages?
At first I thought maybe purging messages is a discord.py abstraction over multiple calls to message.delete
But then I found this
https://discord.com/developers/docs/resources/channel#bulk-delete-messages
Since this is just one request there should be no reason for ratelimits
purging multiple messages is fine, but perhaps ill try measuring the delete_messages() method
my bot is giving a error message about this after it work fine all day with out this
the error would suggest you've passed None as the colour= argument
yes i have and it wasnt a problem until now
yeah it seems to be slow
right but how do u get those dimensions? do i need to use css grid parameters to configure the sizes or is there like style presets or something?
and what do i about the error
you cant control the precise organization of it, each field is rendered in a specific format defined by the user's application
you fix it? i cant say much more without a full traceback and the code that caused it
user aka not the bot developer?
yea, entirely client-side
gotcha
i dont know how to fix it LMAO
oh you literally just wrote color= None
yeah
remove it and it'll be fixed
the whole thing
So is there anything I can do to remove the delay?
nah you can only blame discord for it
like none or the whol color = none
just the color=None
but in the mean time you can do the interaction deferring to give the bot more time to respond
i.e. ```py
await interaction.response.defer()
do whatever long task here (webhook takes 15 minutes to expire)
await interaction.followup.send(...)```
You make them with discord.embed
https://discordpy.readthedocs.io/en/latest/api.html?highlight=embed#discord.Embed
The thing on the bottom is set_image, to the upper right is set_thumbnail, the bold on the top is the title and the rest is the description
Embed = discord.Embed(title=f"{User} has left the server...",
description="Bye dude")
Embed.set_image(url="www.weeb.png")
Embed.set_thumbnail(url="www.brokenlink.png")
await .send(embed=Embed)
Hey whenever I or anyone else sends a message in my discord i get this message in the terminal. Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 409, in _run_event await coro(*args, **kwargs) File "/root/bot/akro.py", line 79, in on_message await bot.process_commands(message) NameError: name 'bot' is not defined
any fixes
define bot...? gonna need the full code ๐คท
fixed it i put bot instead of client
async def on_member_join(member):
guild = client.get_guild(1058181103132868619)
channel = client.get_channel(1058184521587105853)
embed=discord.Embed(title=f'Welcome To {guild.name}', description=f'Hello, {user.mention}.')
await channel.send(embed=embed)```
im trying to make a welcome event so when someone joins the server this come up. it's not working though, there's nothing in the terminal and no problems so im not sure whats wrong. all intents are on
read that if your commands arent working
its not a command
anyone know why whenever i run this command @client.command() async def create(ctx, channel_name: str): guild = ctx.guild existing_channel = discord.utils.get(guild.channels, name=channel_name) if not existing_channel: await guild.create_text_channel(channel_name) await ctx.send(f'Created new channel: {channel_name}') else: await ctx.send(f'Channel {channel_name} already exists') it creates 2 channels?
elaborate on your issue
its supposed to send a welcome message when someone joins the server but its not working
in dms right?
no, in the server
hm
the event handler itself seems fine, so can you show the rest of your code (without token) in a paste? perhaps the event handler is on the wrong client, or another handler is shadowing it with the same name
!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.
you might have two instances of your bot running, or you're accidentally calling process_commands() more than once
nah i reset the token but i will see if im calling process_commands() more than once ๐
you've forgotten to pass the intents to the last definition of your client, which btw you only need one
nice arrow
ok maybe a bit of a confusing arrow but i mean writing the same intents=intents inside the Bot constructor
ohhh
ok ty
client = commands.Bot(command_prefix = "k!", intents.members=True) like this?
i meant writing the same intents=intents inside the Bot constructor
oh
also discord_slash is a pretty outdated library, discord.py v2.0+ already has native support for slash commands
iirc support for dpy 1.7 is going to die pretty soon because the v6 gateway is going to be removed
ok, ty for letting me know
!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.
why do you create 3 clients in the first place lol
delete lines 14 and 16 altogether
@hushed galleon i cant seem to find a issue you mind looking at my code and seeing if you can spot any? https://paste.pythondiscord.com/celasivelo
you're not meant to use process_commands() in a listener
omg thank you so much, it finally works
its the same thing described in the FAQ entry you linked earlier
the .event decorator?
yes thank you.
do i have to manually sync the command tree?
you should, yes
Could someone explain to me the difference between using command.commands() and bot.tree.commands()? I'm looking at the documentation and it says they should be equivalent, but when I use command.commands() none of my commands work.
I'd like to understand what exactly is happening. I think the root in there is the bot object that I declare? Would it make a difference if instead of something like :
bot = commands.Bot(blah blah blah)
I would have done something like
bot = commands.Client(blah blah blah)?
difference between using command.commands() and bot.tree.commands()
neither exist, perhaps you meantcommand()?
commands.Client doesn't exist either
True, typo on my end. My bad. But my point stands. command.command() doesn't work
how so?
should?
well... you could sync in on_ready or equivalent, but like at that point you're just begging to get ratelimited
is that another typo? cause it's commands.command()
so discord never syncs by itself?
you sync your commands with discord
not the other way around, discord doesn't develop commands
i thought they'd detect changes & update or smth
Damn, got me again. I'm losing it. But yeah, swapping between commands.command(blah) and bot.tree.command(blah) kills it
they might as well just access your computer at that point lol
@commands.command() converts the function to a prefix/message command. The command doesn't get automatically added to the bot when using this deco
@tree.command() converts the function to a slash command. The command gets automatically added to the tree when using this deco
why didn't you have to sync prefixed commands then?
prefix commands are just fancy message parsers, unlike slash commands
got it, thanks
sure
Unfortunately, I have more silly questions.
I'm trying to replace some repetitive code in my commands with a decorator. I only want certain commands to work in certain channels. Right now I just have a basic check that I outsourced to a helper file in a function that returns a boolean and if it's False, send an error message.
I just don't want to keep calling this function. I found the bot.check() decorator, and I'm passing the function, but it keeps giving me an error. Specifically that a Command object doesn't have an attribute called guild, which tells me something is funky with the interaction being passed.
Any ideas?
code? error?
Error:
Can you show us your decorator & command?
I know that decorators are run from bottom to top and was experimenting with the order, so that is after I swapped them just to see what would happen
!d discord.ext.commands.Bot.check
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
use @commands.check instead
it should be ```py
def correct_channel(ctx):
right_channel_name = "testingbot"
channel = discord.utils.get(ctx.guild.channels, name=right_channel_name)
right_channel_id = channel.id
current_channel_id = ctx.channel_id
if current_channel_id != right_channel_id:
return False
return True
@bot.tree.command(name="signup", description="Register the user into the database.")
@commands.check(correct_channel)
async def signup(...):
...```
flipped the decorator order and used commands.check instead of bot.check
@lethal creek FYI your entire function can be shortened down to
def correct_channel(ctx):
return ctx.channel.name == "testingbot"
I think you might be overcomplicating a bit ๐
I tried this before, but keep getting that app_commands isn't defined
you gotta import it from discord
from discord import app_commands
or use the full namespace discord.app_commands.check
I could totally defend myself by saying that my motto right now is "get it working, then get it working well", but man... that's just embarrassing.
isn't there an existing way in the library to restrict the channel?
Not a bad strategy.
You got it working, now get it working well :P
can't you pass it to bot.tree.command?
no you can only restrict the guild
nvm
The first thing I tried was to go through the documentation because I noticed that there was a way to restrict it by guild.. figured there HAD to be a channel one too, right?
I was wrong.
There isn't. Discord.py is quirky like that
๐
So then if I want to use check() with slash commands I have to use app_commands?
you were right in searching the docs first though!
yup
the commands framework and app_commands rarely interact with each other
I'm trying really hard to do my due diligence first. But man, some of these docs are... rough.
I think I got it to work... except not in the way I expected.
that's the philosophy of the people that run Discord.py, you better already know everything because the docs are just note and you are dumb for knowing less than them.
check() will only accept a function that returns a bool, correct? So if it evaluates false, the command doesn't run, which results in an error?
I'm plenty dumb already. Just trying to whittle away as much dumb as possible each day.
you can catch the error in an local error handler
it can return anything falsey
Good luck, if you are anything like me you just start learning how big the dumb pile really is.
so py return None or py return [] will also prevent the command from running
but yeah you should just return true or false
Just to be explicit I would recommend return True/False
"Explicit is better than implicit"
type checkers will shout at you if you don't 
Yeah. Recently got pyright installed for my Emacs configuration and man it will not shut up no matter what I do
I've gotta figure out how to turn off strict mode
the only reason why I have it set it to strict is because it makes me feel smart 
Real smart people dont use type checkers
from discord.ext import commands
intents = discord.Intents.default()
intents.members=True
client = discord.Client(intents=intents)
client = discord.Client()
client = commands.Bot(command_prefix = "!", intents=intents)
client.remove_command('help')
@client.event
async def on_member_join(member):
guild = client.get_guild(1023746108830257173)
channel = client.get_channel(1023746108830257177)
await channel.send(f'{member.mention}', delete_after=5)
@client.event
async def on_member_join(member):
guild = client.get_guild(1023746108830257173)
channel = client.get_channel(1026071401825841233)
await channel.send(f'{member.mention}', delete_after=5)
client.run("") ```
im tryna make a bot where it pings someone 5 minutes after they join in 2 different channels. everything works except when someone joins, it only pings them in one channel and not both, i was wondering if someone could help me please (im not doing the 5 minutes thing yet) btw thats my whole code
.event overrides the old event with the new one
Also why are you trying to create client 3 times
why not just do py @client.event async def on_member_join(member): channel1 = client.get_channel(1023746108830257177) channel2 = client.get_channel(1026071401825841233) await channel1.send(f'{member.mention}', delete_after=5) await channel2.send(f'{member.mention}', delete_after=5)
I removed the guild variable because you weren't using it
also this
anyways thanks
how would i make it send it after 5 minutes?
use asyncio.sleep
ok ty
i have a question about asyncio.sleep
await asyncio.sleep(30)
bot.loop.create_task(on_ready())
for example here i set 30 seconds and its in loop now. Is there any harm in having too little or too much value for it?
๐ฅ๐ผ
im getting an error right now;
discord.http We are being rate limited. PATCH (URLOFCHANNEL) responded with 429. Retrying in 271.80 seconds.
just fixed rn by setting asyncio.sleep at the beginning of the code. anyways thx for your time
yo if i want the first value of the embed then is it good to use search instead of findall?
I've got a friend starting out with coding bots in python... but there's something wrong with his libraries. I'm unsure on what cause this didn't happen to me when I started out (or its been so long that I've forgotten?)
Traceback (most recent call last):
File "C:\Users\main\Downloads\AAAAAAA\AAAAA.py", line 2, in <module>
import discord
File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\__init__.py", line 23, in <module>
from .client import *
File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 46, in <module>
from .ui import print_banner, start_logging
File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\__init__.py", line 12, in <module>
from .view import *
File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 36, in <module>
from ..components import (
ImportError: cannot import name 'Component' from 'discord.components' (C:\Users\gibbs\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\components\__init__.py)
Thats the error message
first value as in?
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
charset-normalizer==2.1.1
discord==2.1.0
discord.py==2.1.0
frozenlist==1.3.3
idna==3.4
multidict==6.0.4
yarl==1.8.2
Those are his installed packages
remove the discord library
like the top value of the embed
File "C:\Users\main\Downloads\AAAAAAA\AAAAA.py", line 3, in <module>
import discord.net
ModuleNotFoundError: No module named 'discord.net'
Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement discord.net (from versions: none)
ERROR: No matching distribution found for discord.net
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='/', intents=discord.Intents.all())
@client.event()
async def on_ready():
print('we have logged in!')
client.run('TOKEN')```
why is this not working?
whats the error?
remove the parentheses
remove () from client.event
@client.event
async def on_ready():```
how would you remove a file from a message?
^ editing the message + passing file=None causes AttributeError: 'NoneType' object has no attribute 'fp'
why are you trying to import discord.net?
Wrong language ๐
you should be able to do py await message.edit(attachments=[])
!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.
Go to that link and enable all 3 intents
he misread .ext as .net ๐
enable from portal
lol happens
Aight, next library
from dotenv import load_dotenv ModuleNotFoundError: No module named 'dotenv'
pip install python-dotenv
oh
maybe he's mispelling it?
I'm on a call right now with him ๐
python-dotenv
install it
yeah
docs say theyโre different things
well a file is an attachment though
when editing a message it's an attachment, not a file
and you cannot pass files to an .edit call
it should be a common sense that a file is a stored object, while attachment is a part of a message
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
oh you're using a different library
idk you can try message.edit(files=[])
discord.py does it using attachments=[]
I would recommend trying that with pycord regardless
its same for either
pycord is nothing but a fork
and same Endpoints are being used there
I know but clearly the edit method is different
discord.py does not support a file or files argument, only attachments
whereas pycord accepts the former two
I think pycord forked from dpy 1.7.3 where those arguments may have been defined
might seem like that but no its same
property edit
This function is a coroutine.
Edits the original interaction response message.
This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.
its just message.edit in background
what
is this not true
I'm not seeing file-related parameters in either of these places
whereas pycord does have file related parameters
i said that context.edit is nothing but a shortcut to message.edit
disagreed to this point
there's both file and files kwarg in discord.py
!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**.
discord.py's discord.Message.edit method does not support a file parameter

since when are we talking about the sendmethod lol
clearly the edit method is different
i'll add it to the ever growing list
Is there a reason pycord has file(s) in edit
๐ (why are reactions disabled in this channel
)
Oh wait, no discord.py is the weird one here
only way to find out is reading src
!d discord.InteractionMessage.edit
await edit(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
I see, both use multipart form data
But yes the offical API has a file[n] parameter
ig discord.py did that to maintain consistency between Message.edit and InteractionMessage.edit
And an attachments parameter
any help?
uhh whats the color code for invisible embed?
!d discord.Color.dark_theme
No documentation found for the requested symbol.
or the color which matches discord's bg color
!d discord.Colour.dark_theme
classmethod dark_theme()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x36393F`. This will appear transparent on Discordโs dark theme.
New in version 1.5.
i hate the british spelling
do U :p
At least when the documentation only works for one version, haha
Even though discord.py is aliased to use either
Oh no! You got bit by the Rust bug too eh. (I'm trying really hard to ignore Rust and Go and focus one lang lol (I peeped your prof)
It has indeed! I'm having quite a bit of fun - all that really matters to me at the moment ๐
Oh see why'd you hafta go and say something exciting like that when I'M ON A DIET! =P
d! Pandas
Can't hurt to try, friend!
regex returns a list right?
whats the actual question?
!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.
depends on which function of regex
figured thanks
getting this error when importing the discord-py-interactions file addon thingy ma bob
Traceback (most recent call last):
File "c:\Users\Lenovo User\Desktop\LifeAsPy\Hypixel Api\LobbyChat\testing.py", line 3, in <module>
from interactions.ext.files import command_send
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\ext\files\__init__.py", line 1, in <module>
from .files import *
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\ext\files\files.py", line 15, in <module>
from interactions import (
ImportError: cannot import name 'LibraryException' from 'interactions' (C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\__init__.py)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000217889E1090>```
even the example is giving that error
Just use discord.py's command tree
async def defaulttest(self, interaction: discord.Interaction, create:str=None) -> None:
The same way I made that create:str=None parameter, is there a way to make it a selectable option but you dont have to type anything into it?
I assumed that you're talking about choices
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/transformers.py#L80-L87
examples/app_commands/transformers.py lines 80 to 87
# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.
# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
Literal is from typing module btw
how do you use arguments or options or whatever you call them with discord.py?
examples/app_commands/basic.py lines 47 to 54
@client.tree.command()
@app_commands.describe(
first_value='The first value you want to add something to',
second_value='The value you want to add to the first value',
)
async def add(interaction: discord.Interaction, first_value: int, second_value: int):
"""Adds two numbers together."""
await interaction.response.send_message(f'{first_value} + {second_value} = {first_value + second_value}')```
than kyou
Tring to code a purge command, however it only deletes int-1 of whatever value I put, doesn't send the embed and gets this error in the code: discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
Any help would be great
@bot.tree.command(name='purge', description='Deletes a specified number of messages from a channel')
@has_permissions(administrator=True)
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)```
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
can you tell how to get the numbers at start?
!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.
how do i let my bot go online?
yes but what is the code to get the bot online?
it says things about intents
here
did it
but still not working (this is my first bot btw)
yes
do you have like a standard code to get the bot online?
There's basic examples in discord.py GitHub
can you help with regex 
from discord.ext import commands
at the start of the code near imports, paste this
it still does not work
don't you just have a standard code template that is used to get a bot online?
i can't this will be like 20 screenshots
its so long
!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.
this is not even all
i did
oh oops
that was an old screenshot
i already tried
i tried like 6 times already
Reset your bot token also
i did
how can i detect reactions?
I need to figure out the bot commands around here.
It's because you need to have your token as a string. Without it between "" the computer thinks you are trying to call a variable.


