#discord-bots
1 messages · Page 718 of 1
what are you trying to do right now? Like what are your intentions?
gonna need a screenshot containing more code mate
So after someone used a command i have it set up so i can see who used it fr it would print the function used but i can’t define ctx so it just gives me a error
Are you using this on_command_completion ?
Hey do any of you guys have an idea of how to make a bot (maybe with webhooks) of checking when a Minecraft Server is online?
No, it would print it after the bot has sent ctx.send showed in this screenshot
I wouldnt recommend doing that.
Oh
Especially since you'd have to do that for every command
Make use of the on_command_completion event
Thats why im making a function do it would be print(used) and it would do it automatically
Im fairly new to python so im not 100% sure
ex:
@bot.listen("on_command_completion")
async def command_listener(ctx: commands.Context):
print(f"{ctx.author} used {ctx.command.name}")
in your case it would be
@client.listen()
Ok tysm
how do i make it send all in one
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
await ctx.send(", ".join(responses))
why doesnt this command work?
Caeden 😄
it was working great a few dyas ago
Wdym it doesn’t work
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
haha thanks! but anyways what i mean by "it doenst work" is i do my prefix so ?topic it doesnt say anything (no errors in term either)
so i have no clue what to do or how to help because it just doesnt do anything
is that all of your code for your command in your ss
yes it is
you're not actually sending the embed
You only build an embed
you didnt actually send it
tyler is right
cease
thats what im confused about
because it was working before
i dont remember if i changed the code
You probably accidentally removed it or something
thank you to whichever moderator that was 👌
so how would i fix this
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Literally just await ctx.send(embed=embed)
No
await should be after you've made the embed
You'd get an UnboundLocalError or something
I think i got it thanks gonna test
Why did you send it before it was even declared
Code is read from top to bottom
For the computer
Been busy with the logger today colors :3
By putting it above it won’t be declared
♥️
❤️🔥
!e
print(a)
a = 6
@velvet tinsel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'a' is not defined
NameError
Code is read from top to bottom.
This is like starting at the end of a book and reading backwards.
We're in a method right now
It will throw UnboundLocalError
which is a subclass of NameError. So meh ig
hey guys
whats the code for ask for input
i forgot it and i think there are many different, so need the one for discord.py
thanks!
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Hello! I do not know if this is the right place to ask this, if it is not, sorry. I'm using the api discord.py, and I want to make an anti bots, but I don't know how to make the variable antibots = True be different on each server. What happens to me is that if a user activates or deactivates the anti bots, it does it for all servers and I don't want that. Can anybody help me?
pls help
What are anti bots?
when a bot join, if anti bots is True, the bot will br banned
object of type 'Command' has no len()
how do i fix this stupid error
Oh so with another bot using on_member_join check if bot if bots join is disabled kick the bot?
Want to get the amount of commands in your bot?
If it is enable yes, but thats not the problem
no but its showing that and onmly for that command
What is?
Some code and what you expect please.
Hello again! I am building a football bot and in discord it says tampa bay and green bay both won. What did I do wrong? Thanks!
@client.command(name='football')
async def football(ctx):
coinflip = randint(1,2)
if coinflip : 1
await ctx.send('Tampa Bay won the coin toss! They elect to defer.')
if coinflip : 2
await ctx.send('Green Bay won the coin toss! They elect to defer.')```
What happens to me is that if a user activates or deactivates the anti bots, it does it for all servers and I don't want that. @Pandabweer#7576
Well the syntax isn't quite right
?
its like a global var,
if coinflip == 1:
...
else:
...
replace the colons with ==
thanks
use the comparity operator
what?
Ohh, well you have to pass the current guild id using a database.
ok tyvm
wait
Yes?
it is on 20 servers
Yeah ofc i'm coding myself aswell.
I know so i suggest using a database if you want to do it per-guild.
coding is actually really cool once you get very far along
so fun lol
@slate swan Yep, been coding a better logging system in my own bot.
thats exactly what i need, but how can i do it?
Well using a database..
what would be the best for like colors, colorama?
!pypi coloredlogs i use this
Looks pretty neat and i can shorten error tracebacks so my eyes don't die on large errors.
@cloud dawn I know how to make the database, but I don't know how to do the rest, could you give me a short example?
What do you mean by "the rest" i need specific issues.
Getting items from the database? If statement? Adding to the database?
ok, I can do the writing of the server ids in the database, but how do I do the rest? I mean, the variable is per server
Could you show me your database?
what sort of database are you talking about?
I'm suspecting a .py file now 😅
a txt file ._. , it works for me with a blacklist
With a dictionary
Ah that's not a database.
A Python dictionary would be better than that tbh
@cloud dawn but is useful?
Yeah it's a bit more complicated than that 
@slate swan Have you used JSON files before?
@fluid spindle with node .js
It's a public bot though once he gets to 50 or 100 servers it could already die.
only for load the prefix and token
json is as fast as an txt file lol
Well you got a small bot rn so i recommend sqllite a file based sql
So, what can i do and how?
!pypi aiosqlite
Pretty sure sqllite can handle 20k guilds or so.
Is there an article or something that I can see?
The pypi link has docs links and more.
SQL is a bit boring but it's almost a must in a bot.
shit, so now I gotta migrate from JSON to sql
Fact ytbers and tutorial site even explain things with json makes me sad 🙁
json is not really meant to get updated or get really large in terms of size.
yeah, I felt that when I once downloaded a JSON of all cities in the world with some other data
Makes sense
If you are more interested alec unleashed his anger onto JSON files -> https://discordapp.com/channels/267624335836053506/343944376055103488/822824159091884042
fair enough
Also, one more problem I faced with JSON is that it can't store Discord objects like ctx...
Hold up
Why would you ever want to store ctx?
Not ctx exactly, but ctx.author.mention or something like that, can't remember exactly what it was
Well you can store objects but that method is pretty cursed
@bot.command()
async def suggestie(ctx, bug=None):
await ctx.send("Wat is uw suggestie? Reageer binnen 120 seconde met uw bug!")
try:
message = bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=120.0)
except asyncio.TimeoutError:
await ctx.send("Niet optijd gereageerd, prompt gecancelled.")
else:
bug = message
await ctx.send("Bedankt voor het melden, hij wordt naar het kanaal gestuurd!")```
I immediatly get the last await ctx.send, instead of waiting for a message. How to fix this?
Well wait_for is a coro
I have used It before In commands tho, so dont onderstand why not now.
And don't code in german lol
Dutch
Guys, how can I connect a Discord Bot with Roblox API, in the way that Bot connects when the product from the game has been purchased and adds the value of that product to the user's variable.
So basically, user buys for example product worth 10 robuxs, and then the bot adds 10 to his variable.
If possible, with -30%.
Can anybody help me, please?
Well what do you got so far?
I knew that, but you still have to await it hehe
Not sure where to start bud.
Why not have the suggestion inside the command? Like /suggest a bug or smth
Can you code a Discord bot?
So, could you help please? @cloud dawn
Yeah but never uhh, did something related to Roblox API.
I can but i'm not going to make it for you. I can help with problems and errors not entire projects.
Have you tried to get a response from the roblox API?
Thats what my boss requested, that makes more sense but yeh
Nope.
What i do sometimes is seperate the 2 API's if i'm dealing with a difficult API then merge them if they both work.
kan you niet suggest something anders
not that this bug argument only takes one word, not a sentence
if you weet what I bedoel
ah i also get wat you bedoel
How would i format the str so it works? gbkickdist is an int. Thanks!
embed.add_field(name='Hari Kawn kicks ', str(gbkickdist), ' yards to end zone' )```
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
niiice i just update my logging system to not be boring
!pypi discordheximals
returns hexcode by name for discord.py and its forks
nice

💪
So I'm tryna make it so I can copy the ID of all members in a discord server but when I do it my console blows up with this error:
I was following this tutorial https://www.youtube.com/watch?v=jaEa-6fgyb8&t=399s... can someone help me fix it?
So I'm tryna make it so I can copy the ID of all members in a discord server but when I do it my console blows up with this error:
Does anyone know how to get a banner url in a command?
#help-chestnut if have understanding of discord and database
Well guild is not in the dict
in the dict?
Of..? Member? Guild?
Member
!d disnake.Member.banner
property banner```
Equivalent to [`User.banner`](https://docs.disnake.dev/en/latest/api.html#disnake.User.banner "disnake.User.banner")
class disnake.Asset```
Represents a CDN asset on Discord.
str(x) Returns the URL of the CDN asset.
len(x) Returns the length of the CDN asset’s URL.
x == y Checks if the asset is equal to another asset.
x != y Checks if the asset is not equal to another asset.
hash(x) Returns the hash of the asset.
Do i need to from discord.py import disnake?
no
Ok
Oh i still had the disnake docs on
so any idea how i can fix it
Well the guild is not in the dict.
So i recommend adding it.
wdym by the dict
how do I do that
That doesnt mention a banner url
Atleast i cant find one
Could you show what you are doing?
Im looking on the website linked in the title of the 2 embeds
Should be something like member.banner.url
Ok
Are you using discord.py v2?
I think so
Oh
?
?
Thats me still having disnake docs on
ah
You would use banner_url
okay, so they are using discord.py.
ok
I thorght i was
but you'd need discord.py 2.0
How do i update bc im on repl
i think you have to install it via github?
someone correct me if im wrong.
This part of the app im on now is like pip install i just type in the name of the pip and it downloads for me
yeah but im pretty sure you cant usepip install... --upgrade for 2.0
i think you need to install it via github
but im not sure, not even i use discord.py 2.0.
You can use pip
alright, my apologies, i was unsure.
pip install git+https://github.com/Rapptz/discord.py for discord.py 2.0
why?
btw ill do the pr maybe in 4 hours
coming back from america
ic
went there for holiday
i don’t like america
🕴️
it was fun

im too lazy to try it well . imma just ask yall, so i wonder if i put 8ball as an aliases like alaises["8ball"] is it going to work? cuz on async def 8ball is not going to work doe
Yes that will work
ty
You can also just specify the name of the command to be 8ball
What you wrote wont work exactly though
I will just join in on this so he does some effort when it's wrong.
I am aware that what he did is not correct
name arg/kwarg. I haven't completely figured out the difference
@cloud dawn hi! arevyou there?
ye
!arg-kwarg
*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
yes
yep
you didn't know that?
Now you made him insecure, he won't ask these questions anymore.
||me neither||
I got a book
Does that count as a class 💀
@final iron
def function(*arg):
print(arg)
function("arg")
thats a unknown amount of positional argument as it gets called for its position
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
hope it helps
Actually a very good explanation. I now understand why dpy uses them
nice btw i hope you ask these types of basic questions more because they dont make you look stupid but they make more questions
We would use .get though for those really potential kwargs.
Yes i made okimii insecure.
😂
@final iron btw theirs something know as a optional arg which can be a kwarh or an arg
example
def function(optionalarg = None):
print("works")
its a argument which is positional but has a default value of none which can be a kwarg or a positional argument with a default value
and
*args
gets stored as a tuple while
**kwargs
get stored as a dict
!d disnake.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild.ban "disnake.Guild.ban").
this has 2 kwargs as *, makes all the arguments after kwargs
Yeah, I used optional arguments before I quit making my bot
okay great im just making sure you know this
Can you go more in depth about what the * signifies in the docs?
dont have much about docs but i do have examples
Nothing this explains it all.
- is a build-in python "function"
correct
See it like a special character.
Interesting
def function(positionalarg,*,kwarg,another_kwarg)
so (required_arg, *, required_keyword_arg, required_keyword_arg)
Defining an arg or kwarg in the function makes them optional.
yeah
Thanks for the explanation
anytime dont be afraid to ask these types of questions we all have these types of questions
not insecure hm
no need to be ashamed as it just makes more confusion 
no im just making him feel free to ask these questions as their nothing wrong about them
do we all? :D
damn im a dickhead
we all know that
Honestly I might pick my bot up again
who says i have these types of questions
you're*
^
idk maybe you do 
no one is to smart
too*
im about to hop on a plane so i cant piss you off for the next half a day 🥲
did i ask this before? what timezone are you @slate swan
give ma an 1 amd 30 minutes
good
im expecting a lot from this pull
100+ commands
20+ new cogs
are you bored🕴️
1000+ typehints
no, hes factual
🕴️
well actually hes pandabweer :D
well actually,hes pandabweer.*
he's*
x.x
😂
I'm bored don't mind me.
we know
It's funnier in my language trust me.
how is it
Well it's pretty satisfying to scream out.
how do you guys pronounce my name?
ic
in english its pronounced
oki me
Oki-miiiiiiiiiiiiiiiiiiiiiiiiiiii
Oh-key-me
@manic wing i hope you get a seat thats not by a window 
yes like that
im getting an exit seat
plenty of leg room
me hopingly waiting till airplane mode starts
i hope the door opens mid flight
about an hour till the flight
on my laptop rn
an hour till we board*
pip install discord.py
i did
😠
requirment already satified
i hope your flight gets delayed
no more time for you to cry
You can't code without internet?

weak
@manic wing
multiple python versions i presume
Is it the right interpreter.
should branch out to new things afterwards
I've been doing API stuff all my career basically, now I'm branching out and making my own lang
what do you mean?
Idk, just coming from someone doing API related stuff during their entire programming career, branching out is def a breath of fresh air
ic
to what?
discordheximal
sure make a pr with all the new colors or idk
only 800? bah!
i can add 258 colors so it can have 1k colors 🤔
add 3k
but idk i have to make a dpy wrapper
dpy wrapper?
my bad i ment discord api wrapper
i have people hating my long read me and you want me to add more colors🕴️
uh not to be rude but i think thats a bit hard for you
thats the point
im trying hard stuff isnt that how you learn new stuff?
not really, seeing as you will literally get nowhere
then what do you recommend?
but you can try ig - i never tried because its pointless. even if i succeed it doesnt get me anything
learn c++
already??????
?
thats true
im scared tho😰
ok well i’m boarding now soooo you have 11 hours to make me a pr ;) i expect only the highest of quality
good pr = contributer
bet
Caedon you're expecting too much. Have you seen Okimii's and Download's PyBot.
are you stalking me🕴️
my commands are great tho
They would be better if you actually utilized cogs
i wish i did but my os doesnt find any cogs
I don’t have a single command in my bots runner file.
i do know cogs
well its not really my problem as my os doesnt find any cogs
even with the file path
try os.listdir(".") and see what it returns
cant rn lol
I decided to finally pick up my discord bot again. I want to use a real db instead of json. What would yall recommend?
for lightweight database use sqlite3, for async stored database use postgresql
and if you want to use sqlite3 just use aiosqlite
!pypi aiosqlite
Which one would be easier?
I'm not looking for anything powerful
Just something with a small learning curve
i mean aiosqlite iirc stores it in a file while pg uses a server
yea aiosqlite, sqlite3 uses local db in your computer
I'll probably use aiosqlite then. I'm planning on hosting on a raspberry pi
yeah
cogs r overrated smh
If I wanted to make the change from dpy to disnake what are the changes I found have to make?
Aside from refactoring discord to disnake
you can do pip install disnake[discord]
What would be the difference between that and installing it without the extra
that will install disnake by the name of "discord"
I'm fine using pycharm's find and replace
I also intend to publish it on Github so I would want simplicity and readability
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.
check their
So aside from refactoring discord to disnake is there anything else I would have to do?
I’m trying to make my command so you can mention other members but it’s giving me this error
im tryna make one of those to the pp size!!!
oh mb for ping sorry 😭
Eh?
i suck at coding but maybe this if member == None:
member = ctx.author
Ah
Nope
ill try to research if i get it working il lyk
Alr
Python allows for string multiplication
No need to hard code a list
Eh
Can you help with the error?
I can't read it. Formatting on mobile is fucked
!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.
Put the code in to here and specify which line is giving the error
It says line 69 and it’s an invalid syntax
@commands.command(help="Checks the size of your pp")
@commands.cooldown(1, 5, commands.BucketType.user)
async def pp(self, ctx, member = discord.Member = None):
if member is None:
member = ctx.author
pp = ['8D', '8=D', '8==D', '8===D', '8====D', '8=====D', '8======D', '8=======D', '8========D', '8=========D', '8==========D', '8===========D', '8============D', '8=============D']
embed = discord.Embed(
title=f"{member} pp:",
description=f"{random.choice(pp)}",
color=ctx.author.color
)
await ctx.send(embed=embed)```
Wait 💀
Cuz I already made it and it too lazy to change anything and I fixed it
I'm assuming you meant to typehint member to discord.Member and not assign it
if you want to play it sexy
if member is None:
member = ctx.author```
is basically
```py
member = member or ctx.author```
Yea that too
It's fine haha
i have a small discord bot and im trying to make a inventory system
Okay?
the bot can add items to the json file but it cant add multiple things at one time
A bit of code would be better ngl
i just wanted to explain that first
i think some things are missing in the for loop
Rip i dont understand anything. Still sleepy 
ok
I guess wait for someone else to come and they will explain, sorry
you basically copy pasted someone's stinky code, I've seen the function open_account etc already too much
im using repit and i had to edit the code/pafy package to get it to work on visual studio, is there a way to install custom packages/your own to repit? i wanna use repit to try to web server host it there
correct, you're just defining and intializing a variable in that loop and not doing anything with it
you want to make your project portable?
kinda, just tryna get this one changed package over to repl or whatever its called
unless theres a better method of free bot hosting..?
you can generate a requirements.txt and just install it on the vps
replit sucks, for sure
free vps's mostly do or only have a limited trial
like AWS or GCP
AWS lambda sounded good but someone told me it only lasts 15 minutes, Im tryna get one with 24 or maybe 12 hour uptime if possible
AWS EC2 has a free trial for a year.
you just don't have to go over the limits or will be charged automatically
not an issue if you know what you're doing
how would i go about making a command to restart my bot from discord
please tell me how to fix
i dont think that can be done, considering the fact that the bot wont run commands when it goes offline
im not sure if you can log into your bot if the connection has been closed
via a command
once your bot is off commands will no longer be detected
no like its already been running
lmao, I can't "fix" your code if you don't even know what you're trying in that loop
so the problem would be i guess that maby the command wouldnt have purpose since its telling the bot to go offline
so prolly wouldnt come back online
only thing i could think of
but
way above my knowledge
hence why i came here
im trying to get the loop to add values to the persons inventory
well, why would you want to restart your bot?
use a db for those kinds of things, you obviously followed a stinky yt tutorial which told you to use json
json isn't a db
no, json is just simple enough for me to understand
like if its having latency etc
json isn't a db, you shouldn't implement shit because it's just "the easiest way"
and as i said its a small bot
you can make an eval command which executes something in your terminal
https://stackoverflow.com/a/67846342
the size doesn't matter ||in this case||
thanks
know what it does, please
don't ever blindly copy paste
also make sure the command can only be executed by you, not a random stinky boy
yeah
im looking in to everything now understanding the code
i appreciate the help
Your if statements shold be inside the for loop ig
If you're not in a cog then you don't have to add the self param
!d discord.ext.commands.Context.author.color
No documentation found for the requested symbol.
not a thing
That too
member portion is kinda iffy too
thought it was great
where it says None
yeah
how can i print a random amount of something kinda burnout and dont want to think😔
wait i got it
!e
import random
print("lol" * random.randint(101))
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: Random.randint() missing 1 required positional argument: 'b'
should be random.randint(1, 101)
why
cant you still not do that
!e
import random
print("lol" * random.randint(1, 101))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
lollollollollollollollollollollollollollollollollollollollollollollollollollol
why my buy command not working?
Can we have some code?
ok
async def update_bank(user,change = 0, mode="wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("mainbank.json", "w") as f:
json.dump(users,f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return user
async def buy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in shopitems:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_bank_data()
bal = await update_bank(user)
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"] = [obj]
with open("mainbank.json","w") as f:
json.dump(users,f)
await update_bank(user,cost*-1,"wallet")
return [True,"Worked"]
@client.command()
async def buy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That Object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy {amount} {item}")
return
else:
await ctx.send(f"You just bought {amount} {item}")
@final iron
what does the class method decorator do?
before that you should know what's the difference between an instance and a class:
class Foo:
pass
Foo # this is a class
Foo() # this is a method
a class method means that the function can be called from a class, normal method only can be called from an instance
im not quite sure still
ill google it lol
thx
copying code off youtube isnt the way to go.
Difference between classmethod and instance method (normal method):
A class method means that the function decorated by it can be called from both, class or instance. Normal method only can be called from an instance.
Example
class Foo:
def normal_method(self):
pass
@classmethod
def class_method(cls):
pass
# instance
Foo().normal_method() # works fine
Foo().class_method() # also works fine
# class
Foo.normal_method() # raises TypeError
Foo.class_method() # works fine
here, you can see the differences:
Class Method
- Takes
clsas the first parameter.clsbehaviour is similar to self but the only difference isclsis the object ofFoonot an instance ofFoo. - Works on both, class and instance
Instance Method
- Takes
selfas the first parameter.selfis the instance ofFoo - Works only on instance, not class
Foo.normal_method() doesn't raise attribute error
Also thinking of @classmethods as sort of from_* functions helps me understand it better, and many times they are used as that. For example, in discord.py, there are functions like from_rgb(), from_hsv(), that are classmethods
They take one form of input and basically return a full class rather than ints or strings or whatever like normal functions
Not sure if that helps but it helps me understand it
They can return anything
Well yes but I think having it not return an instance kind of breaks the whole point
After all it is a classmethod
What error are you getting
Let me check something one moment
No problem
I'm pretty sure payload.emoji.name doesn't return the actual emoji
For that you should probably str() it as long as it's a default discord emoji
what about when its not default
it does
Then you can employ is_custom_emoji()
Cause adding the reaction adds the role
And use the ID/name
Oh it adds but won't remove the role?
I've tried that, and it wouldn't add the roles anymore
try unicode?
Yes, it adds the roles, but just doesn't remove them
Most likely the if statement isn't passing
Actually i don't see why else it wouldn't
Trying doing str() on it
Just humour me
On the remove?
Yes
Can I see the code after you used str on it?
emoji = str(payload.emoji)?
That should be right
yep
payload.emoji is a discord.PartialEmoji
so
here's the weird part
This passes fine in the onrawreactionadd
but it fails in the remove, after changing the payload.emoji.name to str(payload.emoji)
What's the code for the add
Oh my
I think you should have a dict that maps emojis to their ID and do it that way but that's beside the point
adding works fine
It just seems to be the removing that breaks on something
Could it be the fact that I'm using 2 different listeners?
If it's a listener shouldn't be an issue
I'm going to upload the code for you to look at fully
If it's an event then yes
Anywhere specific I upload?
Hastebin I think the name is?
It's aight i can see it
Eh i can see it who cares haha
It's weird because from your error payload.member is returning NoneType
Ah you know what
"Only available if event_type is REACTION_ADD and the reaction is inside a guild."
So you don't get the member when they remove the reaction
Let's see
Alright
You should it's typehinted to Union[Member, User]
wait....
Other one was typehinted to Optional[Member]
Don't think like the docs said on_raw_reaction_remove doesn't provide you with the member
Yeah you were getting an error
I'm going to see if I make the reactions the bots reactions, it'll work, if not, I'm out of ideas.
plus on_reaction_remove takes 3 args, I only have 2 provided, so I have to stick with on_raw_reaction_remove
I don't think you get the difference between the 2
It's not just about the args
on_reaction_remove only works for messages that are in the cache, and provides a better input to you such as the user and the reaction objects in itself
on_raw_reaction_remove works regardless of the internal message cache, so it will still pick up reactions from messages a long time ago that are no longer in the cache. It provides a more raw format and expects you to get any useful data out of it
bro, so when it's the bots reactions on the embed, the roles don't add to the member.
but when they're mine, it works on adding roles
and let me click the doc link
TypeError yeah
So how do we make this so on_raw_reaction_remove removes the roles from the member
user_id gives you the ID of the user (not member)
yo
how would I get the author of a message in an on_raw_reaction_add event if I can't use ctx.author
payload.user_id convert to user/member object
You can also check if the payload had guild_id and try fetch a member with that data
If i want my bot to mention a message in vs code terminal is this how its done? print{member} Welcome to the {server}
wdym mention a message
Mentioning is a Discord thing. The application transforms a string into a mention, so using it anywhere else will be a string.
i mean something like heyy {member} welcome to the {server}
the member turns to a Gangsterhood101#8346
What is the difference between the brief and description kwarg in the command decorator?
brief = brief/short description of the command
description = command description
I'm guessing this would only matter if you're subclassing the help command?
@command(description = "this is the description")
async def cmd(....
"""
This is the brief/short_doc/Command.callback.__doc__
"""
brief is usually the short help
ofc doesnt brief mean a resumed version
It Does
hey guys how do i get these kinds of text things in my embeds?
how do you implement them?
<t:<timestamp integer>:Type>
mhm
There's an internal function in discord.utils too but I'm unable to recall it
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
^
not really related to bots but people on ny server are telling me that webhooks are really exploitable and shouldnt be used byt u cant see how. Does anyone know why?
They are only exploitable if you leak the webhook's token
if you don't keep providing manage_webhooks to random people there's nothing wrong with it
Basically it can be misused by people by copying the webhook url and sending messages
And by exploitable the most you can do is spam messages
yeah idk what people are freaking out about
but its tye same with a bot if you leak the token
bot token leak can be really harmful to servers which provide additional perms to bots
As it can simply do anything within the server , webhooks are limited to sending messages , thw worst they can do is spam and send everyone pings
yeah
my bot for a server doesn't have mention everyone pings
holy shit that exists? i always used to do it the hard way with datetime and calendar
I turned it off for mine completely , everyone pings , role pings and reply pings are turned off
whats calendar?
you will still need a datetime object....
If you use the util
true true so like a datetime.datetime() obj
yeah
think of a psyichal game irl, then put into your bot
make a flip phone with buttons and the screen is a picture and you change the pictures on a button click
or maybe a smart phone
wait do y'all make a class to just do bot=Class() and is it better to do it?
I do, and that's just for overriding some methods
what methods will be overrided?
None if you dont override them..?
ok
how to i get user by id in on_message discord.py
@commands.Cog.listener()
async def on_message(self, message):
if record := await self.get_all(message.guild.id):
print(record)
for i in record:
if message.guild.id == i["guild_id"]:
user = discord.utils.get(self.bot.get_all_members(), id=i["user_id"])
print(user)```
$ /usr/bin/env d:\\servernotif\\env\\Scripts\\python.exe c:\\Users\\andan\\.vscode\\extensions\\ms-python.python-2021.12.1559732655\\pythonFiles\\lib\\python\\debugpy\\launcher 62877 -- d:\\servernotif\\servernotif.py
Logged in as Ping Notifications#4447
[<Record guild_id=836464932236165140 guild_name='Server Sebelah' user_id=811051954389647372 user_name='Ditttt#6059'>]
None```
why the result is None?
do you have member intents enabled?
oh yeah i forgot, thanks for reminding
Why not just do bot.get_user BTW
Hello so i have a function that is trigered with *convert
async def convert(ctx: commands.Context, count: int):
Is there a way to make it trigger with *cher convert instead?
So it would have 2 words that would trigger it with a space in between?
I know i can do *cherconvert
But would like to use *cher convert instead is this possible?
The function converts a number inputed by the user
*convert 10
so it converts number 10
why doesn't this work:
@bot.command()
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def rhyme(ctx, *, word):
try:
def check(r: disnake.Reaction, u: Union[disnake.Member, disnake.User]):
return (
u.id == ctx.author.id
and r.message.channel.id == ctx.channel.id
and str(r.emoji) in ["🔄"]
)
async with aiohttp.ClientSession() as session:
newword = quote_plus(word)
url = await session.get(f"https://api.datamuse.com/words?rel_rhy={newword}")
urlJSON = await url.json()
rdn = random.choice(urlJSON).get("word")
success = await ctx.reply(f"Word: {word}\nWhat rhymes: {rdn}")
await success.add_reaction("🔄")
event = await bot.wait_for(
event="reaction_add",
check=check,
timeout=30.0,
)
except IndexError as ie:
await ctx.reply(f"There are no words rhyming with {word} :(")
except asyncio.TimeoutError:
pass
else:
newWord = random.choice(urlJSON).get("word")
if str(event.emoji) == "🔄":
await success.edit(f"Word: {word}\nWhat rhymes: {newWord}")
my error is: 'tuple' object has no attribute 'emoji'
because on_reaction_add returns (reaction, user)
event var is a tuple
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
You get (reaction, user) as the response
oh
just index it
No help for me 😦
so event[0] or smth
yes
event[0].emoji
oj
Hello so i have a function that is trigered with *convert
async def convert(ctx: commands.Context, count: int):
Is there a way to make it trigger with *cher convert instead?
So it would have 2 words that would trigger it with a space in between?
I know i can do *cherconvert
But would like to use *cher convert instead is this possible?
The function converts a number inputed by the user
*convert 10
so it converts number 10
No issue just a question
Yeah sure , use command groups
sad new error now
!d discord.ext.commands.group
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Note
If the original message has embeds with images that were created from local files (using the `file` parameter with [`Embed.set_image()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_image "disnake.Embed.set_image") or [`Embed.set_thumbnail()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_thumbnail "disnake.Embed.set_thumbnail")), those images will be removed if the message’s attachments are edited in any way (i.e. by setting `file`/`files`/`attachments`, or adding an embed with local files).
You need to mention what you are editiing ie content = "THR MESSAGE"
♥️
if this works thanks sarthak and tylerr
it does!!! but it only works for 1 reaction :[
how can i make it infinite or something
use a while loop.
oh yeah and if str(event[0].emoji) == ":arrows_counterclockwise:": would check if the USER has reacted, not the bot right?
no......
fuck
just add , an and condition...
i don't use not that much and was thinking and ctx.author not bot.user or and ctx.author != bot.user
ok
why you comparing the that to ctx.author tho
true , ctx.author won't be a bot user ever
ok but then do reactors have an author attr
no on_reaction_add returns the user that reacted
you get the user
wait i forgor
on_reaction_add returns (reaction, emoji) as tylerr said so im confused if there is an author attr or something similar
wait tylerr alr specified
You're just trying to see if the reactor is your bot right?
didn't you say it returns the reaction and emoji
yea
The bot that contains the command being executed.
ok this exists
That would work i guess.
now moving on to the while part
wouldn't that just make the bot 24/7 edit the message
Why not just exclude all bots , and not event[1].bot
holy shit that's fucking genius
uselessly genius idea
ok since we have if the reactor is not the bot
Break out somewhere
On your first timeout you could break the loop.
while True:
try:
await Bot.wait_for(timeout=30)
except asyncio.TimeoutError:
break
man you sure do swear a lot
true true
😂
but my gut is telling me that if the user did react with the emoji, the bot would endlessly loop the editing right?
Yeah if a user did add an emoji before the timeout ends it will continue onto the next iteration.
Basically , it gets disabled when the emoji is not clicked atleast once in every 30 seconds
ok but then what happens if the user reacts to the emoji in the loop?
i do know the positioning of the loop does change shit
The loop continues.
and continue in this case would be known/defined as?
when someone reacts
.
If someone reacts to the message the loop will continue. If not within the 30 second timeout it breaks the loop and it will no longer wait for emojis
so it doesn't endlessly edit the msg, air (am i right?)
when the user has reacted
it should edit the message once
not how much letters are there in the bee script into edits
how to switch lines when ur bot is sending a long message?
ok so it doesn't endlessly edit the message, it just sends a new message with the reaction
'message\n' + 'message' if im right
you don't need a plus
"for example:\nthis works!"
It does whatever you make it do whenever someone reacts to the message
thanks
!e print("hello\nworld")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
The loop is just something that will make it continue to listen for someone to react to the message. Like, thats all it does.
well after the reaction and edit it sends a message x]
which is not an error one
its just the success = await ctx.reply(f"Word: {word}\nWhat rhymes: {rdn}") from my code
well yeah then ig, everytime someone reacts it will do that.
aw man so i can't remove that? :[
I mean, if you dont want it to endlessly keep sending messages everytime someone reacts just take it out of the loop.
tru tru so at the else: statement where the reaction action is
await message.send('message\nmessage')
```this will do
bro message.send is not a thing i think
but normal we call it ctx not message
thanks
he's doing it in an on_message event
oo
Message.channel.send
^
ok i get what u mean now
message.reply does the same except just replies
well this is an event so it'd be weird to add ctx here
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
:/
not really
:/
ctx is short for commands.context
nobody saw that
i forgot
i thought ctx = context hmmm
maybe my mistake
yes the context of the command?
maybe
in this case the class commands.Context
thats why sometimes you see
@bot.command()
async def command(ctx: commands.Context) -> None:
await ctx.send("msg")
i swear i saw that
its 4am give me a break
async command 💀
and im on mobile
its 4am smh
if it was 1 hour earlier then 💀
¯\_(ツ)_/¯
3am moment
lol
ill remember you typed async command
smh its 4am leave me alone im falling asleep rn no jk
I wonder if I can attach a file inside embed ?
hey tylerr putting the while loop in an else statement kind of endlessly edits the msg
i think you can im not sure
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Docs please
nah this isnt for embeds
I don't think that embeds
use embed links perm
!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.
I want to embed a wav file inside
i don't think you can...
I thought the same and that's why I asked....
if its a img you can ofc but a file im not sure
you could always set the wav file above the embed
It's an audio....
as the content
good morning guys
Gn!
Sd!
no jk its morning in my country rn
you could say that
Good afternoon guys!
its 4am so ig
lol
gn
!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 fuck
that's my entire bot code 💀
how can i make it so that it doesn't send a new msg everytime someone reacts https://paste.pythondiscord.com/ejopisadoz.py
GitHub exists......
:/
this
wdym
check it
No, The else has nothing to do with what the while block does. Its only to significant to the factor if the loop will even start.
put the while 1: before the wait_for then
if your trying to say if the loop even started, yes yes it did 💀
I honestly don’t understand what’s going on with your stuff anymore.
Like can you explain what you wanna do with this command again.
oh yeah alright
- look for a rhyming word with the word given
- it sends the word and rhyming word with the word
- adds a 🔄 reaction to get another rhyming word
- yeah i forgor but i think that's it
How can i get all the guild id the bot is in?
-
send message with rhyming word and whatever word they send
-
add repeat emoji before starting your whole loop
-
start a while loop with your Bot.wait_for()
-
everytime they react to the emoji edit the message with new content or whatever.
-
when any of the wait_for timeouts hit. Break out of the loop.
[guild.id for guild in bot.guilds]
That map should cover everything you want.
ok but the third one is kinda misunderstandable tho like "with" my bot.wait_for() or "near" my bot.wait_for() 💀
ok
Imagine being it like async command instead of async def command :DDD
Do the bot.wait_for() in the loop. As well as the message editing.
Or it’s not gonna continuously wait for reactions. Like you want it to.
well it is already in the loop x]
the try statement, the except statements, the else statement
ok if you did all that and followed the map I just gave you. Everything you want from that command should happen, no?

could it be because the reactions are mine?