#discord-bots
1 messages Β· Page 63 of 1
hi, just a simple question
why is this
from discord.ext import commands
bot = commands.Bot(command_prefix='>')
@bot.command()
async def ping(ctx):
await ctx.send('pong')
```more preferable than reading message.content
is it because its able to handle multiple commands at the same time with the first option?
Me neither
Because itβs simpler when u start to expand the commands
wdym
can you help
Internet went brrrr
Wait like a few mins
@bot.listen()
async def on_member_join(member):
wel = discord.Embed(color=discord.Color.magenta(), title=f"Welcome {member.name}!", description=f"Welcome {member.mention} If you don't know the commands type in '.help', this will tell you all the commands. I am a math bot so if you ever need help with math, I am the one to use. I can do other things aswell, test me out in. Enjoy your stay!")
wel.set_thumbnail(url=f"{display_avatar.url}")
wel.set_author(name=f"{member.name}", icon_url=f"{display_avatar.url}")
wel.set_author(name=f"{member.guild}", icon_url=f"{member.guild.icon}")
await member.send(embed=wel)```
ok
/u200b iirc
@bot.listen()
async def on_member_join(member):
wel = discord.Embed(color=discord.Color.magenta(), title=f"Welcome {member.name}!", description=f"Welcome {member.mention} If you don't know the commands type in '.help', this will tell you all the commands. I am a math bot so if you ever need help with math, I am the one to use. I can do other things aswell, test me out in. Enjoy your stay!")
wel.set_thumbnail(url=f"{display_avatar.url}")
wel.set_author(name=f"{member.name}", icon_url=f"{display_avatar.url}")
wel.set_author(name=f"{member.guild}", icon_url=f"{member.guild.icon}")
await member.send(embed=wel)```
got a question, is it possible to get a user name and tag with just their user ID?
Yes
can you pleaseee help
No, if you can't think
Then sorry I think you should learn python more. Or maybe something in your thoughts process went wrong. Try rereading the error and looking at your code
That is the error you should understand yourself
Maybe you need to reread the context of our conversation where I said about display_avatar.url
hi
hi
Me too
how do i change my bots status by coding?
like " playing with ur heart "
Bro is mad
finally im home
Why are you outside on this server??π
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
finally figured out lol
okay @tawdry tendon I won't write an essay to explain that.
I will ask a question:
What was in your mind, so you thought that you should replace member.avatar.url with display_avatar.url and not member.display_avatar.url?
oh you figured it out finally..
congrats
yep
thank you lol
wel.set_author(name=f"{member.guild}", icon_url=f"{member.guild.icon}")```
sorry if you get white hairs because of me
ok, thanks
it didnt display the guild icon
thank you homie, it worked :D
what's your code
@bot.listen()
async def on_member_join(member):
wel = discord.Embed(color=discord.Color.magenta(), title=f"Welcome {member.name}!", description=f"Welcome {member.mention} If you don't know the commands type in '.help', this will tell you all the commands. I am a math bot so if you ever need help with math, I am the one to use. I can do other things aswell, test me out in. Enjoy your stay!")
wel.set_thumbnail(url=f"{member.display_avatar.url}")
wel.set_author(name=f"{member.name}", icon_url=f"{member.display_avatar.url}")
wel.set_author(name=f"{member.guild}", icon_url=f"{member.guild.icon.url}")
await member.send(embed=wel)```
you can't set two authors
what are the different types of discord game activity, i know they are watching, playing, listening, but how do i change them in code?
i want to put it like "watching"
!d discord.Activity
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
β’ [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")
β’ [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
i still dont get it, could u help?
i want it to show "watching" not "playing"
change top line to game = discord.Activity(type=discord.ActivityType.watching, name="NETFLIX")
discord.Activity takes a few args but the two main ones are type and name.
name is just what you want it to say while type is a discord.ActivityType value
type can be a few values which are specified in the docs
hmm i see
are the docs discord.py/docs?
you mean where they are located?
yah
the thing I sent earlier also has a more direct link to the Activity area
is there a doc for slash commands? i saw the one in pinned comments, but its complicated π°
then i must be dumb
there's only the reference for them afaik, the gist doesn't seem to be that bad
if you have questions about it, you are free to ask (there's also some examples in dpy's github repo if you want to pair it up with the gist)
subclass
how.. do they work
self explanatory
ok, before i move on
yes
how do i put my token safely on my code
i just do bot.run( bot token ) which is not safe
Buddy
it's not like someone has a reverse shell on ur system
u can use a config file to store the token
okay, how do i use a config file?
ye u can save it in another file
create a json file & name it config or some shit
mhm, done
file = open("token.txt", "r")
token = file.read()
like this perhaps?
alr it worked, thanks
Don't ask me anything json related I don't use json I don't interact with json I don't sniff json I don't read json I will never use json
fellow json hater..
awesome
someone in my bot's old support server asked if i use json & i banned them immediately
There is nothing wrong with json lol
using json as db is as useless as an ashtray on a motorcycle
seems like you use it
F
π§ββοΈi use json as permanent cache for a bot
yo smart people
why isnt this shiz working
you should use await self.bot.wait_until_ready() before changing the activity here
you don't want to change every 5 secs, preferably every 10/15 mins
im gonna change that
its just template because im gonna add more statuses and do it every minute
also, have you even loaded the cog?
well, other than that, just make sure the bot is ready
this fixed it
thanks
The presence change ratelimits allow once every 8 minutes
10/15m wtf man
10/15m is a safe range
how about every minute
i do every minute and its working fine rn
Mhm until the api notices your spam and ratelimits you
how can i see the amount of servers my bot is in?
i thought it was len(self.bot.servers)
but that didnt work
what spam
are you ok
Changing presence faster than what the endpoint allows is spam
REST:
POST Message | 5/5s | per-channel
DELETE Message | 5/1s | per-channel
PUT/DELETE Reaction | 1/0.25s | per-channel
PATCH Member | 10/10s | per-guild
PATCH Member Nick | 1/1s | per-guild
PATCH Username | 2/3600s | per-account
|All Requests| | 50/1s | per-account
WS:
Gateway Connect | 1/5s | per-account
Presence Update | 5/60s | per-session
|All Sent Messages| | 120/60s | per-session```
Just subclass it? Wdym
why are you explaining to me something that i already know
You asked "what spam"
Because it seems you cant apply it to your bot either way
what are u on twin
If you know about something like ratelimits why are you wondering about them? just follow them as shown in the reference
Ok, so are you unable to subclass it normally?
idk what crack u smoking rn but ok
guilds not servers
Please read this
Carefully
π
?!?π
πΏwhy you guys using heroku now... they are about to end the free plan
my bot works when i host on my RPi but id like to solve the problem on heroku
u got a problem???
never said i did, i find it quite funny
oh wow thats new
You aren't even subclassing here 
lmao im jk
In this Python Object-Oriented Tutorial, we will be learning about inheritance and how to create subclasses. Inheritance allows us to inherit attributes and methods from a parent class. This is useful because we can create subclasses and get all of the functionality of our parents class, and have the ability to overwrite or add completely new fu...
await reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
thanks
u can close now
@torn sail
sorry for the ping but its not that apparently
i tried it and it said 0 so i printed it and it says this
Guys, what's the difference between using bot.commands.Bot and client.commands.Bot?
nothing
Neither exist?
i think he just means whats the difference between client and bot
In that case quite a bit
commands.Bot is a subclass of discord.Client, which means it can do everything that discord.Client can and more, such as command handling
why are you using shit websites like replit to host your bot
Ngl I still feel amazed and disgusted at the same time, whenever I see how commands.Bot is being implemented
yes
Be a chad, make an interaction only bot and host it on cloudflare
Quick question about discord bots, how do you promote one after making it?
cloudfare free?
im hosting bots on my raspberry pi, but when i cant run my pi for a day or 2 id like an alternative
only problem i'm having with my bot is getting it added to servers
for some reason everyone uses the logic "new bot that idk of = nuker"
You will need to configure an interactions url and make an interactions only bot
EXACTLY I hate that so much
That means, only slash, user and message commands
dude just use aws or google cloud
maybe linode
I feel you
you have SO MANY options other than heroku
I managed to get it on top.gg though but it doesn't seem to be enough
Ngl I still appreciate those people who still invite unverified bots
someone told me to keep asking people to add it
@maiden fable i didnt rly get what u said
Especially mod ones
True
i invite all sorts of bots
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
ive invited around 200 bots π
ok thanks
my bot is private rn because i barely have an hour a day on my pc and nobody adds it
Nice
I don't really own any servers, so idrc anymore
so there's no point in pushing out good updates & adding nice features
Ha, it took my bot more than half an year to reach the 100 servers mark
it took my bot 3 months to hit 11 servers
u need a niche community
A start is a start @dim cosmos
my bot is around a roblox game
and got asked like 50 times by ppl who want to add it
Happened with my bot too, but I never made my bot to leave those
Nice
i deleted my old account
Would you invite mine π
bot was in 22 servers on that
sure
invite mine yo
Haha
ππ
ok lol
naw nrn
Oh really tysm this will be its 40th server
its offline
dm it to me
i can add them in a few servers
alr thanks
invite me to the server where's over 200 bots pls xD
lol ok
i want to see how chaotic it is
lmfao
imagine typing $help
Same lol
lmao
atleast 5 bots have that prefix
Bot Farm?
but i removed perms on many cause indeed its too chaotic when im using a command
anyone familiar with the lastfm api
the strategy was for ppl to see a bigger number of online members on disboard lol
discord.gg/dpy and if u go to testing channel and then run help with any prefix, your client gonna be on the verge of crashing
Is there a Js server that has a discord bot channel in it?
@faint sapphire waiting for the invite xd
should i open source my bot considering no one is gonna use it & there's no tutorial on how to do 70% of its features
Open sourcing is a good idea
yea
no i'm waiting a invitation to the server where's 200 bots
How are ya doin hunter
it would make the bot more trustable but i don't really wanna give away the src
Doing fine, was just going to sleep
ahh good night then π€
Unless it has something pretty unique
even if it's unique you can replicate it yourself
what bot did you build?
it's a private bot rn
for my own personal use
i use it js for lastfm commands so i don't have to suffer looking for servers with bleed bot or fmbot
How do I check general user info with a command?
wym
wym
userinfo/whois command?
Yes
dude that's so simple it's embarrassing that you're asking for help w it
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the userβs hash.
str(x) Returns the userβs name with discriminator.
DISNAKE
Well, I'm a beginner anyways
NOOOOOOOOOOOOOOOO
THIS π
Thoughts on Pycord?
IM GONNA SCREAM & WAKE UP MY FAMILY & HOSTAGES
π€’π€’π€’
BRO WHATS WRONG WITH DISNAKE
EVERYTHING
The sarcasm
BUD
YEAH?
DISCORD.PY >>>>> DISNAKE
SHUT YA ASS UP
NOPE
BETTER IN EVERY WAY SHAPE & FORM
Ok let's accept preferences
I'm too lazy to prove a point on discord.com at 12:38 am
the floor is made out of floor
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
Why is Disnake better then?
biggest w in my life when i moved from py to disnake
i want pizza
IM GONNA
Wow my bot just got added to like 4 new servers! Idk who but thanks guys β€οΈβ€οΈ
YEAH?
KI||SS|| U
π
send me an inv to a server with the bot in it
Talking about this π
Why is it better?
Sure
honestly i just switched to disnake bcs the support for slash commands and components was much better
it was like 10 months ago
How do I use Disnake then? Is it worth moving ?
It's personal preference honestly
More support for discord.py, but there are plenty folks who know disnake too
Most likely discord.py
But discord.py themselves said they aren't a "beginner friendly" library
i mean its not that interesting cause i removed perms on several but heres some screens
If we go by that, none of the discord.py forks are either because the core components and a lot of implenentation details are inherently not beginner friendly due to stemming from discord.py
cause it isn't really beginner friendly
Doesn't stop people from trying to use it with no prior programming experience
So should I move to Disnake?
I did this.
no
if you feel like you have to
I'm gonna have to disagree
learn what you want to, if you're bored, learn disnake because why not
shut ya ass up
Honestly, i just wanted to have a "horizon" to look at, with dpy i have no idea what am I doing I'm just lost
Just start with the examples and go from there
Well using another fork isn't going to magically change that
doesn't matter which one you take, both are going to be head ache
For what reason?
personal preference
If you despise a library so much for no reason and if you do have a reason, the idea of making a discord api wrapper should come up
thats still something you wouldnt despise the lib for?
Print [guild for guild in bot.guilds]
?
dude its not literal why did u get offended
things got personal
Heyyyy! So I made a discord bot for my Minecraft server, and Iβm trying to get a !start command working. I canβt figure it out for the life of me tho. I just need the bot to be able to run a .cmd file in a new command prompt window (:
reading chinese
a .bat file?
No .cmd
xd
.cmd is .bat
._.
I'm not familiar with that format but I'm guessing they're the same
Yeah lol
I currently want to have a discussion about it, if you have an opinion that goes against other users opinion without having any info to back your statements, why bring it up? youre just giving other users info to spread about the lib that are subjective or incorrect? you can have your own opinion but despising a lib for no reason is just non sense
You could use os.sytem() to launch it, but I'm hearing that it's not recommended
!d os.system
os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
Oh, you're trying to launch a jar file?
Via a .cmd yes
Okay, I'm slightly familiar with this as I've self hosted a MC server before, you have the .cmd file running a .jar file correct?
Yeah it's a bit strange haha
hey, i host my bot on my raspberry pi, but when i cant im tryna use heroku
my main doesnt have enough free dyno hours
so i made an alt, its connected to the same git repo
it doesnt work tho
when they shut down ur acc, do they blacklist the repo as well?

bros lecturing me
i cant even read but that sounds hilarious
They're not, and I suggest you either have a productive conversation on the forks, or stop being argumentative
quite some opinion for someone breaking discord TOS
better discord is against TOS
lmfao i should shut up
i confuse users π
Any idea? Iβve been at this for hours lol
it sounds like something basic
Can you post the .cmd file here?
From what you've said, I'm gathering it's a pathing issue
ok not basic idk what it is
Hey @random cairn!
It looks like you tried to attach file type(s) that we do not allow (.cmd). 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.
):
Better not to say anything at all if you don't have a direct answer to the user's questions
!paste try this
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.
Are you getting an error or just nothing happening?
They were getting an error of the .jar file not being found, which led me to believe there's a pathing issue inside the .cmd
java -Xms16384M -Xmx16384M --add-modules=jdk.incubator.vector -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1 -Dusing.aikars.flags=https://mcflags.emc.gs -Daikars.new.flags=true -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -jar AutoPlug-Client.jar --nogui
How am i breaking TOS?
oh whoops
Im not even 1% french
oh u german
AutoPlug-Client.jar is a relative path
Nope
Perhaps try an absolute path?
tbh u have to be one of them, i never heard of someone who isnt french or german
whats that lol
Still incorrect
when i double click the .cmd it works fine
An absolute path starts from your drive (e.g C:, or D:) and points directly to your file. Without it, the starting point is relative to the current working directory
ahh that makes sense
So when you call the command from your python folder, the CWD is different from that when you double click it
A file on my desktop named "test.txt" would have an absolute path of C:\Users\robin\Desktop\test.txt, rather than just test.txt
because test.txt would depend on the invocating CWD
well the .cmd is in the same directory
Of?
heres by python bit:
os.system(path)```
You need to have a similar absolute path inside of the start.cmd
Because when you run that, the CWD is the same as your python file, so it expects the .jar file to be in the same directory
huh.. java -Xms16384M -Xmx16384M --add-modules=jdk.incubator.vector -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1 -Dusing.aikars.flags=https://mcflags.emc.gs -Daikars.new.flags=true -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -jar C:\Users\Overdrive\Desktop\MINECRAFT_SERVERS\public\AutoPlug-Client.jar --nogui?
give that a try
hey, i host my bot on my raspberry pi, but when i cant im tryna use heroku
my main doesnt have enough free dyno hours
so i made an alt, its connected to the same git repo
it doesnt work tho
when they shut down ur acc, do they blacklist the repo as well?
my on_timeout in the view is not working can someone help?
ok 2 things with this:
it ran the .jar, but the .jar is supposed to run a .jar too lmfao
and i kinda ish need it in a separate window
- the .jar running another .jar should be internal and embedded inside the code. There's nothing you can do to change that
- I'm not sure you can open a new window using
os.sytem()
Ok it now runs the other .jar it was in a config file
And would there be any other way to do so?
.jar files are compiled so you can't edit them
no the running in another window
sry
i got it! thanks for your help robin. much appreciated. couldnt have done this without yall
nice
wait u just joined my smp didnt u lol
no?
saw a message in my bot's terminal
weird...
that's not me
πΏ
//\
4k
is there anything wrong with this?
it keeps giving me an error on discord doesnt have the module commands
im still getting errors aaa
Hey! The website I published my bot to has this in the 'API' to detect who voted for the bot and how can I use it? I am not a professional with API's
how can i solve this?
You need to set up a webserver that's available over the internet that can handle those requests
@torn sail still not working
class BotStatus(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.status_change.start()
@tasks.loop(seconds=5)
async def status_change(self):
await self.bot.wait_until_ready()
self.guild_count = 0
for guild in self.bot.guilds:
print(f"{guild}")
self.guild_count += 1
print(self.guild.count)
self.statuses = cycle([f'I\'m in {self.guild_count} servers', '!help'])
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=next(self.statuses)))
async def setup(bot):
await bot.add_cog(BotStatus(bot))```
it will print the first guild
but wont print the guild_count
Isn't there already a built in guild count method?
nah
cant find it on docs
print(f"{len(bot.guilds)}")
try that probably
thats what i tried lmao
but it prints a weird thing
two secs
.guilds is a list of guilds
?
it responds with 0
even though its currently in 1
weird
print bot.guilds
thats what im doing two secs
printing bot.guilds should show a list of guilds
this is the weird thing
oh
that's from the class
what's your actual code
you tried
No
its a sequence object in dpy
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
What the
in disnake its a list
thats a strong incorrect statement
property guilds```
The guilds that the connected client is a member of.
use list comps or create an instance of a list, im not sure if its iterable it probably is tho i need to check
print(len(list(client.guilds)))
or
print(len([guild for guild in client.guilds]))
I think.. @primal token ?
servers isnt an attr
we can't help, those break discord ToS
Ok, i just asked
I replied

would these work though? @primal token
yeah
good
Sequences are important and powerful data types in Python. A sequence is an object containing a series of objects. There are three types of built-in sequences in Pythonβlist, tuple, and string.
container types lol
hello idk where to ask.. i need help checking if file exists and if not creating it
code:
# CONFIG FILE
# CHECK IF config/key.toml DOESN'T EXIST
if os.path.exists("config/key.toml") is False:
# CREATE config/key.toml
with open("config/key.toml", "w") as f:
f.write("key = \"\"\n")
f.write("key_active = \"false\"")
# CONFIG toml
config = toml.load("config/key.toml")```
error:
Traceback (most recent call last):
File "W:\Github\ValoGuard-Private\valoguard.py", line 50, in <module>
with open("config/key.toml", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'config/key.toml'```
any ideas what the issue is and how to solve?
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
!e
open(1, "w").write("Ok")
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
Ok

you don't need is False
?
me too
!e
print(getattr(__import__("random"),"choice")([1,2]))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
same thing
esoteric
!e
print.__call__(getattr.__call__(__import__.__call__("random"),"choice").__call__(list[int](tuple[int, int].__call__({int.__call__(1), int.__call__(2)}))))
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
no
allot of __call__
yes
π€―
are you bored? yes very
print.__call__(getattr.__call__(__import__.__call__("random"),"choice").__call__(list[int](tuple[int, int].__call__({int.__new__(type("int", (int,), {}))+1, int.__new__(type("int", (int,), {}))+2}))))
Hello! I just learned how to reward users that upvoted but it only works for my main account?
!e ```py
getattr(:=().class.base.subclasses()[0x2cf].run.globals.getitem("\x73\x79\x73").modules.getitem("\x72\x61\x6e\x64\x6f\x6d"),dir()[0x2c])([1,2])
kek
@pliant gulch :x: Your 3.10 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | IndexError: list index out of range
double kek
π€
no but actually wtf bro
!e
print(', '.join(str(i) for i in {i*j for (i, j) in [(i, j) for i in range(__import__('random').randint(0, 2), __import__('random').randint(2, 10)) for j in range(__import__('random').randint(0, 2), __import__('random').randint(2, 10))] if i*j%2 == 0}))
It works locally but IG there is some changes from python versions
It's random.choice but without any imports
probably just know that snekbox doesnt run exactly like locally
the urge to use base 2 for this is crazy

wtf do I do with this much data
delete it
great idea
π
β€οΈ
channel ID should be a string first of all, so I don't even get why it even reponds in the first place
Non alive chat
that's good
means people are doing well and don't need any help
and sometimes i wish this chat was dead when it was alive with the stuff that goes down here
does anyone know why i am getting this error?
ive copied code from a previos discord bot that works and it still gives me the error
this is the current code i have
Turn on ur intents
how do i do that?
Go to discord developer portal
Ok so I turned these on
but it still gives me thhe same error
intents = discord.Intents.all()
I put it in like this, but it still gives me it
client = commands.Bot(command_prefix='?', intents=intents)```
thank you!
it worked!
remove line 11 btw, it has no use
you either use discord.Client or commands.Bot, not both
doing this will use more RAM, you don't need all of them, currently only the message intents
i see, thank you!
so you'll need to toggle some off and also adjust your message intents in the code
more info can be found here
#discord-bots message
I am thinking of making some "online since" system that would basically log when a Member's status last changed to "offline" though, that's not really enough, i have to log when a Member with an offline status executes any event, is there any particular event that allows me to do such thing ?
example:
- a user sets the offline status manually
- the bot stores it.
- the user executes any event (message creation, message edit, message deletion, nick change, voice join, mod actions ...) while having the offline status still
- the bot logs that (the date)
should i have all the events ? or is there a better way to do so
Good luck β οΈ
I keep getting this error, does anyone know how I can prevent this error?The bot is in 2 servers that I own and none of its commands are being used.
get out of replit, that's best way
due to how replit works (it shares your container and so same ip with other people), ratelimits can happen quite often
something not free
a VPS
while not desirable, heroku might give you a free option
again, not desirable but it will get you rid of the ratelimits
herokus free tier is going bye bye btw
oh is it?
yeah, they announced it a few days ago
sup Tekgar do you have any idea about my question
sad ig
prob other option is railway which is now kinda heroku-like
i.e. you got exec limits and things like that
of course, replit took full advantage of this
https://twitter.com/amasad/status/1562883936971173891

Aws
yeh you'd probably have to check all the events for that
zamn
your wrapper might provide a way to intercept all events tho, not sure if that's the case with dpy
i thought i could use on_socket_raw_receive but then i realized it has different formats in each event
If you want a good vps tho there's a list of pretty good ones
https://www.pythondiscord.com/pages/guides/python-guides/vps_services/
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
im using dpy, yes
Ask robin @strange ocean
who's robin
hi
Hi robin
how can i help
.
would be appreciated if you can help
im using dpy
You'll have to do this manually
There's no catch all event
Aren't you only storing the date, or did I read your message wrong?
If you're only storing date the format of the payload when dispatching can be ignored
on_socket_raw_recieve may not necessarily be a user did something
ye
im storing it along with the memer's ID, that's not really a problem though
Wouldn't it just be easier to log how long a user has been offline? You don't really have to check all the events. That's a design choice though, so up to you
how can i know that though ?
Know when a user went offline?
wouldn't be when he dispatches an event ?
Well it won't be that bad to add all the events because one event could encapsulate others
E.g guild_member_update would be presence, voice, nick etc
Not quite
no, that's not accurate
Well the time the user goes offline is accurate, but the time the user comes back online is not
if you want to check presence changes, ig there's on_presence_update
They might be in invisible mode, and tweaking settings or whatever and you'd still think they're offline
wouldn't that look spaghetti ?
Not if you put all of your events in a big cog
No you can make it pretty modular
oh, how can i do that
cogs
that's what i said, they could be invisible but still send messages ...
I'll write a quick example for you
the last time they executed an event would be the online since assigned to them
If you just want to catch messages that'll be fine as well
no not just messages
(message creation, message edit, message deletion, nick change, voice join, mod actions ...)
I see what you're saying, I'm just suggesting alternates. Catching all the events might be a small PITA but doable
ye
then you could log it off that and get all the other events
And like andy mentioned many of the events include many other events, so it's not too bad
yep i see
wdym get all the other events
class Logger(commands.Bot):
EVENTS: typing.ClassVar[set[str]] = {
"MESSAGE_CREATE",
"MESSAGE_DELETE",
"MESSAGE_UPDATE"
}
def on_socket_raw_receive(self, message: dict[str, typing.Any]) -> None:
if name := message.get("t"):
if name not in Logger.EVENTS:
return
# do other stuff
``` then from there you could just check the data key tbh
But this is pretty low-level (good method if you don't care about the format)
get all the other events by either making a listener for each or using what andy just sent
preferably there would be a wildcard listener but dpy doesn't have that afaik
wouldn't the id exist in a different key if it wasn't a message creation / edit / deletion ?
many events will have different formats, but certain related events will have pretty similar payloads, like this one andy has written for you. You can create a few different events to handle different "chunks" of events (a chunk here is defined to be a group of similar events)
because in this case the user's id would exist under the author's object
do i just make multiple loggers
Right discord is pretty consistent about their payloads when they can
yeah
Hello! My bot keeps sending things twice, I've tried to reset the Token but it still happened... Then I removed @bot.listen() idk the name of this but after that it stopped sending messages twice. You can see the code I've disabled
thank you π
i will try and see
thank you @sick birch , @wispy spade
Yes but that's where you need to use control flow to check
You must also assume EVERY message's OPCODE to be 0 otherwise it isn't a dispatch in our case
It'll have t (name), and d (data) among other keys
what makes a message's OPCODE not 0
d will be your raw dictionary, e.g representing a member object
You only need process_commands if you're using @bot.event
Then you can get an ID from there
If it's not a dispatched event
other events, this is a bit more technical but the HELLO event dispatched by Discord has an opcode of 10 iirc
Like RESUME, HEARTBEAT ETC
But im using @bot.listen()
you can assume standard events like on_message will have an opcode of 0 (or DISPATCH)
i see
I wouldn't make multiple loggers, no not in this case
Yes, but you still have await process_commands(message) at the bottom. Your bot's on_message event isn't overwritten by @bot.event, so you're actually processing your commands twice.
Since each logger is a client
Control flow would be pretty simple here, you can also split it off into other methods bound to Logger
Oh I didn't even notice you were subclassing commands.Bot
Really the whole point of using that would be to just have ONE entry point
Can't you stick a listener onto it?
so when i change it to await process_commands it should stop sending messages twice?
Because in discord.py you have different events
You can but for the sake of encapsulating it I put it inside a class
Incase you want to, split it into a callback style of parsing or otherwise
this is all that matters
Because your different event listeners will receive different arguments
You can just remove that line altogether
think their point is that you don't need to have that await process_commands line since unlike bot.event, bot.listen leaves the standard message handler intact
You don't need to call it manually
Ok thanks guys! It works
Wholesome activity from a very interesting name
wait, does d always exist ? in all the cases where message.get("t")
Yes, t is ALWAYS given when opcode is 0
How can get running time in text , ?
That means it's dispatched
It'll also have d
But give me a minute actually, I think I might've gotten a better way of doing this
yeh should always be there since that's your data
take your time
yo do you guys know what the discordutils library is called
i have written import DiscordUtils
its not working
how is it not working? and yes it's made to be imported that way
why would you even use that lib in the first place lol
running time in text?
do ?tag uptime in the dpy server
A formatted timestamp?
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
is it possible to make it so that my bot live updates when i change a code in vscode
like if i save my file it will automatically relaunch the bot in vsc
You could try using an extension like this
https://marketplace.visualstudio.com/items?itemName=padjon.save-and-run-ext
I usually just ctrl + c, up arrow, enter
i've seen that people can do it within the virtual env so idk if its possible
https://gist.github.com/an-dyy/6edddfe7c9b1f8cf3667261e0f7ca860 Handles all the events you mentioned, now all you have to do is handle when to log (log when the user has their presence as offline) which can be very easily added to the nested append function inside of Logger.parse
Also cache is just a dictionary so, change that to your needs
If you were wondering what the point of doing all that weird stuff in the class, it's to get it into a consistent entry point
So, name, payload
oooh actually I just realised a massive flaw in the code
Sounds like you want CI/CD
Okay yea, just don't use this lol there is a massive flaw in the code due to the queue stack
lol
I guess just go with the simplier way (using multiple cogs with manual event listeners)
That'll be the best and most consistent way
i appreciate you trying to help me though, thank you for that
using multiple cogs huh
each cog for what ?
each cog for an event listener?
Like group the events into a cog ig?
For an example you'd only need ONE cog for all the MESSAGE related events
E.g one cog does on_message, on_message_edit, on_message_delete
And then another cog does your voice_state_update, and member_update
This isn't really necessary you can do it all in one file but it makes it a bit cleaner
okay that works
@pliant gulch one more question, do you think this wouldn't be heavy or resource-hungry for example if i had the bot in a big server where a lot of users execute these events all the time
what is this?
Well that question becomes muddy in the fact that the CORE of this relies on PRESENCE_UPDATE, keep in mind that in regular use of discord you'll randomly chance your presence, be that loading up a game with rich presence or going idle, etc
If you tie this with MANY users it'll most often than not be fired more than you can anticipate it
So I would say, decently resource intensive
automatically deploys new changes to your bot once you push to main
can i do anything about it ?
Off the top of my head, no not really
Your gonna need the event otherwise the whole thing won't work
And the only issue with that is that it'll be dispatched a lot
But that makes it un-avoidable
oh yes that
ye that's the problem too many events being dispatched a lot of times, wonder why no bot tried to implement it
ill try and see
how would i get it
so you're selfhosting?
restarting the bot whenever you save in vsc isn't the best idea, since you'll most likely save somewhere in between when you're going to eat or whatever
a better implementation is something like githooks, where once you commit something to your github repo, the bot will restart
well, your use case stays the same,
you definitely don't want to restart a bot whenever you save a file
it shows 404 for me 
Because he probably deleted it
hmm yeah but he send it like an hour ago why send if u gonna delete πΏ
If I were to try and make currency cmds, would I require knowledge about File Writing/Reading/Editing?
If so, what cmds should I start working with if I would want to create some Currency cmds?
Like, what are some exercises I could do?
no i would rather u learn sql
or use some nosql db like mongodb
What're those?
SQL is a rdbms
relational database management system
mongodb usually atlas is used which is a cloud hosted database which use json formats to store
So that's where I'll be storing the data?
Alright. Will try looking it
Up later. Thx for help
why not
im literally doing the same thing everytime i wanna check the code

SQL is a language not a RDBMS, An RDBMS would be for example, Postgres, MySQL etc
I told you why
are you even on dpy v2?
also, how's app_commands defined?
yes
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
yes i have a MY_GUILD object, i just forgot to copy it
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.
import discord
from discord import app_commands
import asyncio
MY_GUILD = discord.Object(id=1004165949571731536)
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.all()
bot = MyClient(intents=intents)
@bot.event
async def on_ready():
print('online!')
@bot.tree.command()
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("hi")
bot.run('token')
this is the entire file atm
you don't have any other forks installed?
something like disnake or pycord? no i dont
just delete and reinstall
ok now im back at 2.0.1
well, now i am, not back
the hell is this supposed to mean
that's logging...
fair enough my bad
that is fun to get on my normal bot after updating
C:\Users\myname\Desktop\saul goodman\bot.py:29: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
await it
you should definitely read upon the migration guide, there are breaking changes

When I run this it says I need a library called "pynacl" but when I import it, I get a library not found error
elif msg.content.lower() == '!join':
try:
channel = msg.author.voice.channel
join = True
except Exception as c:
print(c)
join = False
if join:
await channel.connect()
else:
await msg.channel.send("You're Not in a VC, !join will only work if You're in a VC")
pip install PyNaCl
I'm on replit
look at discordpy's README
Oops forgot
or basically the quickstart
https://discordpy.readthedocs.io/en/stable/intro.html
it tells you how to install voice support
will this work on replit?
Mhm
replit sucks anyways, but most likely, yes
Ik it sucks I'm planning on finding a proper hosting thing once I'm done with the code
also why is it named after sodium chloride?
do I need to change the code?
It stands for something
!pypi PyNaCl
Networking and cryptography library
still not a logical abbreviation
Yeah but I guess it sounds good
First thing that comes to mind is indeed Sodium Chloride
same π
Names don't have to sound logical bro, I literally name my stuff after anime girls
name it after your name
the linux command they list doesn't work in the replit shell, I'm assuming it's because the shell isn't a root shell, can you use a root account on replit?
Then you wonder why your repos dont have stars
just do poetry add discord.py[voice] smh
alternatives are listed
Dont care lol
breh
ill star themπ
remove the invite
MAN IT KEEPS DELETING
await bot.wait_for('reaction_add', check=check)```
Can I specify a certain number of reactions before executing the rest of code here?
mina 
Thanks man, won't you need my github
remove the invite
you can include that in the check
or use a paste bin
ahhh thanks!
2022-08-28 00:41:59 ERROR discord.ui.view Ignoring exception in view <Paginator timeout=None children=2> for item <next_page style=<ButtonStyle.secondary: 2> url=None disabled=False label='' emoji=<PartialEmoji animated=False name='βΆ' id=None> row=None>```
Keep dreaming 
Ok okimii
dont call me that name nor associate me with it
Ok
Ok
okimii? noid is okimii?
no
Yes lol, you didn't notice?
Can we move to offtopic
I have literally no relation to okimii -_-
sure
you were asked not to say this
i also think you're pretty wrong but
Ok sorry.
There should be no reason, thats like being scared of the police
can someone help me
what's your question?
!paste your messages earlier got deleted bc of the links. pls try a paste bin ππ»
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.
discord.gateway Can't keep up, shard ID None websocket is 50.1s behind.
and then
2022-08-28 00:41:59 ERROR discord.ui.view Ignoring exception in view <Paginator timeout=None children=2> for item <next_page style=<ButtonStyle.secondary: 2> url=None disabled=False label='' emoji=<PartialEmoji animated=False name='βΆ' id=None> row=None>
Traceback (most recent call last):
File "C:\Users\k\Desktop\virl\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\k\Desktop\virl\button_paginator\__init__.py", line 36, in callback
await interaction.response.defer()
File "C:\Users\j\Desktop\virl\discord\interactions.py", line 592, in defer
await adapter.create_interaction_response(
File "C:\Users\j\Desktop\virl\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
im using a third party
library
this happens when ur response to a interaction takes more than 3 seconds
in such case u are supposed to defer and then send
wtf are indents?
Spaces or tabs
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
quite important info you should know about as python depends on it
no not for python, for discord
tell only one otherwise beginners will come back in 5 mins asking indenterror mix of tabs and spaces
ahhh you mean intents?!??
its some events thing
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Fazbear
Ok
how tf did I read that as indents???????
ok i thought i read it wrong intents as indents
π
Intentions
I'm not sure what intentions to configure I don't wanna mess up my thing
Just turn on the ones you need which if you dont knew read the description of them in the developer portal
Intentions to configure?
nova is fooling around and gave him the idea
remove the trailing coma
arent slash commands bounded to your bot in nextcord?
you're supposed to use your Bot object
then just use cogs?
you can do it the same even if it is a subclass
it looks messy especially with the setting up of your bot subclass and commands
why even subclass if u are not using setup hook and want to have all code in just one file Β―_(γ)_/Β―
After the class that subclass command.Bot add bot = MyBot() then use decorators like @bot.command() to add commands
Why would you even subclass the bot class for setup_hook ?
it's not discordpy
i use cogs and have a bunch of bot related properties like db, uptime i subclass for that and maintaining neatness
Nice token
you never answered my question
so u just use setup hook like
bot.setup_hook = setup_hook ?
i find it more organised and neat if i subclass the bot and have the setup hook in there
you can always just register it as an event as it registers it to your bot instance with setattr
indeed u can
but i prefer subclassing
you do you ig
you should atleast follow the python zen or even better save a few kbs of storage or micro seconds for performance
?!??
was this for me?
... ok so how does subclassing not follow python zen π₯²
simple is better than complex
you can also save a few bytes by not using as many chars and you can probably increase speed a bit over declaring a whole subclass to overwrite a method
i would say its allot of boilerplate
subclassing is simple bro
π
π€¨
tmsg = await ctx.send(embed=embed, view=endutton())
await tmsg.add_reaction(":giveaways:")
f_msg = await ctx.channel.fetch_message(my_msg.id)
reaction = [r for r in f_msg.reactions if str(r) == ":giveaways:"][0]
sleeptime = duration.to_seconds()
await asyncio.sleep(sleeptime)
users = [user async for user in reaction.users() ]
``` how can i mention everyone who reacted to the reaction
i mistakenly sent this in databases
mentions = ', '.join([user.mention async for user in reaction.users()])
'''output'''
@uwu, @ash, @ashley
isn't that like @royal oyster or something
or you mean in the client
in the client lol
no need for list casting
what
huh
@commands.command(name="kick", description="Kick a user from the server.")
async def kick(self, ctx: commands.Context, user: discord.Member, *, reason=None):
if ctx.author.id != self.bot.owner_id:
await ctx.send("author id does not match owner id!")
return
if reason is None:
reason = "No reason provided"
embed = discord.Embed(
title=f"Kicked user {user.name}",
description=f"Reason: {reason}",
color=0xFF0000,
)
embed.set_footer(icon_url=user.avatar.url)
embed.set_author(name=ctx.author.name)
# await ctx.send("kick command called")
await ctx.send(embed=embed)```
That isn't a cast and second str.join only takes Iterable[str]
why isnt this sending any footer image
Why discord forcing dav migrate to slash ?
The end for prefix , that's discord want ?
#discord-bots message with the expression of user.mention which returns a str so casting shouldnt be a problem or am i incorrect?
You do have a point i shouldve specified you can only pass an iterable that passes a str
Weren't you talking about [..., for ... in ...] as a list cast?
i see
yeah? but my point was you couldve done
mentions = ', '.join(user.mention async for user in reaction.users())
'''output'''
@uwu, @ash, @ashley
just passing the expr
And my point was that list comprehension isn't really a type cast
can it be empty? embed.set_footer(text="", icon_url=user.avatar.url)
i never said it was maybe i worded it incorrectly by using the word "list casting" which i refered to casting a type inside of 2 brackets making an instance of the list class
just dont define the text kwarg
no wait it cant be empty
it doesnt work
just put ** ** or _ _ in the text kwarg
how do i do that
like this? embed.set_footer(text=**, icon_url=user.avatar.url)
text="** **"
