#discord-bots
1 messages · Page 198 of 1
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1d6+1d24: [2, 19]
002 | 1d28+1d49: [22, 3]
003 | 1d500+1d893+1d5+1d9: [406, 237, 4, 3]
@slate swan is this what you want
[random.randint(1, int(i)) for i in re.findall(DICE_PATTERN, user_input)]
You can even oneline that function to this
And yeah have a good workout
anyone that got any experience with humanizer?
You should claim a help channel: #❓|how-to-get-help
okay i'm back
i'm planning to also use normal numbers to make operations
guess i'm not used with that kind of function
i'm using the basics of programation i have
i need it more explained, i'm new to regex. it's like a clusterfrick for me
is there any way to call an interaction from code itself?
You extract the main logic and extract it into its own function
Then you call that
Also good for TDD
what's tdd
okay i'm starting to learn it
Test driven development
!regex
Regular expressions
Regular expressions (regex) are a tool for finding patterns in strings. The standard library's re module defines functions for using regex patterns.
Example
We can use regex to pull out all the numbers in a sentence:
>>> import re
>>> text = "On Oct 18 1963 a cat was launched aboard rocket #47"
>>> regex_pattern = r"[0-9]{1,3}" # Matches 1-3 digits
>>> re.findall(regex_pattern, text)
['18', '196', '3', '47'] # Notice the year is cut off
See Also
• The re docs - for functions that use regex
• regex101.com - an interactive site for testing your regular expression
So basically it extracts 38 from 1d38. \d+ in regex means "digit repeated one or more times"
There's lots of syntax and patterns might seem complicated (hence simple link regex is https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*), but once you get hang of it it is not that hard
well, i'm gonna have a study now, i'm also planning to use the number before d since the first number represents how many times i'm rolling the same dice
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
hey with this code it only prints me SequenceProxy(dict_values([])) even i get the guild
if data["hunger"] <= 0:
server = await bot.fetch_guild(526180194810******)
print(server.channels)```
that's correct
server.channels is a sequence
you can just iterate through it normally for channel in server.channels or convert it to a list if you really felt like it list(server.channels)
it only gives me []
then your bot doesn't have access to the channels in that guild
it has
it has admin previlage
It looks like fetch_guild will not update the channel list
you should do await guild.fetch_channels()
it workde thx
any1 can help why its not working >
you need to be a lot more specific than "it's not working"
I assume you've read the error at least right?
yeah i read it but i dont really understand lmao kinda new into this
it says "unexpected keyword argument 'name'"
and if you scroll up a bit it tells you that the error is caused on this line
the error is telling you that Embeds don't have names
did you mean to give it a title instead?
how do i make the dice roll as a matrix?
i'm planning to not use "1d" since the number before "d" is used for indicade number of rolls
that can happens a multiroll
Just list comp inside list comp
!e ```py
import random
user_input = [(2, 6), (5, 10)]
output = [[random.randint(1, maxval) for _ in range(count)] for count, maxval in user_input]
print(output)```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
[[2, 3], [3, 5, 7, 3, 2]]
Anyone got an idea who this wouldn't remove the entry from the database:
await db.execute('DELETE FROM afk WHERE user_id = ? ',(message.author.id,))
It puts it into the database, just doesn't delete it
check for name='cmd name' and then async def ...
there might be an overlapping one
Is this an error that your facing? or a joke. bc like i actually cant tell with that crying lemon lmao
there is only one command.....
its an error
oh so one of the commands are used twice
async def load(ctx: discord.Interaction,extension:str):
if(ctx.author.id in ADMINS):
try:
print(extension)
bot.load_extension(f'{extension}')
await bot.sync_commands()
await ctx.response.send_message("Cog loaded.",ephemeral=True)
except Exception as E:
await ctx.response.send_message(E,ephemeral=True)
raise E
....................................
class LANGUAGE_SELECTION(discord.ext.commands.Cog):
def __init__(self,bot):
self.bot=bot
def auto():
return LANGUAGES
@bot.slash_command(guild=config.GUILD, description="Set your Translator Language.")
async def set_language(ctx: discord.Interaction,language: Option(input_type=str,description="Select a Language.",autocomplete=auto())):
print(language)
def setup(bot):
bot.add_cog(LANGUAGE_SELECTION(bot))
Ignoring exception in command load:
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "e:\Python Projects\Translator\Cog_gathering.py", line 18, in load
raise E
File "e:\Python Projects\Translator\Cog_gathering.py", line 14, in load
await bot.sync_commands()
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1: Application command names must be unique
@tawdry tendon
is this the whole thing?
excluded the non related things but yeah, these are the only commands other than unloading ones
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
!list-statement
the problem now is on my calculation thing
like, i'm planning to make the operator thing to calculate the arguments input to total
like 1d6[5]+2d5[2,3][8]+8 result into 21
maybe when i implement the input accept separance between () and [] i will need to make it recursive
and when i implement the stat system the {} thing being the identifier for stats
idk what I did
but whenever I run my code this happens the bot doesn't work, it was working fine before idk
and when I go to discord the bot appears online
but again none of the commands run
!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.
your method won't work lol
reinstalling python will always install it as python
not python3
it installs it as python3.x for me
!e
print(["a" if n % 2 else "b" for n in range(10)])
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
['b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']
im curious to know but is there a googletranslate package w pyton?
like i want to make a translate command
i mean things like this dont need an update as long as the base API doesnt make a breaking change
oh i see, and if i need to put an elif?
thanks for the first information
you guys are making me adapt my basics of programmation to advance into python
with that i will learn wonder stuffs that i never knew
elifs aren't supported. You could chain if-else though, but that'll probably make your code look a lot messier and unreadable
"a" if n % 2 else "b" if n % 5 else "c"
ty
now it will makes my code even cleaner
"a" if n % 2 else ("b" if n % 5 else "c")
``` for the sake of readability
no it makes your code worse
he already said it makes it look messier
don't just try to fit everything in one line
well, in a certain case it will be useful
the calculation thing
but good to know that the basics willl be still valid
depends on what kind of datamining
messages?
then probably, you at least want some kind of privacy policy, don't do it without consent
!e print(“amongus”)
I'm trying to create a 8ball slash command, and appereantly it doesn't work due to: "parameter 'question' is missing a type annotation in callback 'eightball.' "
@bot.tree.command(name="8ball", description="Checking with the bot's health.")
async def eightball(interaction:discord.Interaction, *, question):
responses = [
'It is certain.',
'It is decidedly so.',
'Without a doubt.',
"I'm feeling well",
'Yes - definitely.',
'You may rely on it.',
'As I see it yes.',
'Most likely.',
'Outlook good.',
'Yes.',
'Signs point to yes.',
'Reply hazy, try again.',
'Better not tell you now.',
'Concentrate and ask again.',
"Don't count on it.",
'I cannot predict now.',
'My reply is no.',
'My sources say no.',
'Outlook not so good.',
'Very doubtfull.',
'I am tired. *proceeds with sleeping*',
'As I see it, yes.',
'Yes.',
'Positive',
'From my point of view, yes',
'Convinced.',
'Most Likley.',
'Chances High',
'No.',
'Negative.',
'Not Convinced.',
'Perhaps.',
'Not Sure',
'Mayby',
'Im to lazy to predict.'
]
await interaction.response.send_message(f":8ball: Question: {question}\n:8ball: Answer: {random.choice(responses)}", ephemeral=True)
use " instead of ”
you need to put : str after question, because all arguments in a slash command need to have a type or else discord.py doesn't know what to send to the discord api
!e print(yoaiaj)
@abstract pewter :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'yoaiaj' is not defined
?
Thank you so much. It worked
no problem
Sorry just messing around I have no idea what I’m doing
alright
it's funny how it's always the one missing code that can mess up entirely for you
if you want to try the bot out, you can use #bot-commands or #sir-lancebot-playground by the way
and yeah @steep marsh errors do often work like that lol
tyty
I am unable to check at the moment, but pretty sure it has alias executables
anyone know how to decode these?[<function is_owner.<locals>.predicate at 0x7fa247167790>, <function has_permissions.<locals>.predicate at 0x7fa2471675e0>]
Call the function
what if im trying to get the permission inside of a help command, how would i do that?
does anyone know why this doesn't work? ```@bot.command()
async def help(ctx):
help_embed = discord.Embed(
title="Help Menu",
description="A list of available commands:",
color=discord.Color.blue()
)
help_embed.add_field(name="ex", value="ex", inline=False)
help_embed.add_field(name="ex", value="ex", inline=False)
help_embed.add_field(name="ex", value="ex", inline=False)
await ctx.send(embed=help_embed)```
Which part of it, be specific
like when i run the command the embed does not show/ the command does not run
not for python3, no
You able to reply to my other comment?
are you subclassing help?
yes
But that person's issue was fixed after they did my solution, did they start using python instead of python3 or something
probably
show your code
i have other code at the top which filters the command_set etc, but here im trying to get the perms required for the command
aiohttp is having problem
params or perms?
where is the permission code though?
i deleted it for now but it would go on around line 88
yes
sorry i'm stupid
everytime i printed it, it'd output the function has_permissions.<locals>.predicate etcetc
i see that but i'm trying to figure it out though, dont quite get it
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.
it returns a list of callable checks
it doesn't say what specific one though
bruh @unkempt mauve https://paste.pythondiscord.com stop flooding chat
how would i go around that?
f
to get the exact permission it needs so like Administrator, ban_members, the list only returns the functions
probably something like
for check in command.checks:
if check == commands.has_permissions:
...
@smoky sinew he's tryna make it so he has this^ on the help embed from the command. so if he does !ban it'll send the usage/help embed and then a field is Permissions with the matching permission needed for it
i'm aware
alright just making sure
tried that no result
i'm checking to see what it returns
returns nothing 🤷
no..
if it returned nothing, it would be Optional
but it's List[Callable[Context, bool]]
using this code, nothing returns
what does command.checks return then
when i print that? with the s on commands or without
command.check: [<function is_owner.<locals>.predicate at 0x7fa247167790>, <function has_permissions.<locals>.predicate at 0x7fa2471675e0>]
commands.check: <function check at 0x7fa24c8a9700>
huh
if i print either of those those are the results
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
@lean plank I doubt you can really get what permissions command needs to run with dpy. Maybe you can get all function decorators somehow and extract data from there, let me check
!d inspect.getsource seems like a possible way
inspect.getsource(object)```
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised if the source code cannot be retrieved.
Changed in version 3.3: [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised instead of [`IOError`](https://docs.python.org/3/library/exceptions.html#IOError "IOError"), now an alias of the former.
thanks
I'm currently trying to make a "dad jokes" command, and when I run the command in my server the bot answers: 403.
May someone help me out?
@bot.tree.command(name="dadjokes", description="Jokes of what most dad's would say.")
async def dj(interaction:discord.Interaction):
url = "https://parade.com/940979/kelseypelzer/best-dad-jokes/"
async with request("GET", url, headers={}) as response:
if response.status == 200:
data = await response.json()
await interaction.response.send_message(f"**{data['setup']}**\n\n||{data['punchline']}||")
else:
await interaction.response.send_message(f"{response.status}")
the response.status says 403, it means forbidden, you dont have credentials, kinda unrelated to discord.py
ahh alright, thank you
welcome
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot: return
cursor = await self.bot.database.cursor()
await cursor.execute('SELECT * FROM afk WHERE user_id = ?', (message.author.id,))
data = await cursor.fetchall()
timestamp = data[0][2]
time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
if data:
await cursor.execute('DELETE FROM afk WHERE user_id = ?',(message.author.id,))
else:
return
await self.bot.database.commit()
await message.channel.send(f'Welcome back, you were away for **{time}**')
if message.mentions:
for mention in message.mentions:
await cursor.execute('SELECT * FROM afk WHERE user_id = ?', (mention.id,))
data = await cursor.fetchall()
await message.channel.send(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')
Bot isn't sending message and not getting data from database if a person gets mentioned who is in the database.
No errors and no returns when printing/sending the data.
Does the listener even react to messages
There's some stuff
- Weird stuff, how are you trying to access
data[0][2]and only checkif dataafterwards? - This construction should be inversed
if data:
...
else:
return
# to
if not data:
return
...```
Hello
Cat

How do you mean, how am I trying to access data?
Im getting the data from data = await cursor.fetchall()
And then I'm getting the timestamp from the database
Which is data[0][2]
You would get IndexError if you would try to access an element of an empty list
data is a list I presume?
It isn't empty
Then why even check for it
Yes
That part works, it's the part with the mention.id that doesn't work
The first part isn't the problem
It's from here:
if message.mentions:
for mention in message.mentions:
await cursor.execute('SELECT * FROM afk WHERE user_id = ?', (mention.id,))
data = await cursor.fetchall()
await message.channel.send(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')
That part doesn't work. The for loop works because it prints the mention if i do print(message.mentions)
Maybe only send a message for first mention? Just for security reasons, if someone mention-spams your bot might start spamming in the channel
Wouldn't work
It'll only send the message if the entry is in the database
it's my AFK listener
Yeah I know
so it's checking for people in the afk table
if they aren't in the table and they get mentioned, it wont send the message
But still case when attacker pings specifically people with AFKs set is possible, potential security vulnerability
Not really
But that isn't the problem
Let's focus on the problem that I came here for instead of trying to solve other stuff that isn't needed
You need to check it in a different way
data = await cursor.execute("SELECT EXISTS(SELECT * FROM afk WHERE user_id = ?)", (user_id,))
exists = (await data.fetchone())[0]
if exists:
await send(...)```
Let me see if this works
Actually would be better if you made a single query but sqlite probably can't do that
Also, the [0] is the row right?
Yeah
EXISTS returns 1 if the row exists, 0 if doesn't
Yeah i need the second value from the table
so for me it goes: user_id, status, timestamp
I don't remember how correctly it's named in aiosqlite
and i need status
You don't select *, you select EXISTS(...), it is a single value
Look at the query
It might be fetchrow instead of fetchone
Yeah I just don't remember how it is named in aiosqlite
Still nothing
The way I did it should've worked because I've used it before
In my old on_message code it worked, but something else was broken and it was pretty messy code. hence why i'm rewriting it.
But it did send me the message and data etc.
This is the old code I used. The message.mentions stuff worked on that code.
This is with the old code
can u try printing what await db.fetchval("<query>") returns? Instead of await db.execute? I can't remember what it does but I remember that's a method
I'm sorry what
never mind you're using the cursor object
Yeah I know
for mention in message.mentions:
print(await cursor.fetchval("YOUR QUERY HERE"))
SELECT...
yep that's called a query
Oh had no idea
Now you know :)
try it with this query by the way
yeah it's not even letting put the fetchval in properly, it's erroring in the edi
ide*
Nevermind
weird, the method doesn't exist then I guess that's my bad
strange
mhm
sorry can't help you right now omw home
that's alright
just hoping someone can help me to fix this
because it's very odd why it isn't working
are u sure you're not using a method on your cursor before this? You can only use it once
i have been using this button every time i have to stop code
is there a better way in which you dont have to kill terminal?
i tried using the shortcut to stop code but didnt work
As far as I'm aware, yes
A. close it through an eval command with bot.close (cleanly closes the bot)
B. close it with ctrl + c in the terminal
or C. I'm pretty sure vsc has a "stop" button when you run code through it
there's also a handful of other ways to stop your running code depending on how you run it or if you use a process manager, etc, etc
SOLVED
ah thanks
i was running with code runner and for some reason it couldnt stop it
ctrl + c worked
Hey guys, how do I install Socks if I have already done pip install socks and it's still giving me error saying " module not found - socks "
should i use disnake, pycord, or discord.py
Yes, discord.py, by far
I didn't even hear about what is "disnake"
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
discord.py if noob else disnake
shouldn't it be the other way around though
discord.py's slash command interface is more complex than disnake's
discord.py has a bigger community more tutorial while disnake offers more modularity and feature wise its structured very nicely as well
con is u have to read everything from the docs and make it urself
use hikari if u wanna go next level
Take it as an example: if you don't know math you'll use the math library, if you know math you don't need the library. (The same goes for discord.py - disnake libraries).
I mean, even if you know math, you would often still use the math library out of convenience 🍨
Get the point of example
Sup guyz
i dont see how that's a con lol
98% of the dpy "tutorials" you see are outdated
relying on the docs is a pro
discord.py docs is goated
True.
I use math library despite being proficient at it.
Why would you watch tutorials in the first place
Especially YouTube tutorials 
i mean there are up-to-date tutorials too but they get outdated quite quick
some people learn better when they can get a visual representation of something, than just reading, i know for a fact that i do 🤷♂️
but i still use docs and src code
maybe get better at reading?
yeah, something i train on
Not really, math module "wraps" math, while discord.py and disnake both wrap discord API
It's not about visual representation, it's about ready code 🤓 or people who prefer to listen to something instead of reading it
In videos they should be explaining some stuff that might not be explained in docs/articles, but specifically for discord.py I have seen many showing discouraged practices which is a problem
yeah that can sometimes be seen by beginners too
i'll give an example, i'm currently taking the CCNA certificate, all the resources are written - it is extremely technical with many jargons. i started watching videos instead and it certainly helped me to better understand the theory
but this is quite unrelated to discord.py, i feel like anyone should learn the way they know they'll learn the best. docs and src codes are almost always up to date so it's the best resource someone can have access too, videos is a great alternative to beginners who have harder times understanding technically written documentation
Extremely technical tutorials are created by experienced people with education, that's the difference from dpy
🍿
there is a reason to why dpy discourages beginners to code in dpy
Meta question but: why can't we put reactions on messages in this specific channel?
It is possible on every other channels in "Topical Chat/Help" section so I don't get the logic.
It is also almost the only one to have slowdown mode activated.
Ok slow mode is configured for 5 seconds so it's fine, but I think it's useful to put reactions on messages like 👍 or 👎
#python-discussion and #discord-bots are the two most active channels iirc, allowing emoji reactions could be prone to spam
and you should ask in #community-meta for more
Oh this channel is more active than the others?
Thanks, I was looking for such a channel
I don't think so 
Its the second most active behind #python-discussion
Hmmm, I guess I'm not active enough to notice
Can u give tutorial for making a bot in python? (I started python 3 days ago so please, I'm a noob)
guys, i noticed that when an array have only intergets i can't use range
what do i use instead?
What
i'm planning to use the number of indexes as a range for my while
like this:
#then it will be calculated the sum and subtraction
print("calculating rest")
if indice[cont-1] == "+":
sub_total = sub_total + store[count]
elif indice[cont-1] == "-":
sub_total = sub_total - store[count]
count = count+1
indice.pop(all)
store.pop(all)```
anyone help? PLEASE
can someone please help me with my bot i made some simple embed message commands but i have no idea how to combine my script with another
i want to make a command that when i type csc ltc [my litecoin adress] to send how much money it received and how much money it send
import requests
address = "typetheadresshereplsplsplspls"
api_url = f"https://api.blockcypher.com/v1/ltc/main/addrs/{address}/full"
response = requests.get(api_url)
txs = response.json()['txs']
total_received = 0
total_spent = 0
for tx in txs:
for output in tx['outputs']:
if output['addresses'] == [address]:
total_received += output['value']
for input in tx['inputs']:
if input['addresses'] == [address]:
total_spent += input['output_value']
# Print the results
print(f"Total received: {total_received / 1e8} LTC")
print(f"Total spent: {total_spent / 1e8} LTC")
i have this code and idk how to turn it into a command
Anyone can tell how to make a discord music bot plz
i have a frnd who made it DM ME
guys, when i try this this error occours with me:
list index out of range
code:
for cont_ ,num in enumerate(store):
#first it will calculate the division thing
if indice[cont_-1] == "/":
print("calculating /")
sub_total = store[cont_-1] / num
del indice[cont_-1]
del store[cont_]
del store[cont_-1]
pivot = cont_-1
while indice[pivot] == "*":
sub_total = sub_total * store[pivot]
del indice[pivot]
del store[pivot]
pivot = cont_
while indice[pivot] == "*":
sub_total = sub_total * store[pivot]
del indice[pivot]
del store[pivot]
store.append(sub_total)
indice.append("+")
sub_total = 0
the code works until while
then when it reaches while the code gives me that output
this is another thing
the dice are working
now i'm working on a function that calcultate the total
Of dices?
yep, first calculate division then multiplication then sum and subtraction
It shouldn't be that huge 
!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.
@slate swan so input you have is a list of lists and you need to calculate what?
i need to calculate the result of the dices into the total result
like 2d6[1][5][6]*1d5[4]/2 = 12
the sum and subtractio part is working
but the division seems problematic
Uh what kind of formula you use
Dot product of sums of outcomes divided by two or something
this:
sub_total = store[cont_-1] / num
like it gets the previous number and divide by the actual number
then it pops the both numbers and check if there is * in the previous expression from indice
if yes it multiplicate
but doesn't seems to work
it also do the same for next numberszx
*numbers
but i guess this thing can helps me
Sounds like #algos-and-data-structs things
it don't need, all that is need is to calculate the numbers
can you not use elif?
You could
Guys, I need some opinions!
Which of the discord py wrappers is best/do you use and why?
• disnake
• discord.py
• NAFF
• interactions.py
• nextcord
• hikari
• others?
its the one i found
btw has anyone tried making a chess discord bot yet?
seems like a fun project
I've not tried, could be much fun, there are a few out there already
What's the best approach to getting my discord bot to ping users at random times during the day
discord.py is basically also the first one that was made
I've already got the pinging system down by users registering with a slash command but the scheduling is really tricky
I've only really used discord.py. I have never had any real issues with it, and it has a very active support server.
That's also the one I'm currently using.
ok
make c h e s s v a r i a n t
chess960 bot 🙀
i find hikari the best out of these
discord.py and Disnake are also nice, tho Disnake is just a fork
why?
it's much more low level than discord.py and other libraries, you have more control over the ecosystem
it also supports rest apps for applications like a bot dashboard or an API
it looks confusing to understand
what about it seems confusing lol
if you're gonna start with keeping your discord.py stuff in mind it will for sure be confusing
I have used NAFF before too which is also an independent wrapper from dpy
their design is mostly inspired by discord.py and they are completely open about that lol
read their GitHub readme
Discord.py fork?
While this library shares features and some stylistic choices with discord.py, it is completely separate from them. We think discord.py is a fantastic library, but we disagree with the direction and design decisions that were made by it
take a look at this https://github.com/Rapptz/discord.py/tree/master/examples/views
Hey all, how can I store my bot token in a seperate file and pull it into bot.run
Take a look into .env (or dotenv) files to store environment variables
!pypi python-dotenv
here (#1075839125795655870 message) someone said to use a .py, whats the difference?
(I said to use a .py because you explicitly told how to store the token in a file)
yeah I mean a .env is also a file though im wondering why use that over a regular .py
im gonna ask bing
Hey, I'm trying to make my button create a text channel like a ticket but am unsure how to create the channel in the class?
class OrderChannel(discord.ui.View):
@discord.ui.button(label="Order Now!", style=discord.ButtonStyle.success)
async def order(self, interaction: discord.Interaction, button:discord.ui.Button):
await interaction.response.create_text_channel(interaction.author.name)
AttributeError: 'InteractionResponse' object has no attribute 'create_text_channel'
!d discord.Interaction.guild you need the guild object to create the channel, create_text_channel isn't a response method
property guild```
The guild the interaction was sent from.
Im using pycord. How i can use slash commands in cogs?
!slash
envs are not limited to .env files, it can use any environmental variable located in your device, you can setup your token variable in a linux environment easily using export TOKEN="your token" and access it using os.getenv("TOKEN") in your program
not yet but that sounds like a good idea
Should I use while to repeat a block of code if a certain condition is true?
if len(queue) > 0 and len(current_players) < 10:
while len(queue) > 0 and len(current_players) < 10:
next_player = queue.popleft() # Get the next player in the queue and remove them from the deque
current_players.append(next_player)```
This will keep repeating the process of adding players to current_players as long as there are players in the queue and current_players has fewer than 10 players right?
How do i get kick command for mt bot
well i was going to get documentation but
why make a kick command? its already integrated into discord
bc i want to make it for my bot
!d discord.Member.kick
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick "discord.Guild.kick").
i'm trying to make a bot command that allows me to reset bots but it's not working:
or better, it's showing those error messages
syntax erroes
that's what i received:
PS C:\Users\Gabriel\Desktop\projetos python\RP Utilities> python: can't open file 'c:\Users\Gabriel\Desktop\projetos': [Errno 2] No such file or directory
using this:
os.execv(sys.executable, ['python'] + sys.argv)
try this if you mean that your trying to restart the code:
os.execl(sys.executable, sys.executable, *sys.argv)
PS C:\Users\Gabriel\Desktop\projetos python\RP Utilities> C:\Users\Gabriel\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'c:\Users\Gabriel\Desktop\projetos': [Errno 2] No such file or directory
os.execlp('RP Utilities', 'RP Utilities', "bot.py", *sys.argv)
this is assuming your main file is named bot.py
can you use slash commands in dpy?
and any pointers would help cause youtube and google isnt :)
YouTube tutorial moment
Yes, there's a walkthrough in the pins
👍
Do you have a python file called discord.py ?
Could you print(discord.__author__)
if thats right
Yeah did you try running that?
i
Its not discord.Bot its commands.Bot from discord.ext extension
this?
prolly not just asking
No
Dont nist copy paste what I said
You already have commands extension imported from discord.ext
Just have to replace discord.Bot with commands.Bot here
same error
You didnt save the file.
Pass a prefix
i can just add onto the intent line correct
Yes.
It is a positional arg so
bot = commands.Bot("!", intents=discord.Intents.all())
bot = commands.Bot(command_prefix=".", intents=discord.Intents.all()) oh ok
bruu
i have slash commands enabled
in dev portal
Mhm, in discord.py there isnt any slash_command decorator
For slash commands discord.py has @discord.app_commands.fommand and @bot.tree.command decorators
Maybe instead of copying someone's code you should read the docs.
its my friends code he gave it to me and i have no discord.py only main.py
Meh, you should probably learn python basics and then discord.py
i dont have time for that, I changed all to @discord.app_commands.command
Because you are doing it wrong
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
broo why cant u just tell me ill still read it tho
If you read it, you wont need to ask me
if it wasnt in a cog it would be much easier
i really dont know what to put down lol
There's no much difference
im just confused
idk what to put to fix my error
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
i added
Bot.tree.copy_global_to(guild=guild)```
thats what im using lol
Where did you get that from, first of all
thats what the dude told me to put thats all my coding besides the @discord.app_commands.command
she or him
you are using py-cord code and expecting it to work in discord.py
so what do i do?
read this
or check pins for a simpler guide
the code you have isnt even 10% functional in dpy
Hey, so I don't know why, but for some reason my commands don't work and I get no errors in the console
and I think it might be my intents
is this correct?
do you have an on_message event @graceful ermine ?
Yes
Okay
@slate swan
it was my anti spam
but it was doing the same thing when I tried to run my command
it doesnt change the functionality of anything
event overrides the default callback and ghosts the command callbacks
using listen() just creates a new listener instead of overriding the default ones
so your old stuff will work + the commands will work as well
Nvm it works
@bot.listen()
async def on_message(message):
author = message.author
if author == bot.user:
return
if author in spammers:
spammers[author] += 1
if spammers[author] > SPAM_THRESHOLD:
await message.channel.send(f"{author.mention} has been kicked for spamming.")
await message.delete()
spammers.pop(author)
else:
await message.channel.send(f"{author.mention} stop spamming!")
await message.delete()
else:
spammers[author] = 1
await asyncio.sleep(SPAM_TIMEFRAME)
if author in spammers:
spammers[author] -= 1
if spammers[author] == 0:
spammers.pop(author)```
this is my anti spam function
and when a bot logs something constantly
it keeps on saying stop spammingh
How could I make it stops saying that too a bot
Someone already answered
I wonder what kind of spam detection method this uses
can anyone tell me why my security bot does not bans , kicks or punishes members while testing anti nuke commands
no, nobody can tell you
you didn't even say anything
Hello, I have been experiencing some difficulties migrating to v2 can anyone help me figure out what is going on with the on_ready?
@client.event
async def on_ready():
await client.remove_command("help")
print(f"{color.FAIL}-" * 32)
print(f"{color.WARNING}Starting Bot!")
print(f"{color.WARNING}Loading Cogs")
print(f"{color.FAIL}-" * 32)
count = 0
for cog in cogs:
try:
await client.load_extension(cog)
count += 1
print(f"{color.OKGREEN}{count}: Loading Cog: {cog}")
except Exception as e:
count += 1
print(f"{color.FAIL}{count}: {e}")
print(f"{color.FAIL}-" * 32)
print(f"{color.WARNING}Cogs loaded!")
print(f"{color.WARNING}Bot Online!")
print(f"{color.FAIL}-" * 32)
print(f"{color.WARNING}Extras!")
print(f"{color.FAIL}-" * 32)
print(f"{color.WARNING}Serving {color.FAIL}{str(len(client.guilds))}{color.WARNING} servers!\n{color.WARNING}Serving {color.FAIL}{str(len(set(client.get_all_members())))}{color.WARNING} users!")
print(f"{color.WARNING}Running on discord {color.FAIL}{discord.__version__}{color.WARNING}!")
print(f"{color.WARNING}Running on python {color.FAIL}{platform.python_version()}{color.WARNING}!")
print(f"{color.FAIL}-" * 32)
while not client.is_closed():
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=(f'z!help | servers: {str(len(client.guilds))}')))
await asyncio.sleep(3600)
print(f"{color.WARNING}Online!")
async def Zim():
async with client:
await client.start(os.getenv("TOKEN"))
print('Ready')
asyncio.run(Zim())
extending on @graceful ermine's bot, as helping in https://discord.com/channels/267624335836053506/1075990389439336519:
I've noticed that muting users is commonly done via a muted role, but also sometimes via member.edit(mute=True). Is there reasons to prefer one over the other? edit seems easier
Yeah I never new that existed
Is there away that I could put a timer on that mute for like 10 minutes?
!d exencolorlogs you can use this for logging instead of those prints
No documentation found for the requested symbol.
!pypi exencolorlogs
I forget commands
@fringe narwhal ^ you can use this for logging instead of those prints
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., 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...
mute=True refers to voice mute
Second method is for voice I think
tbh ppl should use timed_out_until instead of roles
okay, but is that the problem? because my bot runs and gives no errors but my prints do not show up to tell me that it is operating how i want it to
thank you for the colors tho
where is your client defined
await bot.load_extension("cogs.utility")
or something else?
Some problems and resolutions
- Run bot like this
bot = comnands.Bot(...)
bot.run(token)```
You don't even need async with construction
2. Do not use while loop in on_ready, instead use `tasks.loop`
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
!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.
ive never used tasks.loop lol ive always done the on_ready that way
if commands.has_permissions:
e.add_field(name='Permissions', value=''))
how do i get what permission a command needs for a subclassed help command?
i think there is trouble with await client.start(os.getenv("TOKEN")) because it isnt printing "Ready" at all
import this: from discord.ext.commands import has_permissions
Use this for ctx: @has_permissions(kick_members=True)
That's not what I mean
It's for this:
async def send_command_help(self, command: commands.Command):
if not command.description:
command.description = ''
if not commands.parameters:
commands.parameters = 'N/A'
e = await self.help_embed(
title=f'Command: {command.qualified_name}',
description=command.short_doc
)
e.set_author(
name=self.context.bot.user.name,
icon_url=self.context.bot.user.avatar.url)
e.set_footer(text=f'Module: {command.cog_name}')
if command.aliases:
e.add_field(name="Aliases", value=', '.join(command.aliases))
if commands.parameters:
e.add_field(name='Parameters', value=', '.join(command.params))
if commands.has_permissions:
e.add_field(name='Permissions', value=''))
if command.usage:
e.add_field(name="Usage", value=
f"```\nSyntax: {self.context.clean_prefix}{command.usage if command.usage else ''}\n"
f"Example: {self.context.clean_prefix}{command.qualified_name} {command.description if command.description else ''}```", inline=False)
await self.get_destination().send(embed=e)
I'm subclassing my help command, but i need a field added which displays what permission you need for it
hmm
I doubt I can really get what permissions command needs to run with dpy. Maybe I can get all function decorators somehow and extract data from there, let me check
!d inspect.getsource seems like a possible way
inspect.getsource(object)```
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised if the source code cannot be retrieved.
Changed in version 3.3: [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised instead of [`IOError`](https://docs.python.org/3/library/exceptions.html#IOError "IOError"), now an alias of the former.
you are more experienced than me i think
ive figured it out!!!
i have an error now tho:
Traceback (most recent call last):
File "C:\Users\Classified", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Classified", line 52, in on_ready
client.remove_command("help")
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'remove_command'
client has always worked for this 😄
idk why it doesnt 😄
what am i doing wrong????
0x2b2d31
Discord updated their looks again
!d discord.ext.commands.Bot.remove_command
remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: `name` parameter is now positional-only.
lol this stuff changed from back when
You have to setup logging yourself if you're using that method to start
It's not changed at all
Hey @fringe narwhal! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
i chnaged it:
try:
client.run("TOKEN")
except discord.errors.LoginFailure as e:
print(f"Token is invalid: {e}")
Code:
Main file: https://paste.pythondiscord.com/cemuwuwohu
Commands file: https://paste.pythondiscord.com/weyirixoho
Error: https://paste.pythondiscord.com/rinogadusi
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
cogs?
Yes?
I was already using this damn thing but I want to put commands in each py file
Then use it
bruh
What's the problem
Is that have anything to do with it
like in commands folder I will put all of my commands and then in the main file it will run the commands
cogs it is called
Doesn't mean it is a good way. on_ready can get called multiple times, so you will have multiple loops doing the same thing which is pointless
And?
Ok I will try to provide further assistance on this
point taken, i appreciate the suggestion
yeah nah
i saw the thing you told my friend yesterday
gonna look into it inna sec
just tryna figure out something else rn. also a problem with my help cmd
I already answered it
from discord.ext import commands
from discord import app_commands
class ACog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def command(self, inter):
...
Is it really that hard
you confused me with your answers -_-
trying to change my help help embed to the subclassed send_command_help embed. but i can't figure out how to change my help help embed because there is no command i can change the look of it. just my subclassed and mapped help command code. but that doesn't include my help command.
if u have no idea what that meant, lmk and i'll show u lmfao
Be specific
which one
thanks LMFAO
multipurpose
real
im getting there, its just checking what i needa do for it
but i got friends who can help me lmfao
real
@vital glacier so basically you need to get the function source first and use regex search on it
!e ```py
import re
deco_pat = re.compile(r"@.(?!bot_)has_permissions(.)")
perm_pat = re.compile(r"([a-z_]+)=True")
source = """@commands.command()
@checks.has_permissions(ban_members=True, manage_guild=True)
async def func(...):
...
"""
perm_deco = re.search(deco_pat, source).group()
print(perms := re.findall(perm_pat, perm_deco))```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
['ban_members', 'manage_guild']
and that's for every single cmd?
or can i do it get the src for all the commands and then return the permissions?
That's the only way you can determine the permissions I think
Yeah but do it only for the commands user needs in help ig
What's the point of doing it for all of them
ah, alright
also, any idea how i make this work?
And you can get source via inspect.getsource
trying to change my help help embed to the subclassed send_command_help embed. but i can't figure out how to change my help help embed because there is no command i can change the look of it. just my subclassed and mapped help command code. but that doesn't include my help command.
so basically you just wanna set the contents of help command similar to other commands?
for example you wanna set the usage?
set it to HelpCommand.command_attrs
you can see it here
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#command_attrs
yeah see
that makes 0 sense to me, i read that like 3 times and my brain keeps drawing blanks there
Oooh wait, i see
hmm, which part is confusing?
wait let me try
ok now the next problem, i have my subclassed and mapped help command in my information cog, where would i need to put the attrs' then?
could set it in your init, could do it in your help command constructor
etc
class MyHelp(commands.HelpCommand):
def __init__(self):
attrs = {'aliases': ['helps'], 'help': 'very long docs here'}
super().__init__(command_attrs=attrs)
so here would work?
you could also set it there yea, Help(command_attrs=attrs)
ok let me test it out, if i cant figure it out i'll let u know
oke :3
@golden portal i love u, u are the best
thank you for explaining that properly and helping me properly 🤝
hehe yea, perhaps that command attrs part in the gist need to be shorten since people get confused on it 
either that or they need to make something like: changing the standard on_command_help help embed
something like that could help a lot too
i suppose
connect to db on setup hook or on ready?
setup_hook, dont do it in on_ready, it fires multiple time in the bot's lifecycle
ok thanks
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
await bot.load_extension(f'commands.{filename[:-3]}')```
it's showing red waves and not loading commands
wait i just realized disnake doesn't have setup_hook
what's the equivalent of setup hook in disnake
i dont use disnake sorry
ah that's fine
right so, i got another question right. how do i make it so if i do a command with a parameter, it'll send me the on_command_help or on_group_help embed?
im a bit confuse
elaborate? you mean send_command_help, send_group_help right?
You'd have to make your own async setup then call the .start
At least that's what I would do
^
Or overwrite the start
async def main() -> None:
bot = Rulebot()
await bot.connect_to_db()
await bot.start(os.environ["TOKEN"])
something like this?
class Bot(commands.Bot):
async def start(self, *args, **kwargs):
... # do setup
await super().start(*args, **kwargs)```
i mean, help command already invoke those automatically when you do help command/help group, not sure what you're asking exactly
why is it before calling the base start function
oh yeah
nvm mb
Because code after it does not run
ok wait, let me show u what i mean.
i mean like this
how do i make it do that, when i just type the prefix and command that it'll send me the help command/help group embed
without any params
oh. so if there is a missing required argument, you send the help?
yeah i guess
!d discord.ext.commands.Context.send_help you may use this
await send_help(entity=<bot>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Shows the help command for the specified entity if given. The entity can be a command or a cog.
If no entity is given, then it’ll show help for the entire bot.
If the entity is a string, then it looks up whether it’s a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") or a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command").
Note
Due to the way this function works, instead of returning something similar to [`command_not_found()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.command_not_found "discord.ext.commands.HelpCommand.command_not_found") this returns `None` on bad input or no help command.
and then do this inside your command error, just handle MissingRequiredArgument
huh
ok hold up
could i make it so, on_command_error(self, error: MissingRequiredArgument):
and then await send_help
or how would that work
nop its an event for all errors occurred in text commands
if you see the example, you may just do this in your command error event ```py
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send_help(ctx.command)
Code: ```py
import discord
from discord.ext import commands
from discord import app_commands
class MyCommands(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.commands(name="mycommand", description="This is my command.")
async def my_command(self, interaction):
await interaction.response.send_message("Hello, world!")
def setup(bot):
bot.add_cog(MyCommands(bot))
Error: `Failed to load extension hello.py: Extension 'commands.hello' raised an error: TypeError: 'module' object is not callable`
the decorator would be @app_commands.command(...), its not plural
Failed to load extension hello.py: Extension 'commands.hello' raised an error: TypeError: parameter 'interaction' is missing a type annotation in callback 'MyCommands.__init__.<locals>.my_command' does it need interaction: discord.Interaction?
nope, that happens because you create the slash command inside __init__, which makes it think self as the discord.Interaction, interaction as the argument, just dedent it
How did you get the author title ??
I'm trying to do that but it wouldn't work due to the url. Not sure if I am doing it wrong
also, bot.add_cog and setup should be async
hey helpers
import discord
import asyncio
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
async def send_message():
await client.wait_until_ready() # wait until the bot is ready
channel = client.get_channel(931974039650598925) # replace with the ID of the channel where you want to send the message
while not client.is_closed():
await channel.send('Hello, world!') # replace with the message you want to send
await asyncio.sleep(5) # replace with the number of seconds you want to wait before sending the message again
client.loop.create_task(send_message()) # create a task that sends the message
client.run('your_bot_token') # replace your_bot_token with the token of your Discord bot
i got no error but the code isn't working
Do you have your bot-token placed in: client.run ?
yeah
ok
i got no error but function isn't working
bot.add_cog(MyCommands(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load extension hello.py: Extension 'commands.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression```
Where are you calling send_message?
import discord
from discord.ext import commands
from discord import app_commands
class MyCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="mycommand", description="This is my command.")
async def my_command(self):
await self.response.send_message("Hello, world!")
async def setup(bot):
await bot.add_cog(MyCommands(bot))
error doesnt match code, did you save it? also again, my_command definition need to be dedent so its apart of the class
i didn't get your point
it clearly says in hello.py, line 14, it was never awaited
where are you running the function?
on replit
the error clearly says ```py
bot.add_cog(MyCommands(bot))
not ```py
await bot.add_cog(MyCommands(bot))
``` like your current code is
where are you executing the function
hence, it doesnt match your code
to send automatic messsage in channel i selected of my server
did you save it
have you used functions in python before??
very less i am new in discord.py library
i love coding guys
ok so you should learn about functions first
discord.py is not easy library if you are python beginner
aah would you tell me what should i edit in code i will try to understand why
i know its difficlt
ok thanks
For beginners, I recommend using client commands
yeah i cant seem to figure this one out
what have you tried so far
ok i will learn about it
pretty much all the things that can call a bad/missingrequired argument
It's the easiest than coding for slash commands.
floweryy, how long did it take for you to get the 'active dev?'
for 30 days?
ohh i understood thanks
Hex for discord.Colour.dark_theme?
Yeah of course. Client commands are more for, ' !help '
is the issue that the if statement is not executing?
ok thnx
Any time. Best of luck
Genuinely no idea, i suck with error handlers
error_handler.py line 49
error = getattr(error, 'original', error)```
Ensure you have this line, since some errors are wrapped in CommandInvokeError
why isnt it registering slash cmds
whats your code essentially?
as i said, you need to dedent that function, so its apart of your class
what is the problem?
docs
gib
The thing from EvieePy's gist and then the little part u sent me to see if it would've worked
its fundamental OOP with scope, indentation is one of the first thing you learn
its not really in dpy docs
and how did you write it? i just wanna see it
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
# This prevents any commands with local handlers being handled here in on_command_error.
if hasattr(ctx.command, 'on_error'):
return
# This prevents any cogs with an overwritten cog_command_error being handled here.
cog = ctx.cog
if cog:
if cog._get_overridden_method(cog.cog_command_error) is not None:
return
ignored = (commands.CommandNotFound, )
# Allows us to check for original exceptions raised and sent to CommandInvokeError.
# If nothing is found. We keep the exception passed to on_command_error.
error = getattr(error, 'original', error)
if isinstance(error, commands.MissingRequiredAttachment):
await ctx.send_help(ctx.command)
but i assume i did it wrong anyway cus i suck with error handlers lmfao
MissingRequiredAttachment is for your attachments, it should be MissingRequiredArgument
perhaps you have a local error handler with the command?
wait let me test smth rq
because thats what this line is doing ```py
if hasattr(ctx.command, 'on_error'):
return
nah, i dont have any error handlers as far as im aware
@vital glacier Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
oh shi sec
i had this tho, but i removed it:
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
user = ctx.author
guild = ctx.guild
channel = ctx.channel
timestamp = round(ctx.message.created_at.timestamp())
code = random_string(13)
async with self.bot.database.cursor() as db:
await db.execute('SELECT * FROM errors')
data = await db.fetchall()
if not data:
error_id = 1
else:
error_id = len(data) + 1
await db.execute(
'INSERT INTO errors (id, member, guild, channel, timestamp, code, error) VALUES (?, ?, ?, ?, ?, ?, ?)',
(error_id, user.id, guild.id, channel.id, timestamp, code, str(error)))
await self.bot.database.commit()
await ctx.success(f'An error occurred while invoking command **{ctx.invoked_with}**. Report this using the reference code `{code}` in our [support server]().')
but that's for my traceback command
and even without that, it doesnt work
and i dont have any other error handlers in my files
can you put prints in there to see if its even getting invoked
in this one?

where would i put that print tho
like i said, im real bad with error handling and debugging stuff like this lmfao
or does it not matter
put it at the start of your function
debugging is half the job of being a programmer, it's really useful to learn it
like, basically parts where there could be a potential stop rly, best to be thorough
so under every if statement and under the ignored?
yeah i know but i cant seem to pick it up properly
its easy, just add print statements every so often leaving a few lines to see where the code actually errors, as flowery said
mhm its a rule of thumb really
Only error i'm getting from my ban command tha ti just ran is: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'top_role'
and that was the same one that I had when i was using my traceback error thing
of the ban command?
well, im tryna make it so it sends the help command/group help when i type a command without parameters
so for instance if i type ,ban it will send the ,help ban embed
Ah see that was indeed the problem
can you try removing
error = getattr(error, 'original', error)
It was because member: discord.Member = None
this line
because now it works
oh you set a default value for member
thats great
and prob left it
mhm
🗿 the b alias
Beans
How can i convert a guild id into the guild name?
i assume through the discord api?
or is there a different way?
i guess bot.get_guild/bot.fetch_guild
then just guild.name
oh bet
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Hm xd
what does positional-only mean?
for example:
discord.ext.commands.Bot.remove_command(help)
Prompts this error:
discord.ext.commands.Bot.remove_command(help)
TypeError: BotBase.remove_command() missing 1 required positional argument: 'name'
i've got a prefix with database integration in my bot, but i want to make it so even when i mention the bot, it'll also act as a prefix
hmmmm
oh welp
!d discord.app_commands.AppCommand.mention
maybe 
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
@vital glacier
I had that going at one point before ive been dealing with v2 but its definitely possible
let me test it again
func(value)
# ^^^^^ --- positional argument
func(keyword=value)
# ^^^^^^^^^^^^^ --- keyword argument
Do you know what instances are
Yeah it doesn't work because of my DB i think
Old code of mine, but this is a good example i think:
def get_prefix(client, message):
with open('data.json','r') as f:
data = json.load(f)
try:
return data[str(message.guild.id)]['server_prefix']
except:
return 'z!'
intents = discord.Intents.all()
client = discord.Client(command_prefix=get_prefix, intents=intents)
its the same logic though
What didn't work
Show code
of what do u want the code
the prefix handler in my main file or?
async def prefix(bot, ctx):
async with bot.database.cursor() as cursor:
await cursor.execute('SELECT prefix FROM prefix WHERE guild_id = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
prefix = str(data[0])
if not data:
prefix = ','
return prefix
and I had this
bot = Bot(
intents=discord.Intents.all(),
command_prefix=commands.when_mentioned_or(prefix),
case_insensitive=True,
owner_ids=[566434977093386258, 323118319144271872]
)
but those 2 dont work together
Read the docs, there's an example about this
There is?
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
i showed him that
And
yeah for some reason that doesnt make sense to me
yeah but how would i do that with my db stuff tho
Same way
What else can I say, it's there in the screenshot
You get your prefixes from your db > you call the when_mentioned_or with the prefixes to get a callable > you call the callable
hey , i am creating a cog so inside the init method i am creating a variable self.filter_channels and i have a async func get_set_channels() which returns the list which i would like to set for self.filter_channels . how can i do tat?
i can't seem to figure it out. i've tried so much atp
What did you try? whats happening?
It's either one of the other, or both don't work
just do self.filter_channels = aweait self.get_set_channels()?
Im not sure what you're having trouble with
They are probably in __init__
😑 its not inside async function to await
yea inside init
their db lib is async
yep
Oh, yeah
ah right didnt think of that
hmm
You can make a classmethod that creates an instance of the class, calls that method, and returns that instance
Im not understanding you
You do this
but replace prefixes_for with your own function that gets prefixes from the db
hello guys
this a project that i made a bot of jokes , i was really bored so i did try make some effort on a bot like this can you rate it?
- Use ext.commands or slash commands for your commands
- Read into proper python naming schemes
- Use aiohttp instead of requests (requests is blocking)
the first one i get it
the second one one idk give me example
the 3rd one yes i will use on next bot
Python Enhancement Proposals (PEPs)
thanks
Using requests is causing your bot to block
ah really i didnt know i will read this documentation right now
Help make me a discord bot plz
Any utility command ideas?
async with aiofiles.open('test.txt',mode="a") as f:
text = random.choice(f.readlines())
line = await f.readlines()
for line in f:
if text in line:
line = await line.replace(line,"")
await f.write(line) ``` why doesn't that delete the specified line from the txt file?
$help
MemberJoinMonitoring:
creation_time All commands related to the Creation time trigger.
No Category:
help Shows this message
Type $help command for more info on a command.
You can also type $help category for more info on a category.
hey im tryna customise one of my embeds. Ive noticed when you use ">" to make like a line in the embed or any message tbh. Sometimes it comes with different thicknesses. How can i get the max thickness?
$help print
No command called "print" found.
#bot-commands is probably what you are looking for. For the @unkempt canyon bot, the prefix is ! and for @lament depot .
Hello @velvet compass
hey guys, i made a restart command but it seems to not reload the cogs
i'm planning to during the restart it reload the cogs
it was suppose to repeat the "Sucess line with the other lines that was there
i'm having problems here with this:
start = args.find("[")
end = args.find("]")
find_brackets(start, end, 0, True)
def find_brackets(self, start, end, mod, is_outside):
print("entered")
total = list()
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(mod, end[i])
if(is_outside == False):
break
return total```
cannot access local variable 'find_brackets' where it is not associated with a value
async with aiofiles.open(region+'.txt',mode="w") as f:
text = random.choice(await f.readlines())
#code
lines = await f.readlines()
print(lines)
lines.remove(text)
print(lines)
await f.writelines(lines)``` anyone got idea why this removes all lines from txt instead of the specified line
Why are you opening the file in w then try to read it
And you can't read if the mode isn't in read mode
the "find_brackets_ thing works, but when it goes to the sub-function it doesn'1t works
i'm trying to create a funtion that have two ways of input:
self, args
and
self, start, end, mod, is_outside
Hi all. I put a query in the help system about using python and discord bots to solve an invitation problem I have. Is OK to briefly mention it here as well?
You will need to use **kwargs or smth
wym?
is it possible to make a command that will update a string example key = "test" !updatekey test1 and it makes key = "test1" in the code
As long as u don't store the value in another file or a db, it will only be changed in the cache
ok
!args-kwargs can tell u more about them
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
Kwargs are very useful, allowing u to pass in arbitrary non-positional arguments.
Does anyone know how I can add a description to the help command?
code
oh nvm
to put this into perspective each command is built into one giant class
so Moderation is a class and those commands are sub-classes if that makes sense
isn't that a normal embed up there
for the most part yeah
how can i use attachment with slash command
wdym?
add image with slash commend
do you know what groups are
make an embed
no input image
I recomend you read the docs, I am not a dpy main
use the description= kwarg in @command()
this is coding for one of my more simple commands
import discord
from discord.ext import commands
class Misc(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Embed Cog is ready")
@commands.command()
async def embed(self, ctx):
embed_message = discord.Embed(title="Title of Embed", description="Description of embed", color=discord.Color.green())
embed_message.set_author(name=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)
embed_message.set_thumbnail(url=ctx.guild.icon)
embed_message.set_image(url=ctx.guild.icon)
embed_message.add_field(name="Field name", value="Field Value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)
await ctx.send(embed = embed_message)
async def setup(client):
await client.add_cog(Misc(client))
@commands.command(description='cool description')
Thanks!
ofc

