#discord-bots
1 messages · Page 36 of 1
@client.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"Successfully unbanned {user.name}#{member.discriminnator}")
return```
can anyone help the unban command works but the bot doesnt say anything
Lucas unban😔 ✌️
Yeah it's honestly a pretty terrible unban command
You could get away with a one liner honestly
yea might find a dif one that doesnt even have unban with ids feature
His code is quite outdated and horrible lol
Most of them are, I wouldn't go down the discord.py youtube tutorial rabbit hole
99% of them suck, and I can't even sugarcoat that
So a full rework of your unban command is in order
you mean the pycord rabbit hole?
so what should i do?
Your immediate issue is a spelling mistake
Should be discriminator not discriminnator
do one yourself
Or an easier way:
f"Successfully unbanned {user}"
and call it a day
Yea if i knew how
Well there's your problem then, you're officially in tutorial hell
It's never too late to get out!
Its never too late to learn python
does anyone know how to invite a user to a private thread?
its better to learn python and all the skills than learning syntax its just a mess
yooo
python is not a recognized command
how do i fix that
@sick birch wsp
Make sure you've got it installed and in your PATH
how exactly do you do that?
i tryed watching videos but couldn't seem to figure it out
Installing python or having it in your PATH?
path
Anyone knows where to start learning python?
!resources bunch of good resources here
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thx
bro i'm just stuck
@client.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason="No reason Provided"):
await ctx.send(f"Successfully banned **{member.mention}** has been banned by **{ctx.author}** for {reason}")
await member.ban(reason=reason)```
i want to know if I can change a few things on that and it will work with ids
Should already work with IDs
yea it does i mean for unban
Does it for the ban command as well?
So what's the problem?
I havent yet
why isnt this command working? ```py
@bot.command()
async def pet(ctx):
await ctx.message.delete()
img2 = Image.open("pet.gif")
attachment = ctx.message.attachments[0]
await attachment.save("image.png")
img1 = Image.open("image.png")
img1.paste(img2, (0,0), mask = img2)
await img1.save("image.gif")
await ctx.send(file="image.gif")```
it pops up with the error of ```Ignoring exception in command pet:
Traceback (most recent call last):
File "/home/runner/bottester2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 563, in pet
img1.paste(img2, (0,0), mask = img2)
File "/home/runner/bottester2/venv/lib/python3.8/site-packages/PIL/Image.py", line 1628, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/bottester2/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/bottester2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/bottester2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: bad transparency mask```
The end result should look something like this:
i want to know if I copy that and paste it for the unban command and change a few things will it work
Yes, change .ban to .unban
This is more fit for #media-processing
it has to be a User
why are there so many channels though
Right that too since if you're unbanning a user they won't be in the server
So people aren't all dumping their unrelated questions in the same channel
Keeps things tidy
i mean technically this is for discord bot
get toaster tagged
Yes, but the problem is directly related to media processing
having it on your path how do i do that
@client.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, member: discord.Member, *, reason="No reason Provided"):
await ctx.send(f"Successfully unbanned **{member.mention}** has been unbanned by **{ctx.author}**")
await member.unban(reason=reason)```
You want the easy way or the hard way?
you think thats good?
everytime i look up "discord pet command python" i only get actual pet bots
Just because you're doing whatever this is inside of a bot does not make it dpy related. #python-discussion
"i have a toaster in my house, do i ask a carpenter how to fix it?" - Laggy
easy ofc
Resources for discord.py are quite limited online, so one must rely on their own skills
i just started a week ago
Reinstall python, and make sure you check the little box at the bottom left that says "Add Python to PATH"
@sick birch
Typehint to discord.User, and rename your member to user to reflect that
As being a member and being banned in the server are mutually exclusive
so just change member to user
The variable name along with the typehint, yes
The other one by Lucas is poorly written and error prone, so I'm not surprised
It doesnt unban idk if it works or not it just says that
Did you typehint to discord.User?
@client.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, member: discord.Member, *, reason="No reason Provided"):
await ctx.send(f"Successfully unbanned **{member.mention}** has been unbanned by **{ctx.author}**")
await member.unban(reason=reason)
You did not
it says that when your installing python?
The installer does, yes
is there a command to add python to a path?
works thanks man
There is a command alright, it just a bit longer.
godam aight so when you download python ou can install it to a path?
Well, all you have to do is click on the small checkbox which is off by default. The installer will add it to the path for you
[Environment]::SetEnvironmentVariable("PATH", $Env:PATH + ";C:\Program Files\Scripts", [EnvironmentVariableTarget]::Machine)
Made with love for robin
Yikes yeah. Reminds me why I don't like working with windows commands at all
Nono these arent windows commands robin.
Powershell?
These are powershell commands
Of course
Thus called scripting environment.
Wayyyyy to verbose for my taste
I know right
I just had an issue for over an hour since os.listdir and scandir don't give back valid info after 100+ iterations with 10000+ files.
So I used a very sophisticated method to keep track of the dirs called json

why isnt it working @sick birch
Pretty sure in windows it's just one \?
wdym one ?
can you get in a call with us and help for 2 seconds
how to mute someone if they keep sending invites
with a bot
i mean ,warn them at first bt if they do it again then mute
can you get in a call real quick and help for 2 seconds would help alot man
I can't
I'd prefer not to, it's much easier to help over text
hes in a call with me sorry
😉
am not
?? I just saw you 2 in call
Its not good to lie robin even panda said it
DID NOT
Robbun stop lying🥺 
wrong channel
you meant #python-discussion didnt you😭 😭
mhm nice, i thought you wanted to ask it in #python-discussion since i see you allot their lol
yall weird
leme join for a second
isanyone watching 100t vs tgrd
Traceback (most recent call last):
File "c:\Users\momoa\OneDrive\Documents\Time Is Money bot discord\cogs\moderation.py", line 4, in <module>
from cogs.tools import *
ModuleNotFoundError: No module named 'cogs'
Hello yeah
I have a problème with my cogs

Show dir structure.
@client.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.User, *, reason="No reason Provided"):
await ctx.send(f"Successfully banned **{member.mention}** has been banned by **{ctx.author}** for {reason}")
await member.ban(reason=reason)```
Would anyone known why it doesnt ban the user
can i able to make command which player can do spaces in 1 argument and after that write another argument
i mean
for example
!kick [nick] [reason and here bla bla bla bla] [another argument]
it says it does but doesnt
you need to do member: discord.Member
you can only ban members, not users
You need an init file in there.
!d discord.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://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
I don't now what is this
someone know how can i do it?
__init__.py

__init__.py inside the dir you are tyring to import.
you can do
!kick @HRLO77 "being an idiot" 5D, wrapping arguments in quotes passes them as single arguments
should I rename it?
i dont understand
or you could just do async def kick(ctx, member: discord.Member, time: str, *, reason: str)
putting quotes around arguments makes all of text in the quotes one argument
or making reason at the end of the command 
No you don't need to change the code
so i have to put __init__ in tools.py? The file I want to import

Can't, parsing ambiguity
How would you know where the first argument ends and the second one starts?
But what is the dir I don't speak English very well
Sometimes I use Google translate to talk to you Otherwise I am French
"dir" meaning the folder you are trying to import from.
You got it in the file now just import it like you did previously.
Sure, as long as your 2nd argument is a single word
he could pass args and parse it himself maybe with like a --reason Raiding, just wouldn't be the best idea
Single word arguments should come first, and you can only have one multi word argument. The greedy converter is an exception
is it possible for a discord bot to create roles and channels ?
Just use slash commands 😊
how would i do it?
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
And create_text_channel for textchannels
ayo thanks bro
@vocal snow how would I use it in a line?
would it be
await create_role(name="name")
?
You need to call it on a discord.Guild instance
thanks
Would anyone know how to code this or can send a video so I can do it
I'm trying to do it to all of my moderation commands
how to send emoji with id
like you know
when i want do it with player then i need to copy my id and to this <@!ID>
and how i can do this with emoji?
i need it because i cant paste emoji to sqlite
Does anyone know why you're giving this mistake?
intents is required in v2.0 and up

how do I solve this error?
try intents=discord.Intents.all() as a kwarg
keeps giving the same error
try what i sent
I put what you sent, more keeps giving the same error
how can i print emoji id or something like this ?
What does it look like now?
what ?
anyone know?
Anyone here know why my if statement fails to send context?
If you try and execute the command, instead of sending ctx and returning it'll just give an error
Which is?
Lmao try to ignore the "activate windows" message
eh you can hardly see that
Anyways
Yeah so I get the error instead of it sending my if statement
Oh right. To make the argument optional, you'd do something like this:
@bot.command()
async def my_command(ctx: commands.Context, required: str, optional: str = None):
...
notice the difference between required and optional? Yours currently looks like required so the command won't even run if you don't provide a username
Ohh i see
Thanks!
no one?
The emoji’s ID.
its 9 pm go sleep
no😡 😤
btw its 4 am for me...
can you give me example for 😄 emoji ?
then go sleep
im spamming you with cat memes lolll

i saw
pretty cute right
not enough to compare with my cat but yeah

i cant understand it
what the
Say emoji was an instance of discord.Emoji, then it'd be emoji.id
If you want the ID of an emoji, you can just do it on discord by adding a \ i believe
nope
i have no nitro => no access to animated emojis:(
On the discord client, I mean
but i want to do it in python
Then you can combine discord.utils.get() with discord.Client.emojis
Why do you want the ID of a default emoji anyway?
.
So you want to save the emoji ID into sqlite?
so i need paste to sqlite something like :smile:
yes
when user writing emoji as a argument, in code it is normal emoji but sqlite cant get it
Do you know what i mean?
'This is \N{OK HAND SIGN}'```
This is 👌
yeah and what if i have 👌 emoji in code and want to convert it to
this
just replace it with \N{OK HAND SIGN}
how code can do it?
.......................................................
whhat???
if youre using an argument and it expects an Emoji obj i would just save the id so later on you can format it
How?
you typehint the argument with an emoji obj it should convert it and give you an instance and then just save the id, you should save the guild id as well to bind it
how can i get emoji obj?
i literally just said it.......
bruh
-
if youre using an argument and it expects an Emoji obj i would just save the id so later on you can format it
-
you typehint the argument with an emoji obj it should convert it and give you an instance

p-p-p-p-p-ppp-pwease dont
i want to storage emoji in sqlite but i cant storage it as normal emoji
i dont want to storage it in code for later but in sqlite
ohmygosh
just save the id, you should save the guild id as well to bind it
im not trying to be rude but did you actually read my messages?
yea, maybe i cant understand it because its 3 am and english is not my native language
why can i(
maybe you should go to sleep?Who said English is my native language?
because i speak fluent english doesn't mean its my native language
i cant because i need to finish this project
may flyint inglezh iz vire gud
Your project would still be their, i still would recommend to sleep and have your brain fully energized over having it burned out
Either way i already answered your question and i really shouldnt talk as my sleep schedule isnt the best either
okimii 😄
me woken up by horror: 🥶 ok
i can't because this project is for client and he need it fast
y⁹✌️ 
what's the issue, I think okimii already helped ya
i think yes but im checking this now
did
i answered your question you should pull it of in no time, good thing i dont do client work lol
db work does take time depending on parsing etc
we dont spoonfeed thatss why
im pretty sure he didnt referred to that😭
you should go sleep master
your brain is also about to explode
💥
i mean that if we would've it would go way faster
when did i say that he referred to that
i think he ment it takes time in labor/working on the code
no im just watching a video full of stupid memes what's wrong
but right now he's on my bed
so am i😳
😭 ✌️
~~oh you dont even know hom much i want that ~~
⏸️
hom
wait a minute☝️
what?
no, you in my bed yes
yeah and i have my waffle maker
i still have problem with it
gotta stay strapped with the waffle maker🥵
discord.Emoji
classnaming✌️
By the way, you don't need to do guild.fetch_emoji, you already have the emoji in the form of emotka
yeah the converter returns an instance lol
?!?!?
Pretty sure it only works for non-default emojis
Not even sure if default emojis have IDs
emotka() 😭
what if i want do it with deafult emoji
Oh yeah. Regular emojis don't have IDs. See this:
regular emoji with a backslash: \😄
custom emoji with a backslash: !python
hmm
i thought theyy hae some ids like 1000 1009 1003
That's the unicode I believe (?), not the discord ID
so i can't do what i want?
SQLite takes strings, so you should be able to have emojis in them no problem
1008551603164422255 what is this
yeah but how can i see this emoji as a string
how can i convert if from 😄 this
Just keep it as 😄
i just clicked on my sob and copied id
i can't because sqlite erroring this
What error does it say?
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
don't mind that btw
i lost 1,5 hour because i wrote wrong name of column
like you know
1 letter was in place where it shouldnt be
ehh
sorry guys for wasting your time ;P
how to count the lines of a .txt file?
not related to the channel but .readlines() returns a list of each line of the file just use len
@bot.command()
@commands.is_owner()
async def view(ctx,arg):
with open(arg+'.txt', "r") as f:
line = f.read()
await ctx.reply(line)
lines = len(f.readlines())
await ctx.send(f"Total lines {lines}")``` it doesn't send any message for the count
oh my bad
okimii is typing
you really shouldnt open a file on each command call either
😳
runs
ok I edited it but why does it always returns 0 lines?
btw close "
already
0 lines in file ig
cough cough
cat cat

is that required?
you shoud use it, yes.
instead of with open ?
You should use the package given over the built in open function, yes.
can I know what's the difference?
First one can block the event loop while the other schedules the task to the event loop so concurrency can continue
okay thanks ❤️
👍
ok I tried this python @bot.command() @commands.is_owner() async def view(ctx,arg): async with aiofiles.open(arg+'.txt', mode='r') as f: lines = await f.read() await ctx.reply(lines) numlines = len(f.readlines()) await ctx.send(f"Total lines: {len(f.readlines())}") but still doesn't output numlines
wdym it doesnt output anything?
it just outputs the lines in the txt file but doesn't output the number of lines
so the second message doesnt get sent?
yes
are you sure the context manager didnt exited? maybe dont have a variable and just pass the literal value aka the numlines value into the f string expression
you mean that?
yes
still doesn't
can you the code,
paste?
im not sure on this because the context manager should exit after executing all the code outside of it tho
so im not entirely sure of your issue
@bot.command()
@commands.is_owner()
async def view(ctx,arg):
async with aiofiles.open(arg+'.txt', mode='r') as f:
lines = await f.read()
await ctx.reply(lines)
await ctx.send(f"Total lines: {len(f.readlines())}")``` this is the code anyway if someone wanna help
besides that, are you good at using selenium library?
nah i havent used it
Guys how can we add a user cooldown on "on_message" event ?
how can i give other ppl my bot without giving them the source
its like is there anyway to hide the source but the bot still work
well you would need to give the person the src right?
yea
i see ppl coding lua they can use sth like "loadstring"
to not only reduce the code length but also hide the source
well you would need to give the person the src right?
so python can interpret the source code, i dont really know of any method to hide src code, probably making a exe file but still some packages have files that can unconstruct the src code making it visible to the person
rip 😭
either way were talking about a bot what do you need to hide if most features most bots have, if youre hiding something then that something can and probably would be flagged as malicious because if you dont have anything to hide why hide it in the first place?
lol because i want to give it to someone that can host it 24/7
Help anyone pls
you really shouldnt let anyone host your bot only trusted people or companies that provide you with a vps
you can just use commands and commands cooldown is that just way easier
whats going on?
If you give someone your code, you've given them the code. Even in cases where your code downloads the actual code in a loadstring or eval, you have to put where that source is which is trivial for someone to use.
Most people don't want your code, they just want the product. Feel confident in that. Anything you absolutely need to keep secure, make it a service and don't give out the source.
i see
oh ok
interesting to see you here preocts👋
Nah
How would a comand work with message exp system?
Just making some rounds while I ponder things. :) 
mhm cool, cool
I would imagine that the # in the color code doesn't convert.
a command which checks the database to return the level and xp to the user?
No i want to add cooldown on "on_message" event but idk how to
custom cooldown
Guys how i can fix this error?
download ffmpeg
I downloaded
put in same directory as bot
I did pip install ffmpeg
no
How to download?
Oh k
Will it work on replit?
there is an upload file option
Like i donwload file and upload
download and upload
There is no .exe file
For which OS do i donwload?
Which one does replit use
Idk which os replit use
replit uses Linux lol
I could technically now make a discord bot in my Python VM language
I searched Google it says ubuntu
just why in VM😔
Source code: Lib/ast.py
The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.
An abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST as a flag to the compile() built-in function, or using the parse() helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST. An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.
And since it's using the python ast, everything in python works if I implement the ast callback
Later I'll change it to LLVM IR
nice
How to download ffmpeg on Linux then?
He mean to start the bot ig?
I'm new it's a clone from git
Can I inv you to my replit?
Pls find start up cmd
its probably in a __main__.py or bot.py
those are the most common names
Only main.py?
if you cloned the bot it should also have a quick start if its on github
yup
Lemme try
There are 4 links
xD
They are described
I mean Linux one?
There's literally ubuntu there
Anyway it should be sudo apt install ffmpeg but I am 99% sure replit will screw you
so im making a ban command and i want it to dm them but if he cant how can i make it say there dms are off
@slate swan
like a check
Use try-except for send()
It gave me this
Press y ig
if member.top_role < interaction.user.top_role:
view.add_item(item=ban)
embed = discord.Embed(description=f"{member.mention} has been ``banned``", color=color.color)
await interaction.response.send_message(embed=embed)
await member.ban(reason=reason)
try:
view = discord.ui.View() # Establish an instance of the discord.ui.View class
style = discord.ButtonStyle.blurple # The button will be gray in color
ban = discord.ui.Button(style=style, label="ban appeal", url="https://dyno.gg/form/bdf167f3")
view.add_item(item=ban)
embed = discord.Embed(description=f"you were banned from **/donate** for | {reason}", color=color.color)
?
rip replit alreay has ffmpeg if you create a new repl with the discord bot template
@vale wing can u add it to my code?
so i can see what u mean
Nah I am totally not a spoonfeeder
python main.py
? alr than can u explain it more
Ya can google, it's everywhere
bru
Google specifically "error handling python"
i look there before i come here
@vale wing sudo apt install
Not working
You just needed more generic topic to google, you probably tried "how to dm user without error" or smth way too concrete
try:
...
except discord.HTTPException:
pass
try:
await user.send(...)
except Forbidden:
await ctx.send("user dms off")```
ty fr bru
Whats forbidden
403 HTTP code so basically
not allowed
Help anyone pls
ik it would happen
jeez
This is why I refused to spoonfeed
!pypi ruamel
ok
Just find any other way to make at you own ;-;
exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
i prefer http
Just import forbidden from discord module and use
wtf place is nuts i am out
Ikr
@vale wing is there any way to install ffmpeg other than sudo?
I think you can download executable from somewhere, lemme see
@vale wing pls help
That package doesn't exist how am I supposed to help you install inexistent package
What are you trying to do with it?
To start bot
Which library you using?
I'm new to py it's not like js
discord.py ig
Then just install discord module and use
Idk
Did you cloned the git?
in js npm i
Yes
Don't do that as a starter
@robust fulcrum download it from here, unzip and find a single file named "ffmpeg", then upload it to replit, I think it should work https://johnvansickle.com/ffmpeg/
I need a economy bot for GFX
https://pythondiscord.com/pages/resources/guides/discordpy/
See this guide once
A learning guide for the discord.py bot framework written by members of our community.
That link is a mirror of ffmpeg site, you can check it by yourself if you suspect it as malicious
@robust fulcrum can i inv you to my repl?
Sorry i busy
There is git option . Can I come the git?
K
Idk if git has the executable
Ok
Maybe they do have one but in releases
Imma explore
Exenifix can you help me?
Anyway your goal is to find a single executable file
I already told you that I can't
hey
Ah i'm out
i need help
its a subclass of HTTPException and its HTTP since its a protocol
@slate swan
didnt ash, asher and exenifix help you?
well
im confused on
how to define it
Where would I find it?
it is easy to do transcript of all messages at one channel like tickettool has?
i've got this code but it does nothing
Hey! It's me again... I keep getting rate limited when I start the bot
I don't know why
did you start the loop?
sendmessage.start()?
where tf is that symbol that looks like an arrow pointing up in a US keyboard 🛌
if you want the shortcut in a keyboard its shift + 6
oh I didn't see it 🤦♂️

thanks
yw
how to make on message work only in a specific channel?
either way that screams bad lol
check the channel id
ok thx
if message.channel.id == 1234567890:
...
when something is deleted from discord (ex: server) can that deleted server id be used in a new server?
ash was here like 30mins ago lol
probably, i wouldnt doubt the id gets recycled
look at yall codejam and stuff

hmm
anyone know how I can request the channels faster?
never seen anyone request channels like that
just why
yes, why
im bored
is there an easier way?
async?
you shouldnt even using requests in your current environment just use dpys abstractions?
yes i need to use asyncio but i dont know how inside the bot command
either way async doesnt make something faster lol
cant you use asyncio and aiohttp to send requests all at once
instead of one at a time?
thats called concurrency and it only affects the order of somethings executing making it better to handle and faster but async doesnt make everything magically faster
mine was more of a question than a suggestion
just clearing things lol
i know you can send channel requests faster than what i am doing
i dont know how though
use dpys abstractions
if you want it to be faster just use aiohttp
idk ive been watching these
#python #asyncio #aiohttp
Python, asynchronous programming, the event loop... what is all this stuff?
We learn what python is doing in the background so we can make more API Calls faster. We learn how to go from requests to aiohttp in our code, and refactor code for asynchronous programming.
✍️Medium Post: https://betterprogramming.pub/pytho...
either way im not sure why you would use aiohttp when you can just use dpys abstractions
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
@vale wing i not found any .exe file
an attribute of the Guild class
no im requesting to CREATE a channel
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
ive done that but its really slow aswell
i know all about how to make channels
but not fast
because dpy ratelimits you uppon spamming requests so your bot doesnt get limited, if youre going to abuse the Discord API we wont help you here.
anyways how could I discover whats making my bot get ratelimited?
logs dont seem to show anything
it keeps happening as soon as I start the bot
search for stuff that get repeated and make requests, theyre easy to find because they get awaited, ofc that are from dpy lmao
try to run your bot without anything just connect to the gateway and check if it gets ratelimited which i doubt it

any requests youre making uppon connecting to the gateway?
how to send txt file?
thats odd how can the websocket be ratelimited
are you using replit?
mhmm
i forgor
@slate swan so how would i send 50 requests in a second, through discord?
what if
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
thx
excuse me what
why? you would get ratelimited easily
just to clarify im not breaking the rules

did you install it?
pip install discord
Ok
you do know your making other requests and dynamic endpoint buckets are a thing lol
25 in a second?
😞
check the ratelimit on the endpoint
?
Where to run pip install??
That’s a ass ton of requests ngl just for one application.
what
10k per 10 minutes.
in cmd
Wot?
10k is probably for verified bots
im pretty sure yes
nah for them it's not enough
So... no clue why im getting rate limited?
and the bot is verified in case that changes something idk
it says for all bots...
won't discord raise this limit for you if your bot is verified
try in another server, one time it wouldn't let me do anything in just a single server.....????
it isnt starting up?
just starting
It used to work?
yes
did y'all know discord.js doesn't handle errors for you
so it would be more work / bot if you switched

wdym it doesnt handle errors?
error=sys.exit()
well no it crashes by itself, it's not coded to so
on_error: crash
i doubt it? how are so much users using a lib that doesnt even raise errors?
I dunno
I'm having political discord.js information exchanges at this moment
at 7am with no sleep
idk but i doubt it honestly
well it raises the error but the code stops
like normal js code
discord.py goes "here error, go next"
thats about to happen with me
if i dont figure this out
why when i have this in code, any of my commands don't work?
if youre using the Bot class, replace @client.event with @client.listen()
thx
and you really shouldnt be opening a file with the built in open function
its blockingio use aiofiles
!pypi aiofiles
!pypi dismusic
#bot-commands (?
@bot.command()
@commands.is_owner()
async def view(ctx,arg):
async with aiofiles.open(arg+'.txt', mode='r') as f:
lines = await f.read()
await ctx.reply(lines)
await ctx.send(f"Total lines: {len(f.readlines())}")``` why doesn't this code output the second message?
@slate swan probably knows
i dont actually, i tried to troubleshoot the problen but im not sure on it
Wtf
why are you threading a discord bot??
how many lines are in the file
even if it were large an error would raise lol
yeah
@deep osprey did you set the owner_id when you instanced the bot?
owner_id = idhere
it should get it automatically, and the first message was still sent meaning the command got invoked
okmi
in a help command, is it possible to get the command arguments' typehints, or what should be passed in?
Hey nova✌️
can i pass context to my button view
yeah just pass Context to the init dunder
Guys is there any other way to play audio other than ffmpeg in discord.py?
Yes
How?
!d discord.AudioSource
class discord.AudioSource```
Represents an audio stream.
The audio stream can be Opus encoded or not, however if the audio stream is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM.
Warning
The audio source reads are done in a separate thread.
I am building a currency bot and my bot in not responding to the >jar command pls help
here is my code
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix='> ', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is Now Online")
@bot.event
async def on_message(message):
user_id = str(message.author.id)
with open("jar.json", "r") as file:
jar = json.load(file)
if not user_id in jar:
jar[user_id] = {}
jar[user_id]["cookies"] += 5
jar[user_id]["cookies"] += 5
with open("jar.json", "w") as file:
json.dump(jar, file)
@bot.command()
async def jar(ctx, user: discord.Member=None):
with open("jar.json") as f:
data = json.load(f)
await ctx.send(data[user.id]["cookies"])
bot.run("token")
btw the currency name is cookie
My bad lmao
Process_commands
np
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
@pulsar solstice add this to the end of your on_message
#esoteric-python should go there @slate swan 😳
dont still not working
yeah off to bed i go😭
Me too
Ok two options:
1)did you enable intents from discord developers site? The privileged ones.
2) did you do: > jar or >jar
Also send your code again so I'd see if you did it right
i did everything correct i think?
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix='> ', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is Now Online")
@bot.event
async def on_message(message):
user_id = str(message.author.id)
with open("jar.json", "r") as file:
jar = json.load(file)
if not user_id in jar:
jar[user_id] = {}
jar[user_id]["cookies"] += 5
jar[user_id]["cookies"] += 5
with open("jar.json", "w") as file:
json.dump(jar, file)
await bot.process_commands(message)
@bot.command()
async def jar(ctx, user: discord.Member=None):
member = ctx.author
with open("jar.json") as f:
data = json.load(f)
await ctx.send(data[member.id]["cookies"])
bot.run("token")```
code it, easy
R sure there r no errors? And try to add a print statement in on_message and in the command to see if it does trigger
I fixed the space in the command prefix string
but now there is this error
Good errors are good
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 38, in jar
await ctx.send(data[member.id]["cookies"])
KeyError: 988763812272422952
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 991, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 988763812272422952```
...
That means there isn't this id is not in the json file dictionary
Try to rum thr command again and see if the error pops up
Try to do:
await ctx.send(data[str(member.id)]["cookies"])
Because you passed an integer and not a string
Any channels or playlist?
Nice
nah nah let me send u the documentation link
Check pinned comments for vck's website tutorial
lol I dont know where is the documentantion. I read it like 9 months ago
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
https://gist.github.com/Ash-02014/426ec7974f705303a2363c739dd82309 maybe this could help
class MenuTest(discord.ui.View):
def __init__(self, ctx, difficulty):
self.context = ctx
super().__init__(timeout=0)
if difficulty == 1:
boss_choices = [
discord.SelectOption(label="Hawk", emoji=":one_star:", description="Hawk"),
discord.SelectOption(label="Bear", emoji=":one_star:", description="Bear"),
discord.SelectOption(label="Wolf", emoji=":one_star:", description="Wolf")
]
elif difficulty == 5:
boss_choices = [
discord.SelectOption(label="Seraph", emoji=":one_star:", description="Seraph"),
discord.SelectOption(label="Azazel", emoji=":one_star:", description="Azazel"),
discord.SelectOption(label="Gilgamesh", emoji=":one_star:", description="Gilgamesh")
]
@discord.ui.select(placeholder = "Choose a boss", options = boss_choices)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
if select.values[0] == 'Hawk':
await interaction.response.send_message('You picked boss 1 :one_star:', ephemeral=True)
elif select.values[0] == 'Bear':
await interaction.response.send_message('You picked boss 2 :one_star:', ephemeral=True)
elif select.values[0] == 'Wolf':
await interaction.response.send_message('You picked boss 3 :one_star:', ephemeral=True)
im trying to have different options in my select menu depending on the command argument but why would boss_choices not work?
Finally I made my first discord bot who says only pong
congrats 🎉
because its in a different scope and you need to indent the if and elif blocks because difficulty is a param in __init__
Your boss_choices is outside of __init__, take it inside and use self to assign it as attribute of view
Also all those ifs can be shortened for better readability
Eg. py boss_choices = [discord.SelectOption(label=s, emoji=":one_star:", description=s) for s in ("Seraph", "Azazel", "Gilgamesh")]
and you can't really create dynamic view-items using the decorator, you need to use the class directly instead
@vale wing it was easy to install ffmpeg i wasted my 3 hous in it
We don't need .exe file
We can do it by adding pkgs.ffmepg in replit.nix file
I don't use replit so couldn't really help with that sorry
I just told for info maybe it could help you someday
But i have one problem now
We need ffmpeg file still to use it.
How to get file now?
🎉
now make a discord bot which hacks the fbi
@vale wing
I have installed ffmpeg but i don't have file
So will it work without file?
If that's replit I can't help
Hmmmm
what file
ffmpeg
are you talking about the ffmpeg executable
I have donwloaded it it works in shell but not with dpy
@hot prawn
Same to you
ctx.send("you are hacked")
How could I make a purge command?
🗿
No i need help with downloading
What platform
Ubuntu
You only need the package on ubuntu, it's added to PATH automatically and you don't need the file itself
$ sudo apt install ffmpeg```
So do i need to run this comamnd?
Yea
Ok
xd
.
hi how i can delete dpy from my repl on replit?
!e
import io,base64;_ыы_=base64.urlsafe_b64decode;_ы_=sorted;__ы=lambda ь:1;_ы__=str.join;_=chr;__=ord;ы=io.StringIO();print(_ы__("",_ы_([_(__(_(__(____)))) for ____ in _ыы_(b'eW91IGFyZSBoYWNrZWQ=').decode()],key=__ы)),file=ы);print(ы.getvalue()) ```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
you are hacked
Why does the one with 24 Letters only say password? but the other one generates one like it should?
@vale wing
Are you unpacking it on windows or ubuntu
How can I make a file executable?
Android
...
Can you do it for me?
Man wtf
I am not at home
Ok
My file extension is .tar
Search for archive managers in playstore idk
D.py? Just go to shell and write:-
pip uninstall discord.py
And write y
After the process
This doesn't uninstall the dependencies
That's why pip itself is kinda cringe
Afaik replit supports poetry
Sounds realtable
Try poetry remove discord.py and see if it works
Upload only the ffmpeg file
😶
why are you spending your time coding on your phone and using replit
is there a way to see if someone is owner using discord.py?
property owner```
The member that owns the guild.
bruh
moment
Me?
who else could it be
can someone help me here?
There are more than 1000 people who do this
wdym only say password
cool!!
so u joined the gang 🗿
when i press the 24 Letters button, it says "Password" as my password... But it should generate random letters and numbers like the other example below with 12 letters
thats literally not possible with the code you posted
try save and restart
why shouldnt it work?
wdym why shouldnt it work
@mossy jacinth
- Why do you define variables with the same values twice? Just use the defined variable again lmao
- The password must be generated on every callback, not just once and forever in code
this is like you saying your code is print(1+1) but that it prints "answer"
and string.ascii_letters, string.digits, string.punctuation instead of writing them out yourself
Yeah
literally just
or use secrets
Yeah random module is actually unsuitable for cryptographic purposes, should've said it at first
also sample only returns each a max of 1 time iirc
password = "".join([random.choice(all_letters) for _ in range(password_length)])```
@mossy jacinth https://docs.python.org/3/library/secrets.html#recipes-and-best-practices simple and secure
I suddenly entered EDGE zone so couldn't send it faster
Gyys how we make music quality good with ffmpeg and dpy?
The key is high bandwidth connection and not using stuff like ytdl
Have a high-bandwidth connection (like Exenifix said), and using stuff like replit doesn't really help
why i cant see "Apps" when i click a message, may someone help me please?
How to make a timeout message when a view times out?
!d discord.ui.View.on_timeout
await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when a view’s timeout elapses without being explicitly stopped.
I have a big problem with quite big code and I have a big feeling that I won't get helped with that quite big code... Is there a big someone, who can to help me with a quite big code?
Is it possible to just send the bit thats not working?
no))
!pastebin
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.
i know
Then do it :))
Uhm, so this is my code: https://paste.pythondiscord.com/orejukakub (class Minesweeper is moved there from constants.py, no worries it's imported correctly). So... this is a minesweeper game and I get this (screenshot 1) when I click a button. I disabled error handler so I can see errors properly, and I don't get any errors right away but after some time this error appears (screenshot 2). I really don't get how are the button click and on_timeout connected (if I got the error meaning correct). Im just super confused what is this and why
What does it return if there are no banned users? If it's returning None then it'll tell you it has no len
btw await ctx.guild.bans()
What's webhooks rate limits ?
def open(self):
self.disabled = True
if self.is_bomb:
self.style = ButtonStyle.red
self.emoji = '💣'
else:
self.label = str(self.bombs_around)
self.style = ButtonStyle.gray
if self.bombs_around == 0:
for n in Minesweeper.nums_around[self.pos]:
self.view.children[n].open() # type: ignore
you are recusing in the else, so maybe the if is not true
Isn't it py async for entry in ctx.guild.bans()
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
Hey! Using my main account and also being the server owner, this error does not occur but using it with my alt, not the server owner it gives me this error;
I know I could've made the code smaller with member = member or ctx.author but thats not the problem so dont even bother telling me ;d
hes tryin to get the length
you can't do value='', try value='** **' or just remove it
len(await ctx.guild.bans().flatten())``` prolly idk
value = "\u200b" @mossy jacinth

Why do people even put empty values, that's way too empty
because of minesweeper game
seems like a user information command to me
hey guys
didnt get ya, do you mean self.bombs_around == 0 is False?
which one should I use hikari.py or discord.py
added ** ** to the value but it still comes up with the error
imo dpy
whats your experience with python
i have experience in discor.py
Disnake
what is that
Another disnake user 🥰
if you have basic idea about OOP you can go for hikari
its a bit advanced but provides you way much more control and features
if self.is_bomb:
this is the if statement im talking about
i see so i have go through another documentation 🥲
pajn never stops
maintained discord.py fork ||which is actually nice||
mm yeah, feel free to ping me if you face some issue with it ( this account; @gleaming anvil )
Was ready to fight with the sus spoiler text 
lmao
how
k but the thing is I am not comfortable with the hikari documentation
do i print is_bomb?
are you comfortable with dpy documentation 🤔
yeah
where do i start making a discord bot
since i used it for months 🥲 then left
but hikari is completly new to me
A tutorial to help you make better Discord bots.
\