#discord-bots
1 messages ยท Page 827 of 1
that should do
what is this
oh wait why did you call commands()
oops
also that other for loop for group in groups[0, 4]: is probably causing that error
new error
*predicting the future*
so how to fix this now?
well what do you think those two for loops at the bottom are meant to do?
or a better question, what do you want it to do with the list of groups afterwards
split self.client.commands into groups of four and add a field for each set of four
4 different fields
right, that first part you've done above
yes
not entirely sure how im gonna do that
in other words you want to take each group of commands, join their names together as a string, then add a field with those names
along the lines of this but 4 commands, once it has reached that limit there will be buttons Next and Back to switch between embeds
oh so field per command
buttons i dont want to focus too much on right now
you should have a list of embeds since thats what your paginator will have to traverse through
is there a more efficient way in case later on i have 50+ or so commands, that will be laborious
its neither that complex or computationally expensive
ok
embeds = []
for each group
create new embed
add field for each command in group
add your new embed to list
start paginator with your list of embeds
would the for group in groups or for command in self.client.commands come first?
why do you need the command for loop?
helpEmbed takes in name as command.name and value as command.description
I need to define command somewhere
good point but how would i then make individual fields
loop through each command in the group and call add_field inside
what would the name then be set to
the command's name, of which the command comes from using another for-loop on the group
pain
Why don't you just yoink the paginator example from the repo
for group in groups:
for command in self.client.commands:
#create field
fr
Makes more sense to understand the concept in case I implemet it later
the whole point of getting the list of groups was so you could reference the commands from each group
how would the for loops work then?
table = [[1, 2],
[3, 4]]
for row in table:
for n in row:
print(n) # 1, 2, 3, 4```
for command in group?
yes
which list is the embed added to?
embeds?
ya
line 17 i would need to remove?
mhm you'll be creating the embeds in your second part
so is it 1 embed per command?
1 embed per group
the embed has to be created per group, i.e. not inside the command for-loop
otherwise it would create an embed per command
doing what i said above, and then you can continue to running your paginator with the list of embeds
what your code does right now is creating an embed for one command, then resetting that embed by redefining it and adding the next command
yes
another example of the issue ```py
for i in range(5):
total = 0
total += i
print(total)
prints 4 rather than the sum of 1+2+3+4```
How would I do a timeout based on a slash command?
what timeout
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
How to make a command of on the commands?
Like a help command?
#discord-bots message check this out for more info
yeah delete it so nobody else can read it
xd
my luck
Good thinking ๐ฅบ
):
btw bones are you eivls inferior sibling*
because you two seem very alike
red, skull, undead
ot
is it possible to make my bot send message at specified channel when i interact with button
Yeah
how
Just fetch the channel
is the code must be in main.py or can be at other file
You'll need access to your bot class
So technically it can be in any file as long as you can access the bot class
oh ok :V ty
mhm
await interaction.response.send_message
where to add the fetched channel variable
so, it can be like: (x is the variable)
- await x.interaction.response.send_message
- await interaction.x.response.send_message
- await interaction.response.x.send_message
- await interaction.response.send_message.x
So
logging_channel = bot.fetch_channel(123456789)
await logging_channel.send(...)
interaction.response?
No...
If it makes it easier for you, just think of interaction as a ctx but with less attributes
mhm, ok
If you think about it it's wrong but at a very basic level its a fine comparison
xd k
In discord.py can you force guilds into specific bot shards?
waht
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Learn fundamental concepts and then try to make a bot
pls don't be another one that doesn't know python and tries to make a bot
Discord.py is a (deprecated) library for python which enables Devs to write bots in python
dudes just quit cause of discord bots
why the fuck
it's not that hard
^
discord bots are easy
(if you have at least some experience with python)
โ
python isn't hard
But if you want to make something interesting it can actually get quite complicated at some times
Well compared to other languages, yes
AttributeError: partially initialized module 'bitch' has no attribute 'hello' (most likely due to a circular import)
dis suck
you prolly have two modules importing each othert
thats what a circular import is
wait, so if in my bitch.py file i import main, then in main i import bitch, that's the error all about??
hey, someone here use mongodb?
what to do with [WinError 10054] An existing connection was forcibly closed by the remote host ?
await Guild_Collection.find_one({"_id": message.guild.id}) earlier it worked
lul
Hey @slate swan!
It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
uninstall seems good
an example:
you have your main file, and two other modules
in your modules, A and B, module A imports a function from B, and B imports a function from A. you run the program from main, which imports something from A.
When you run the program, main starts initializing module A because it imports a function from module A. But the first line in module A imports a function from module B. A's initialization is stopped and B starts to be initialized. But B also imports something in A. B stops being ran, and it starts going to A. But, A is already being initialized and this creates circular import
if yes then how to fking fix (cuz in da bitch.py i need func from main and in main i need func from bitch)
don't use from
wut
your import is like
from file import f1, f2?
no
straigt import (file)
import a
import b
import the specific names so your namespace isn't littered with shit you don't use
lul ok
no
ImportError: cannot import name 'hello' from partially initialized module 'bitch' (most likely due to a circular import) (C:\Users\User\Downloads\PycharmProjects\main.py\bitch.py)
duck
imma send code, wait
Hey @small igloo!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
main https://paste.pythondiscord.com/ecafabiyuj.py
dat bitch.py (now change to dropdown.py) https://paste.pythondiscord.com/ewexicikah.py
:bruh:
Lemme alert someone
done?
nah
Too much effort
That from the paste bin link. I'm not even downloading anything
ok
This is not even a question for this channel 
If you can't even install python how u gonna use it 
ok nitro
we won't help if you talk like that
Ah yes another weirdo crying oMg u gUyS wOnT heLp mE
And they talk like shit
Please get out
^
its literally as simple as going to https://www.python.org/, downloading the exe and pressing install
No
Before learning how to install a program learn how to talk to someone 
Feel free to ask whenever
Next next next I read the tos, next install

@hoary cargo this is not acceptable behavior for our community
please read our code of conduct and be more welcoming to beginners
@slate swan do not be rude to other people, especially when asking for help
Okay so
I have some doubts about this whole making bots thing
I have like a few ideas but i cant cause i dont know how to
Whats like a good place to stART?
excuse me but when someone calls me a fat fuck I can't help someone
Oookay ill come later
if you have a problem with someone, ping moderators or contact @novel apex
you were unwelcoming even before that, but either way see above ^
Because their question was off topic like we are forced to help even if it's not about #discord-bots
But whatever
my bad
lol
oof
mm we're going to drop this topic now please
Can you guys just check this out rq?
You don't have to mention me every time you know 
the topic was told to be dropped.
I'll come back when chat is healthy again
good idea.
not our problem, contact staff.
Whatโs the best fork of dpy atm?
imo, disnake
minaberry ghosting chat smh
Is it very different from the original?
the aim is not for punishments to be handed out right? i just want a happy and productive server
Nope
nope
Alr thx ๐
I understand but whats stopping people from calling each others names if there are no consequences?
there are consequences, don't worry
by that i mean to say, we take detailed notes of incidents such as these. so if scenarios repeat themselves, we know not to be lenient
Understandable
i get it :) i'd probably feel the same in your shoes
a verbal warning should be enough imo, it wasnt a huge issue anyways. sometimes disagreements happen. heat gets built at times.
do you guys use IDE debuggers while writing your bots?
is there something special you have to do when trying to debug async code?
No
i don't no
Just run and debug for me in vsc
like putting the breakpoints in specific spots or smth?
I never really used those tbh
Never used a debugger in my life
Break points would be used only if u can't find an error haha
or you just write perfect code 
Totally yr opinion
I've had a few situations where I guess using a debugger would be useful but I never wanted to learn how to use them
I don't usually run in to a lot of errors
@final iron which ide u use
Breakpoint's aren't very helpful imo, at least for me. I much more prefer writing unit tests for things
https://youtu.be/5AYIe-3cD-s i've been meaning to finish this video, but it might be a good intro to debugging that you may find helpful. her focus is using pdb (terminal debugger) and vsc, but the concepts should carry over to whatever tools you use
Presented by:
Nina Zakharenko
Still debugging your code with print? Learn how to level up your ability to troubleshoot complex code situations by using the power of a fully-featured debugger in this talk aimed at all levels of programming ability.
Debuggers allow you to examine your program state, watch as the values of important variables cha...
Assert is also a very amazing tool, but should never be left in production
^ Like a raise as you can also write messages with them
!e ```py
assert 1 == 2, "No it isn't!"
@pliant gulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AssertionError: No it isn't!
!pypi icecream
Never really used it, but seems fun
interesting
Ohh nice
pycharm
๐๏ธ ๐๏ธ
what
hey, i wanted to make a @security.is_owner() whereas it checks if the userid is included in a json folder. This is the function i wrote in security.py, but when i executed it before a @bot.command, the command doesn't seem to be executed even if the user id is included in the json folder. Here's the checking code: (i forked this btw, just wanna understand how it works)
def is_owner():
async def predicate(context: commands.Context) -> bool:
with open("settings.json") as file:
ownerids = json.load(file)
if context.author.id not in ownerids["owner"]:
raise NotOwner
return True
return commands.check(predicate)
``` does anyone know why it doesn't execute the command?
example:
@security.is_owner()
@bot.command
async def on_message(message: disnake.Message):
if message.content == 'cmd':
await message.channel.send('confirmed!')```
Is the owner json-key a list of integers?
yes
{
"owner": [
"389034898666553344",
"847268640508215317"
],
"prefix": [
"e!"
],
"token": "insert token here"
}```
does it raise the NotOwner error?
the bot doesn't respond with anything(it ignored it)
i used a tuple
Because checks are meant for commands not on_message events.
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
ah is that so... i was trying to simplify things but i guess i'll just use if statement lol
make sure you're comparing str(ctx.author.id)
also you have to raise NotOwner() not raise NotOwner
actually
instead of raising an error on the check, you should instead just pass in True/False like the docs say
return authorid in ownerids
(psuedocode but will do)
Raising NotOwner without calling it should work, there is no required argument in the constructor
But wouldn't you just be raising the class object rather than an instance
!e
class MyException(Exception):
pass
raise MyException
@sick birch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | __main__.MyException
!e
class MyException(Exception):
pass
raise MyException()
@sick birch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | __main__.MyException
looks to be the same yeah
Doesn't matter, it still can be caught, so that's all you really need to worry about
!e ```py
try:
raise ValueError
except ValueError:
print("caught")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
caught
Yeah, though I think they should still be returning a boolean rather than raising an error inside of a predicate
They also shouldn't be opening the file everytime
It would be smarter, and more preform-ant to cache the file on startup with only a single open, later appending to it and saving
yep, grabbing from the file and storing it as a list in a bot var perhaps
yeah i'll do that
as the name suggests commands framework methods are meant only for constructing commands ( not events)
oho
Which one of these is a better practice?
def mydecor(func):
def wrapper(*args, **kwargs):
if random.choice([True, False]):
# args[0] must be context of the command
args[0].send("This command won't work because screw you")
return
return func(*args, **kwargs)
return wrapper
def mycheck():
return random.choice([True, False])
# we will decorate commands with @commands.check(mycheck)
# then we will then make a error handler for this
what does the error mean when it says "dict is not callable
you're calling your dict
ok well how would I make it callable?
if "type2" in defender():```
trying to check if a string called type2 is in the defender dict
dont ()
^
but it works if checking if something is in a datastore isn't a datastore a dictionary?
database I mean
only functions/methods need to be called, dict is a datatype and you dont call it
ok then is there an alternate way to check type2 exists in that dictionary
!e ```py
dict_ = {'key1':1,'key2':2}
for i in dict_:
print(i)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | key1
002 | key2
whats type2? ๐ณ
type2 is a string in the dictionary
just remove ()
For functions in my bot that like do a database operation, should I do def of async def?
I assume i should do async def when the code has like await or such?
yea, use async def wherever you need to await stuff, else normal functions work well too
async def for db stuff, at the first place your db should require await else it's blocking
yeah using aiosqlite
async function then
I have a list called embed and it is empty, every time the loop runs through, it should append the variable helpEmbed to the list.
When using print(embeds I found the value being added was [<discord.embeds.Embed object at 0x000001465900E950>]
Is there any other way to add embeds to embeds list?
Maybe its only looping once?
async def check_if_can_ping(member : disnake.Member):
async with bot.db.execute("SELECT obj_id from mod_ping WHERE obj_id = ? AND type = ?", (member.id,'Member',)) as cursor:
single_member = await cursor.fetchone()
async with bot.db.execute("SELECT obj_id from mod_ping WHERE type = ?", ('Role',)) as cursor:
list_of_roles = await cursor.fetchall()
if any(role[0] in ctx.author._roles for role in list_of_roles):
print('failed')
return False
if single_member:
print('failed')
return False
return True
Anyone mind pointing what's wrong? It's returning True even when my role is in the DB
Looks like list of roles is a list of tuples containing role ids, so you are comparing the id to the role object
Wdym?
print list_of_roles
Yeah, I'm pretty sure list_of_roles is at tuple
I did print it and saw yeah
But where's the role object you said?
ctx.author._roles
Doesn't this return a list of the ID's of member roles ?
ID*
my bad i thought it was a list of role objects
I did ctx.author._roles on another command and it printed SnowflakeList('Q', [812365057236533308]) (i only had one rolee)
@bot.command()
async def test(ctx):
async with bot.db.execute("SELECT obj_id from mod_ping WHERE obj_id = ? AND type = ?", (ctx.author.id,'Member',)) as cursor:
single_member = await cursor.fetchone()
async with bot.db.execute("SELECT obj_id from mod_ping WHERE type = ?", ('Role',)) as cursor:
list_of_roles = await cursor.fetchall()
print(list_of_roles)
print(ctx.author._roles)
This prints
[(812365057236533308,)] SnowflakeList('Q', [812365057236533308])
is it because I can't do if role in ctx.author._roles comparing a <class 'disnake.utils.SnowflakeList'> and a <class 'list'>
print("What operation do you want?")
operator = input("Enter either +, -, or *: ")
n1 = float(input("Enter first number: "))
n2 = float(input("Enter second number: "))
if operator=="+":print(n1+n2)
elif operator=="-":print(n1-n2)
elif operator=="*":print(n1*n2)
else :print("error")
!e print([1] in [1,2])
@manic wing :white_check_mark: Your eval job has completed with return code 0.
False
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
!e
print("What operation do you want?")
operator = input("Enter either +, -, or *: ")
n1 = float(input("Enter first number: "))
n2 = float(input("Enter second number: "))
if operator=="+":print(n1+n2)
elif operator=="-":print(n1-n2)
elif operator=="*":print(n1*n2)
else :print("error")
What can I do to check if a user is already using a command
!d discord.ext.commands.max_concurrency i think
@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses.
This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket โ only a set number of people can run the command.
New in version 1.3.
maybe append the user id to a list and check
Wow
bumping this again
Yeah , but anything in default ?
nvm this is command specific
Wdym
You dont even need to write more than 5 lines to check that tbh
Yeah Ik ๐ but still it might be more efficient if there was one
Wait, why u doing _roles? That's internal stuff
Hunter God is here to help
to get the ID's
No need ๐
Or the roles?
Just do [role.id for role in roles]
Don't mess with the internals, they gonna mess with yr bot
I do mess things up 
Cool
if any(role[0] in ctx.author._roles for role in list_of_roles):
this is what I have
so I do
if any(role[0] in [role.id for role in ctx.athor.roles] for role in list_of_roles):
Lol
wait
No like, what do u want to achieve
check if any role Id in the database is equal to any one of a member's role
Explain
Why not use utils.get then
utils.get(member.roles, id=...)
Or just check in role.members after getting the role object
like for a blacklist command, I'm making so you can blacklist a role
Using a bot check?
now I have to see if a member has that role and in the check put it to return False
^^^
so basically I have to do utils.get for the number of records in the DB
there isn't any alternative?
Uhhh?
Well, u can do one thing
On startup, just get every blacklisted role from the db
local_db_role_id = [role1id, roleid]
for role in member.roles:
if role.id in local_db_role_id:
#do stuff```
And whenever u run the blacklist cmd, update the botvar u made on startup
Well that's basically what utils.get also does. It just compares using getattr
is that more efficient than the tils?
Yup
utils*
I just gave an example
Okay cool
so you're saying this is the best way? #discord-bots message
Well, according to me, yes
Since checking on each command invocation means wasting resources
so I store it in a bot variable as a list?
also, what does the whole internals mean for _?
Wym
Internals just mean some private variable, functions and other stuff discord.py has defined, not to be used by people, so as to function properly
oh and what are the bad things about having an eval, when it's set to @commands.is_owner and can you suggest any ways to protect some bad things from happening?
As long as it has that deco, u r fine
Also u should make another deco to make sure the command doesn't take more than x seconds (my bot has set that to 10)
Umm
Since that can make the whole bot lag
Is using the is_owner decorator better or do conditionals work just fine?
The deco is neater but the rest depends on you
I see
wdym?
how do you do that?
Actually I made that for my bot. Lemme get that
def cancel_long_invoke(timeout: int = 10, in_a_cog: bool = True):
def deco(func: Callable[..., Any]):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
if isinstance(args[0], Context) and not in_a_cog:
ctx: Context[Bot] = args[0]
elif in_a_cog:
ctx: Context[Bot] = args[1]
task = ctx.bot.loop.create_task( # type: ignore
wait_for(
fut=func(*args, **kwargs),
timeout=timeout
)
)
try:
return await task
except TimeoutError:
task.cancel()
return await ctx.send(f"Hey there! Sorry, but the command timed out after {timeout} seconds, {ctx.author}") # type: ignore
return wrapper
return deco
I spent 10 mins trying to find that ping
Why?
Wym
I'm thinking to put mine at 3s
Useless as in, the deco haha
Too less tbh
10 seconds was fine for me tbh
Also it's a task, so it won't really block yr bot, as long as u don't use time.sleep or smth
I mean it's only going to be for printing or sending messages
Okay, yr wish haha
how can i make a discord.py code doing โif message in channel, react with โ๐โโ
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if itโs a private message.
so you think it's right
The reason yr bot ain't sending anything is cz it got ratelimited
i know
i need to add a code
so that it stays online all the time
it's works only then
U mean uptimerobot?
when i run it
yeah, i guess
Hmm okay
What is UptimeRobot? Uptime Robot is all about helping you to keep your websites up. It monitors your websites every 5 minutes and alerts you if your sites are down. its 100% free
It will keep your server up until your server ran into problems. For more info click here UptimeRobot setup Once you log into your UptimeRobot account. Go to Dashb...
?
Cool
!resources u will want to checkout these too
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Won't work again. There's a cooldown
oh ok
do you work on hardware too
like you write codes for your robot
i have a hardware kit of lego
lego spike prime
i need more motors
it only has 3
at least 6
and 1 hub
i don't have a team
so
i can only use my set
Correction: freecodecamp
Plus, who makes a normal function while also using requests
Udemy also offers Python courses
I know about that, babe
Okay ยฏ_(ใ)_/ยฏ
also what's in_a_cog for?
oh nvm i got it
I'm not really familiar with that type of deco, do I use it as a command decorator like normal?
also, how do you do this? I tried but it error'd
Just fetch the blacklisted roles on startup
yeah but putting that as a var
^ is what I'm not sure how to do
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
How to change normal discord.py code to disnake
Is that new feature called "Modals" a kind of forms or smth
?
Ok time to try it out ๐
how do I make cooldown for specific server for my discord bot?
e,g,
server 1 cooldown 10
server 2 cooldown 5 second
i am using sql to save data
Just a hacky way to make sure I get the ctx arg only, not the self one
From exchange everything from discord to disnake
this too ^ if you can
??
Ok
Like from discord import Embed changes to from disnake import Embed and so on
and disnake.embed
Okay so have u written the db query to get EVERY role which is blacklisted?
Ok thats it?
yes
disnake.Embed*
But yea, basically
Ye ik captiaps
if your still using dpy you can use slash_util
!pypi slash_util
A small script allowing the use of application commands with discord.py v2.0
async def get_blocked_roles():
await bot.wait_until_ready()
async with bot.db.execute("SELECT obj_id from mod_ping WHERE type = ?", ('Role',)) as cursor:
list_of_roles = await cursor.fetchall()
```this
made by a discord.py helper
Do i need class like class s(disnake.)
Yes
Now just do bot.blacklisted_roles = [roles_tuple[0] for roles_tuple in list_of_roles since cursor.fetchall() returns a list of tuples iirc
..
Yes
Is there anything o i can change all things with same text
Ctrl Shift S
Bro can u give class ill add it
or Ctrl f2
???
In the function i return list_of_roles?
No?
..
async def get_blocked_roles():
await bot.wait_until_ready()
async with bot.db.execute("SELECT obj_id from mod_ping WHERE type = ?", ('Role',)) as cursor:
list_of_roles = await cursor.fetchall()
bot.blacklisted_roles = [roles_tuple[0] for roles_tuple in list_of_roles]
Smh just fix the indent
๐ฅฃ
I'm on mobile, can't help it
The code is theirs. They wrote it themselves, I just added the last line
I'm kidding lol
Just making myself clear
oh wait I put the botvar in the function?
Don't want anyone to hate me for spoonfeeding, already got a bunchful of those haha
yes, why not
Sure
lmao
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
entire bowl?
it doesn't send anything even though I did what it wanted me to do (line 28)
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.
?
In line 28, why not just use lower() and convert msg content to lower too?
!botvar will make everything clear
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!
I know, but that isn't the issue
yes, but this is in a function, not outside
this will work?
yes...
So wherever u got access to the bot instance, u can use bot.blacklisted_roles there
Help
What if it is ๐
???
i did bot.list_of_roles (i initially named the botvar list_of_roles and updated but forgot to change command)
Ah okay
What if that if statement isn't returning True?
so, from the screenshot above, this'll work?
@bot.command()
async def roles(ctx):
await ctx.send(bot.blacklisted_roles)
it raises disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'blacklisted_roles'
ok
should i use the equality operator then
Do one thing... Make it blocking. So that it won't let the bot start until the db operation is complete
Sure, ig
i did bot.wait_until_ready so doesn't it do that?
await get_blocked_roles() in on_ready
ah welp
Lol
isn't that bad
?
to do on_ready
is bot.db just a naming convention or actually has a special meaning
Naming convention
thanks
How to import disnke commands
from disnake.ext import commands
bot=command,bot??
Yea
it's literally the same thing
why is python bot like this
Pls tel where to add class i use cogs
I dont need to add any disnake.client
'''main.py/bot.py'''
import disnake
bot = disnake.ext.commands.Bot()
'''some_cog.py'''
import disnake
class hunter_uwu(disnake.ext.commands.Cog):
def __init__(self):
self.bot = bot
@commands.command()
async def botname(ctx): await ctx.send(self.bot.user.name)
kill me already Yea
U didn't load the cog
do i neeed to add disnake.ext??
They just wanted how to initiate the bot in cogs
ok
Depends on what you import
fine?
i want to use disnake
i use commands.cogs till now
Well okay
i did pip install but disnake is not defined
What even is the purpose of the class
@maiden fable babe, help him
Restart vsc
ok
its using in cogs
Hm
all fine?
ye reload fix it
class Commands(commands.Cog):
"""huh3?."""
def __init__(self , bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
i use this type
I'm just waiting for the time when he changes the cog name from Commands to commands
Nvm just a joke no one really understands
Haha leave it
okkk
Lol
I got a weird humor
fine?
Yea
alright
But be sure to add the setup function
Yea
Okay
What's control f2?
Search (and Replace...?)
very usefull for big code changes
like im shifting from discord to disnake
I use control+h on vsc
disnake_components?
Ctrl Shift F also works
Sorry for the EXTREMELY late reply
But it is two for loops
or discord_components?
None
?
Use neither
i was using buttons
!d disnake.ui.View exists
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
!d disnake.ui.button
disnake.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`disnake.ui.View`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.View "disnake.ui.View"), the [`disnake.ui.Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") being pressed and the [`disnake.MessageInteraction`](https://docs.disnake.dev/en/latest/api.html#disnake.MessageInteraction "disnake.MessageInteraction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
ok
This is meant to append helpEmbed to embeds but the value returned is
Why not send the embed directly?
Pagination
await ctx.send(embed=embed,components=[Button(style=ButtonStyle.URL, label="Invite", url=main.MainAttributes.invitelink)])
``` help button not defined
That's not.... how it works
The syntax is same
ok
^^^
the syntax is same
In disnake and discord, to make buttons smh
I know bruh, I was re iterating what you said, hence "quoted"
You just pinged someone
lol
lmao
again huh?
just dont do it..? and it's called a decorator fyi
someones same is uii
kkk
jesus fucking christ
lol
Ah okay. My bad
don't ping me
np
ok
that's enough
huh?
Oops, me being slow ;-;
ok (0ffs)
How do you append the name of the embed and not the type?
blood red error (no problem)
Traceback?
Why does this unicode not work when I define buttons?
@maiden fable what do you think of this for blacklist a role?
just get the role objects from the DB with guild.get_role and use something like the@comands.has_role deco
no its in code lol
i just put a = sign i fixed it
changed all discord to disnake
Don't...
Use a bot check, or use the on_message event (preferred)
on message
bot check?
!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.
Wait, u making it so that bot doesn't respond to people with blacklisted roles, right?
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 487, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 418, in _load_from_module_spec
del sys.modules[key]
KeyError: 'utility'
PS C:\Users\hp\Desk
Even on mention
Your load extension
yeah, just for one command only
Oh hmm... Then sure, ig
?
Totally yr wish ยฏ_(ใ)_/ยฏ
i use ```py
import main
i just want to use the most convenient/efficient way lol
Huh? Probably missing parntheses or smth idk
Uh, shouldnt you do make an info file and put everything there just to keep clean
okk...
nvmd i put it in the file instead
You can even put your bot token and api keys there
After appending the helpEmbed to embeds, how could I use pagination to run through all the embeds?
disnake.ext.commands.errors.ExtensionFailed: Extension 'utility' raised an error: ClientException: Cog named 'Commands' already loaded
Btw it will be
main.MainAttributes().invitelink
Dont name your file Commands
or class?
Yes
my class named Commands
Yes change that
Why tho
ok lemee change it to Commands1
๐
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
in discord.py it works well but in disnake it dont work
It will work
my all cogs class name is same
I had that same error once, fixed it by changeing the class name from Commands
Dude
Lmao there u go
๐
I'm gonna go cry
How would I use pagination to go through embeds?
Instead just come back here and help him fix it
ik whats my problem
class utility
Then why are you trolling
How would you use pagination to go through embeds?
Apply brain
I can't
help how to put style???
@disnake.ui.buttonstyle(ButtonStyle.URL, label="Invite", url=invitelink)
wait wtf
disnake.ut.buttonstyle tf?
lol
i got it
!d disnake.ButtonStyle.link exists
Represents a link button.
hello is there any more characters in \u200b out?
Add a style parameter
Q
@disnake.ui.Button(style=disnake.ButtonStyle.hunter_uwu)
disnake.ButtonStyle.link*
Lol
.
!d disnake.Button
class disnake.Button```
Represents a button from the Discord Bot UI Kit.
This inherits from [`Component`](https://docs.disnake.dev/en/latest/api.html#disnake.Component "disnake.Component").
Note
The user constructible and usable type to create a button is [`disnake.ui.Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") not this one.
New in version 2.0.
disnake.ext.commands.errors.ExtensionFailed: Extension 'others' raised an error: TypeError: button() got an unexpected keyword argument 'url'
no much errors ahhh
somone help me i am beginder
hec?
U need to use the add_item method
Yes?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!d disnake.ui.View.add_item
add_item(item)```
Adds an item to the view.
what's the best way to get each element of a list which contains all integers?
is there anyone who can make me a discord moderation bot
but why.
Why tho
loop?
idk how to do anything
!resources can help u get started
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
there is nothing there
There is
docs i need u
Use dyno, carl, mee6, probot
Nah
you mean like [for i...] or `
for i in something:
#code```?
Anyways, I want to get it in one line
sluppy also
why mee6 though
It's already a list
yes use sluppy
Never heard of that
So I'm thinking I have some logic issues with this commandpy @commands.command(description = "Get this bots PoC's.", usage = "poc", hidden = False) async def poc(self, ctx): key_perms = ["manage_guild", "manage_messages",] embed = discord.Embed(title = f"Point of Contact(s) for {self.bot.user.name}", colour = self.bot.primary_colour) for guild in self.bot.guilds: admins=[] mods=[] owner="" pocs=[] for member in guild.members: if member is guild.owner: owner = guild.owner elif "administrator" in member.guild_permissions: admins.append(member) elif key_perms in member.guild_permissions: mods.append(member) else: if member.id == self.bot.config.admins: member = "<@{member}>" pocs.append(member) #admins_str=', '.join(admins) #mods_str=', '.join(mods) embed.add_field(name = guild.name, value = f"PoC(s): {', '.join(pocs)}\nOwner: {owner}\nAdmin(s): {', '.join(admins)}\nMod(s): {', '.join(mods)}") await ctx.reply(embed=embed)bc the screenshot is the current output but the pocs, admins and mods are all blank when there should defiantly be users next to them for two of the guilds
my bot
Let's order a customized MEE6 just like in the cod server
Cuz why not uh
use vortex
Uhhh who cares
my customers ๐
because free mee6 absolutely sucks lol
also my bot provide custom commands for special server ๐ must have 1k + members
okay well basically i want to query my DB and get the list of blacklisted role ID's and do @commands.has_any_role() on it but it has to be in ints, not a list
no idea about that
oh yes with their
VX release, the current V8 is showing its age
also if ur server has 100k + members i can also create whole new bot for u for free! ๐
*list_of_ids
Haha idk much about that
i hate buttons in disnake
Then u hate the same in discord.py
im not failed i just find 10 different types of syntax that dont work
finds who tell all are same
Who would risk their 100k members server for a bot that can have potential malware
Nah thanks disnake exists
๐ฅฒ
- open source
but u want to pay for that (not against rule no help nothing stop spamming rule)
view = discord.ui.View()
item = discord.ui.Button(style=discord.ButtonStyle.blurple, label="Click Me", url="https://google.com")
view.add_item(item=item)
await ctx.send("This message has a button!", view=view)
cringe
find something
wdym by cringe i shifted to it!!!?!?!?
Why does this happen?
tryes to react
I only want 1 embed
send 1 embed simple
take the paginator out of the for loop?
edit embed u mean
no as in it sends 2 embeds and edits the 2nd not sure why
sorry cant help
ok
if ur server has 100k + members i can also create whole new bot for u for free!
how do I pass a list that I get from a async funtion to has_any_role?
ok
copy cat ๐ฑ
Does paginator autogenerate the number of pages based on how many commands?
What's so bad in it lol
You'd better add a custom check
Hi
I had a question
So For example
!say hello there, hi there <user>
How do I make the first entire argument send to me
Followed by the second to user
Thos is just example ik doing myself weird
is "he there <user>" respond of bot?
f
No
AttributeError: 'Member' object has no attribute 'avatar_url'
``` hec?
ohhh
ash how??
@command
async def hi(ctx, member: discord.Member): await ctx.send(f"Hi there {member.mention}")```
Member.display_avatar.url
member.avatar.url
.url ok
No?
disnake has diffferent
Yes?
Doesn't help 1 bit smh
!d discord.Member.display_avatar
property display_avatar: discord.asset.Asset```
Returns the memberโs display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
You crying in a corner, Ash? ๐
Should work
disnake
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
embed = disnake.Embed(description=f"**Channel Created : {channel.mention}**", value="** **",color=aqua,timestamp=datetime.utcnow())
embed.set_author(name=f"{channel.guild}", icon_url=f"{channel.guild.icon_url}")
await channelslogs.send(embed=embed)
channelslogs isn't defined
channelslogs = await self.bot.fetch_channel(927193880116473906)
Wherw in the world are you getting the value parameter from?
value/
What
yes what value
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
What kind of value param?
ok value of embed
invisble
Oh god
Lmao
๐ฅฒ
Imma just go
c'mere, have a hug
๐ค
does someone know how I fix this error? I accidentally installed NextCord (which Im not using) and deleted it later bcz it gaves me many errors and I didnt use it but now all my import that is related to Discord.py just gives errors. Just like this one on the screenshot
Leaving me for the Brainfuck
huh
Mine is already fucked
what happen??
Because discord is not installed
but when I look at the packages I can see Discord and Discord.py there
Re-open cmd
Most probably wrong Python version
ok
Open cmd and run python -V
ok
Tell the output
Not talking to u
its python 2.0
My dear, the Embed class has no parameter as value
Re-install discord?
ok so?
embed = disnake.Embed(description=f"Channel Created : {channel.mention}", value="** **",color=aqua,timestamp=datetime.utcnow())
gives error
Ik...
so?
ok removing
@slate swan why u leave me alone
removed
cmon stop trolling me
let me pee at least
you cant have the value parameter in the Embed initiator class
!d disnake.Embed
class disnake.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.Empty "disnake.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
need lot of edit
@nimble plume even disnake does not have a value parameter in the initiator function of the Embed class
discord.py has
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
what kind of explanation do you want?
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
value
I dont know what you expected me to do, but I'm leaving, help yourself
here u go
sorry
do you know that add_field is a method?
if you're gonna be like that then stop asking for help
sorry im wrong
nvm, help yourself, you're not even willing to listen
hi gus
Hi Dyno
