#discord-bots
1 messages · Page 1078 of 1
¯_(ツ)_/¯
?
Just tell how with jishaku then?
I did tell earlier
Not understood.....
import os
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from webserver import keep_alive
cogs = ["cogs.invite","cogs.quote","cogs.wanted","cogs.purge","cogs.pot","cogs.image","cogs.spotify","cogs.channel","cogs.pie","cogs.eval"]
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='>',intents=intents)
@bot.event
async def on_ready():
print("The bot is ready!")
print("Loading cogs . . .")
for cog in cogs:
try:
await bot.load_extension(cog)
print(cog + " was loaded.")
except Exception as e:
print(e)
keep_alive()
Where I have to put load extension
https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/admin.py#L214-L259 this is a quite simple implementation example, but you need to modify it a bit
you want to send text as a file to discord?
or you want to send a file
You can't put spaces in custom ids can you? 
2 days without sleep in a nutshell
nope
Made a button generator function that i need to rethink a little 
is there a single word i can use for "my art"
if you saying that, I dont know how many friends I have made suffer
lies
Nola
But for 30 mins straight 💀
more
is discord .py still active
probably
yes, it surely is
it does, the master branch on "github" is stable
to use*, though its in the alpha state
Pretty happy with how simple i've gotten this for a lot of buttons
how do i get the permissions of a user that i have the ID of?
A user doesn't have permissions.
cuh
you have permissions right now
Yes because I'm a member in this guild, that makes me a member.
A member has permissions and depends if you want guild specific permissions or channel specific permissions
just guild specific
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
epic
this will return a Permissions object
good
Show yr on_application_command_error
passcontext in a slash command is a new one.
In ur console
the file is main.py in your container folder .-.
why do people use bot.http.send_message
is it because you dont need the channel object?
Yup
yeah it saves a request to the api in case the channel isnt in the cache
how to check member top role id?
!d discord.Member.top_role
property top_role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
then use the id attribute
or top_role
i copy now from my code, i misunderstood at first
how make handle the error ? from on_command_error
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
error handlers can be specific command handler or general command handler, it depends how you want to do it
I want to make a general error handler for lack of rights
BotMissingPermissions does not suit me
What parameters do discord.ui.Button and discord.ButtonStyle take?
@bot.command()
async def my_command(ctx):
#whatever
@my_command.error()
async def my_command_error(ctx, error):
#handling
this is command specific
@bot.listen("on_command_error")
async def handler(ctx, error):
#handling
This one is general, you can put it whenever in your code, even inside a Cog, it will work for every command exception
thx
ButtonStyle doesn't take any
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
There you go, all the params
ty
Rip there's no call back param
Hi, does someone know what would be the cleanest way to i18n (internationalize) a discord bot ?
!d disnake.Interaction.locale is there but it only works for slash commands and context commands
But u gotta manually write the translation for different langs or use a translator module
I'm gonna look at this, thanks a lot
nah you don't call Command.error
why doesn;t this gamble command work
@client.command()
@commands.cooldown(1,30,commands.BucketType.user)
async def gamble(ctx, amount = None):
await open_acccount(ctx.author)
if amount == None:
mbed = discord.Embed(
title="please specify amount",
description="the fellow monkey gamblers are actually betting their money"
)
await ctx.channel.send(embed=mbed)
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount > bal[0]:
mbed = discord.Embed(
title="imagine poor monkey",
description="you cannot gamble that much!"
)
await ctx.channel.send(embed=mbed)
return
if amount<0 or amount==0:
mbed = discord.Embed(
title="do you have common sense.",
description="the gamblers watch in confusion, thinking you are a madman, and kick you out of the casino"
)
await ctx.channel.send(embed=mbed)
return
final = []
for i in range(3):
a = random.choice("X","O","Q")
final.append(a)
slotsembed = discord.Embed(
title="The slots roll down in the machine....",
description=f"The slots in your machine are {final} so...."
)
await ctx.channel.send(embed=slotsembed)
if final[0] == final[1] or final[0] == final[2] or final[2] == final[1]:
winembed = discord.Embed(
title="You Won! :D",
description="Must have the charm of luck with you, you won twice as much as you gambled!"
)
await update_bank(ctx.author,2*amount)
await ctx.channel.send(embed=winembed)
else:
loseembed = discord.Embed(
title="You Lost! :(",
description="Seems like you dont have any luck in you, i suggest not trying again, because you lost how much you gambled."
)
await update_bank(ctx.author,-1*amount)
await ctx.channel.send(embed=loseembed)
nothing happens
no errors
i put amount = int(amount)
I would ask what update_bank or open_account and such looks like but I'll probably find it on youtube
async def open_acccount(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("./data.json","w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("./data.json","r") as f:
users = json.load(f)
return users
async def update_bank(user,change = 0,mode = "wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("./data.json","w") as f:
json.dump(users, f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return bal
Rip
istg I have seen that piece of code a thousand times now
yes this do be youtube code
no when i try a gamble command nothing happens
code here
u got an error handler?
Add debug prints
Are you sure the command got invoked/triggered?
no, no command invoke error occured
icy Cirno u still coding bots btw?
Hmm, then try to print something like hunter said
@tropic burrow turn on logging. u r prolly getting ratelimited
how do i do that
i dont ususally turn it on
and im kinda new replit
I help to code my friend's bot a bit (idk if it counts as coding bots), but I mainly code websites nowadays
Why everyone coding websites nowadays lmao
Cause why not 
Not games, not apps but websites lmao
Advertising games are hard especially if you're an indie developer, as you need to compete against other big games
Agreed
So I choose not to jump there yet
What indie
yet
Me done with eval command finally!
congo, im hoping its not a bare exec/eval function
Lmao
Yes, yet, I'm the type of person who likes to know everything rather than focusing on one thing, so yeah, I'll jump there some day
Alone
Chill, u r not even 16. u r already ahead of everyone else lmao
The younger you are, the more potential you have
yeah that makes sense + solo developing an app would be hectic
So I'm trying to get as much as possible during these ages
Imagine
Don't you?
School takes most of the time, so
7hrs of school
extra classes, homework, exam prep, extra time for these
Ding dong I am also in class 12
welcome to the painful laif
Replace your holiday to code 👍
Already started living it in April
Only if extra classes let me think of a holiday as one
Well nevertheless I am still learning smth new everyday in one form or another haha
Learning never stops
holidays without alot of homeworks is not a thing~
Don't take extra classes 
lemme complete the sentence for you: "Holidays without double homework is not a thing in India"
lmao
I wish
Gotta take care of my grades too
they send attendance on phone/whatsapp so its tough to skip
I gotta write 3 reports of 30-40 pages each and I am procrastinating it lmao
Anyways let's take this to an ot
I can sense someone coming here to warn us anyway
?
✨ Its not a mistake, its a masterpiece ✨

Hahaha its just a small bug where it sends the stdout even when its None
lmao
That is why that line
^^^
bugs are tough to notice sometimes especially codes which have lots of details
Agreed
And then there is me, who won't understand my own code if I open it after a week
🚶♂️ thats why you dont write your own code, just copy paste it from stackoverflow!
pro...
stacks like got all questions answered a-z
0-9
My questions are a bit too complex to get answers from even stack
My questions get ignored on there 😄
Totally not badly worded
lmao sed u need to do some digging to find nearest answer to your question
Ik haha
🤔 i had a question... is it normal for py "[`text`](None)" to show up as None in an embed description?
when i do it manually it shows up as text, but in the code it just says None
Never tried
BTW sarth, study maths
he prolly even finished for jee
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
im done, only calculus left
Why this error?
Lmao
replit.
I tried 
How can I make it so that only a user with the role "..." can press the button? discord-components
Hope why
user.roles
its temporarily
i need check who press the button
nvm, discord moment
if role in user.roles
what was wrong?
desktop:
Lmao my cpu and RAM usage to load a GIF
Android
This is a GIF 💀
notice the None appearing instead of the names on mobile
Discord bug prolly
yep
happens i was once working with pil for embed images checking android when i opened on laptop the images became thumbnail size
i had to resize all my images afterwards...
seems bigger than a movie
got it to fix by using str1 if condition else str2
Lmaooo and the gif is only 5 min long
let me show you the code
wut gif is it?
@client.command(aliases = ["репорт"])
async def report(ctx):
await ctx.message.delete()
if ctx.channel.id == 976776289186906142:
author = ctx.message.author
maincategori = discord.utils.get(ctx.guild.categories, id = 976776105702858802)
reportchannel = await ctx.guild.create_text_channel(f'репорт-{author.name}', category = maincategori)
roleforum = discord.utils.get(ctx.guild.roles, id = 976200603694940201)
rolecur = discord.utils.get(ctx.guild.roles, id = 974282941498814504) #curator role
roleeveryone = discord.utils.get(ctx.guild.roles, id = 853219278945255434)
await reportchannel.set_permissions(roleforum, manage_channels = True)
await reportchannel.set_permissions(author, send_messages = True, read_messages = True)
await reportchannel.set_permissions(roleeveryone, view_channel = False)
embed = discord.Embed(description = f'Шановний учасник!\n\n Напишіть сюди своє питання і чекайте відповіді <@&976200603694940201>', timestamp=ctx.message.created_at, color = 0x6d41a8)
embed.set_thumbnail(url = author.avatar_url)
await reportchannel.send(f'{author.mention} <@&976200603694940201>', embed = embed, components = [
Button(style = ButtonStyle.green, label = "Закрити репорт", emoji = "♻️")
])
response = await client.wait_for("button_click")
await response.respond(
embed = discord.Embed(
description = f'Кнопку може натиснути тільки людина з роллю <@&976200603694940201> і вище.'
))```
https://cdn.discordapp.com/attachments/343944376055103488/981516214578851850/unknown.png
U will see in 5 min 👀
lmao
?
thats an image~
ur rich presence?
make a check in bot.wait_for
Why this comes?
replit?
well. you made too many requests to the API and now you are ratelimited
what can you do? : wait
Requests mean?
you can phrase it as "making the bot do something on discord"
like i call u on phone 10 times in a min u get pissed and block me
MEE6 and Dyno call Discord a million times
Then should i change my host?
just an example😂
imagine discord shutting down all the websocket connections just like i switch off my phone when someone does that
Yes
what host it that, is that some vps?
lmao discord throwing tantrums
Yeah
waiting would be the best choice then
its prolly the only choice...
Lmao
running it on some other device may work, just like you reset the IP on replit
Or just go to your nearest Discord Data Center, start a fire to get discord's attention and then tell them to remove yr bot's ratelimit
No, the API ban is token based

@lyric apex try this
prolly the second best choice out there
If i wait how much time will that take?
first*
do google maps give location of discord data center?
prolly 2 hours
No

just go eat wash and sleep wake up tom everything will be fine
it can be, but your's aint
Just do what u would have done, when u load up GTA 5
lmao
Oop
Its Public Bot So I am 
Haha hi there! Welcome
Hey
hello
nice pfp
Hi ? how can i check member banned with whois? Example:
if member banned:
baninfo=No banned
else:
baninfo=reason
why would a member be banned
!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...
user smh
i have this but i want to check
so i have this:
@client.command()
async def baninfo(ctx,*,user:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
for ban_entry in bans: #Looping through all entries
user = ban_entry.user #Getting user
reason = ban_entry.reason #Getting Reason
thats just discord being dumb
@client.command()
async def baninfo(ctx,*,user:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
for ban_entry in bans: #Looping through all entries
user = ban_entry.user #Getting user
reason = ban_entry.reason #Getting Reason
seems fine
Or they not using the correct lang
whats other langs?
dont think any other language uses list , its mostly array for all of them
python and julia are the only ones im aware of
rs is rust?
wow
yes
mhm
py*
yes i just tested it
so anybody have an idea how to check the member banned or not?
if the member is in ctx.guild.bans he is if not he is not banned
@tacit token
@client.command()
async def baninfo(ctx,*,user:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
async for ban_entry in guild.bans(): #Looping through all entries
user = ban_entry.user #Getting user
reason = ban_entry.reason #Getting Reason
smth like this
u can iterate and check
(I forgot how an async iter works)
he already returned a list of bans why not use that?
because i try a whois what check the member banned or not
Because discord returns an iterator not list
banned_users = [ m.user async for m in Guild.bans() ]``` 🚶♂️
and then you can check if the user is in the list
im a clown but how
!e py print( 1 in (1,2,3))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
True
lst = [ban_entry.user for ban_entry in await ctx.guild.bans()]
this should work as well
Lmao did u try to eval that
Lmao
🥲
soo many bans
?
So i try this:
@client.command(aliases=["hackwhois"])
async def hackuserinfo(ctx, *,member:discord.User,baninfo="No banned"):
bans = await ctx.guild.bans() #Getting a list of all ban entries
for ban_entry in bans: #Looping through all entries
baninfo = ban_entry.reason #Getting Reason
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value=baninfo)
await ctx.send(embed=embed)
i never said that wont work tho
😔 its not await _ctx.guild.bans()
i said this works too u can try
nope it wont
and i how can import this, to my whois command? example in up
maybe, for now it raises an exception py TypeError: object BanIterator can't be used in 'await' expression
any idea?
well, it works in 1.7.3
can u try this
yeah prolly 2.0 then
well then continue as sarth was saying and fetch a list of users
cause in 1.7.3, its a coroutine which returns list[BanEntry]
in 2.0 its an async for returning BanIterator
then just check if user is in the the list with ur member parameter
yeah i got it
i didnt work with mod commands only mostly interaction in 2.0 so...
😔 makes me realise 2.0 is really breaking
i solely used 2.0 just for the interactions
mod commands are meh~
i'd prefer to use a public bot instead of adding mod commands to my bot
otherwise i wouldnt even bother updating
nice is hikari drastically better than dpy?
4x faster + better typehinted + multiple command handlers
4x faster srsly?
try it and see
ty
ok any drastic changes from like normal dpy?
works
Better cache, everything is built so you can make your own impl of each part if you want. Customizable cache as well as working well with intents, doesn't break if discord adds a new field to some object (something that d.py has done in the past). Hikari will support cython speedups for the base impl, which is basically python compiled to C, which makes it run on steroids. Overall, faster than d.py and built to last and be extendable
- davfsa#7026
Consistency, strictness, strong typing, modularity, composition and cache independence is what makes Hikari better than d.py
- vicky5124#2207
lmao i googled hikari first result i got was japanese fish
yeah checking
hikari basically means light in japanese
Hikari is a line of specialty fish food brand manufactured by Kyorin Food Industries, Ltd. in Japan
lmao
how can i avoid this error?
Hi guys how does anyone know how to put a post request and post it to to chats with discord border : python
i have a problem, if i use the command in 1 member the bot list of all member bans
what is your command as of now
hackwhois
@client.command(aliases=["hackwhois"])
async def hackuserinfo(ctx, *,member:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
for ban_entry in bans: #Looping through all entries
baninfo = ban_entry.reason #Getting Reason
lst = [ban_entry.user for ban_entry in await ctx.guild.bans()]
if member in lst:
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value=baninfo)
await ctx.send(embed=embed)
else:
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value="Nincs bannolva")
await ctx.send(embed=embed)
its under the loop... so yeah
it gets executed the number of times there are people banned in the server
any idea?
just remove that loop
u can do for i in lst if i==member
do u have any example?
Is it best to code in js for disc bots
js should have larger userbase than py i think
Not by far.
lst = [ban_entry for ban_entry in await ctx.guild.bans()]
if not member in list: return
ban_reason = ban_entry.reason
``` this are all the fields you need, other stuff is extra
Ask in a JS server maybe?
Are there more JS tutorials than Python tutorials?
Most suggest using JS because a lot of it can be done straight in the browser so it's easier to get started
depends on your knowledge about the respective languages
js is harder than python.
imagine debugging js
Historically, this hasn't really been the case. Most services for this are rather new
ts is nice though
py is easier, libraries like discord.py has inbuilt command handler
True I’m comfortable with both but debugging is a butch
Ahhh gotcha
u can go with what u feel will help u in the long run
Python is like the error is on line 90 man
JS is like error ??
errors in python 3.10 are very specific and neat
more like: undefined
I am still really curious in like, what is the easiest framework. Like- what type of design could create a dead simple framework for beginners...
https://docs.python.org/3.11/whatsnew/3.11.html you're gonna love this then..
rust errors are supreme
I know a lot of people who I'd love to recommend Discord bots, but it's rather difficult anywhere you go and none of the frameworks are designed for beginners really
damn
Python 3.11 is up to 10-60% faster than Python 3.10. On average, we measured a 1.25x speedup on the standard benchmark suite.
this gets interesting 👀
yeah
you can always make your own library 👀
yes but websockets are painn
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'type' is not iterable
@client.command(aliases=["hackwhois"])
async def hackuserinfo(ctx, *,member:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
for ban_entry in bans:
baninfo = ban_entry.reason #Getting Reason
lst = [ban_entry for ban_entry in await ctx.guild.bans()]
if member not in lst:
ban_reason = ban_entry.reason
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value=ban_reason)
await ctx.send(embed=embed)
else:
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value=ban_reason)
await ctx.send(embed=embed)
if member not in lst*
This member never banned but she have ban reason
ive used websockets it not much of a pain (a bit maybe) but i dont know about discords websocket
I have attempted once, which is synchronous and built on threading. It's actually like realky low-level but that is the easiest for beginners.
oh nice
I can just re-use it from my other library!
true that, 😔 you can make a new beginner friendly library then,
im sure many people here will contribute
I've made no progress in like 6 months, but I've had it in the back of my mind but not sure what to do with it.
from simplediscord import * # TODO: Come up with a non-used better name
def on_message_create(event):
if event['content'] == 'Hi':
add_reaction('👋')
run('ABC123.XYZ789', on_message_create)
Here's a code example I've thrown around a few times
event is a dictionary of the event, and those functions there use underlying variables that keep track of the current event which means that you don't need to pass which message (it already knows it is the one that was created)
@slate swan do u have any idea?
so the library still doesnt have models? based on the `event['content']
ah
Yes, I don't think I want to though
lemme recheck your code
I feel like it's easier to teach someone about dictionaries and have them learn it that way. Classes confuse some people, although it's easier to do like x.y yeah
Currently it's better to have models so you have autocompletion in your editor
This is typed dictionaries, they have autocomplete
you can actually just get the member in the list ```py
member: discord.User
lst = [ban_e for ban e in await Guild.bans() if ban_e.user.id == member.id]
then check if the list is not empty
if lst == []: return # the member is not banned
send your embed now
in case you want to get the member's ban entry you can just do `lst[0]`
I believe i had some problems with typeddicts so 😅
if not lst
Oh hi there blue
I am really up for discussing it, because this is a decision I am not still sure about. I know I want to strip out async, decorators, and classes (especially subclassing). I see the benefit of having model classes though 
yes thanks for pointing it out, i thought it would be wrong to use it here since it works for not "" and not None too
Actually using not lst is slower than list == [0] or len(list) == 0
ban_e and Guild should be an instance ( ctx.guild) in your case
yes
how long does it take till my bot go offline in replit (if no command running)
30 min
25-40mins from what i observed
After u close the tab
Not true
Also, besides @honest laurel. There's no typing here because I don't want people to start doing that. Even if it was a class they (the very early beginners who don't know close to anything about Python yet) wouldn't get autocomplete.
Huh?
*mins, my bad
Hi 👋
%timeit not some_list
25.6 ns ± 0.483 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
%timeit len(some_list) == 0
61.3 ns ± 2.37 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
%timeit some_list == []
42.8 ns ± 0.304 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
This is good?
@client.command(aliases=["hackwhois"])
async def hackuserinfo(ctx, *,member:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
for ban_entry in bans:
baninfo = ban_entry.reason #Getting Reason
lst = [ban_e for ban_e in await ctx.guild.bans() if ban_e.user.id == member.id]
if lst == []:
ban_reason = ban_entry.reason
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value=ban_reason)
await ctx.send(embed=embed)
else:
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
embed.add_field(name="Ban info:",value=ban_reason)
await ctx.send(embed=embed)
Of course, one can decide to typehint their functions.
Oo, @pliant gulch u might wanna see this 👀
I think for complete beginners it's better to just... learn python, get familar with classes, decorators, etc
Don't these all involve lookup of globals?
alright thanks
Right, they should, eventually. Should they start with that though? Dictionaries will be something I know people learn semi-early (along with lists) after having learnt about strings and integers
not start, but eventually people should learn these things
Also what's up with globals?
When variables are in locals they can be looked up in an array, this is faster. Test it inside of a function, because the majority of code will be inside a function.
I'm using timeit, not sure if it matters here
We care about difference in timings, not timings themselves
hi everyone! i am trying to fetch the member counts keep on getting an error say {"message": "401: Unauthorized", "code": 0} please help:
reqUrl = "https://discord.com/api/v9/guilds/guild_id?with_counts=true"
headersList = {
"Authorization": "token"
}
payload = ""
response = requests.request("GET", reqUrl, data=payload, headers=headersList)
print(response.text)```
Yup definitely. I feel like they can do that with another framework maybe? Should there perhaps be multiple APIs one can progress through? 🤔
Also the thing with decorators is that it's somewhat simple to learn to place a decorator, but I really want people to learn how and why to do something other than just how to write that thing. Decorators themselves (how to write them) are pretty complicated so I want to not do that if possible.
You need Bot token and not just token
Hi all! What database do you recommend for a small bot? I thought about YAML files since I love their simplicity
i am entering the bot token
How small?
Really really small, just for the fun of developing stuff
files (yaml, json) - idk, you can't go wrong with any sql db though
Yes but there will be a bigger difference. len will still be looked up in globals, which is slower, and will affect the result.

https://stackoverflow.com/questions/72461924/how-do-i-add-to-a-list-using-a-command-in-discord-py any answers?
sorry to interrupt
So should i just add len = len?
Or put everything into functions?
for ban_entry in bans: ?? recheck all your code and try to understand it
your function is meaningless
@minor totem Also wouldn't it have to look up len in locals anyway then? I think not is simply faster here
i don't know i'm very confused with this and i can't adjust to it
lower is a function, you need to call it with parenthesis, .lower()
I understand what you're getting at but you've gone off in all directions here
imagine how your function would work in your head and you will realize the problem normally
Yes, my point was just that some_list == [] will get even more faster than len(some_list) == 0 because len will be looked up in globals.
I got 3 different things to do with it and none of it was good unfortunately so I don't know what I wanted anymore
oh i'll try that
The point is that not is simply more pythonic and is a bit faster
Not that you should worry about speed here...
thank you i am using the bot token here
They meant that you have to insert Bot before your token i think
For example Bot abcdefg...
in discord.py selection row how to find which selection option was chosen?
yes i did the same but it says invalid syntax:
reqUrl = "https://discord.com/api/v9/guilds/guild_id?with_counts=true"
headersList = {
"Authorization": Bot "token"
}
payload = ""
response = requests.request("GET", reqUrl, data=payload, headers=headersList)
print(response.text)```
@client.command(aliases=["hackwhois"])
async def hackuserinfo(ctx, *, member:discord.User):
bans = await ctx.guild.bans() #Getting a list of all ban entries
lst = [ban_e for ban_e in await ctx.guild.bans() if ban_e.user.id == member.id]
embed = discord.Embed(color=0x669999, timestamp=ctx.message.created_at,title=f"Felhasználó információk - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Lekérte {ctx.message.author}",
icon_url=f"{ctx.message.author.avatar_url}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Nickname:", value=member.display_name)
embed.add_field(name="Lérrehozva:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"),inline=False)
if lst != []:
ban_reason = lst[0].reason
embed.add_field(name="Ban info:",value=ban_reason)
await ctx.send(embed=embed)
I think it's better.
"Authorization": "Bot token" where token is your actual token
☝️
Interaction.values ig
oh ok lemme try
tell me if it's good because i wrote it on discord haha
async def callback(self, interaction: disnake.Interaction):
abh = self.values[0]
What I use
OMG TY
or just label and desc is enough
got it, thank you : )
@cedar goblet = King
Does it work?
yess
okay cool 🙂
Just label and desc
the label of the option should be the value, lemme recheck its been a long time i used discord.py
ok thx
try to compare the solution with your old function to understand and find your mistakes
it's better for you
ok ty sir
sir ahah
yes, it indeed is the label of the option
Yes
in view.add_item(select, items) here items is a list?
Not that much difference from what I saw..
Label is the big like title and description is like description
yeah i got it
Why I can't see bold words 💀
Bold
normal
probably related to ur device fonts
Ye ig
!timeit Ah, you are defining the function each time. That might affect it, here's what I was thinking:
def test(l):
return len(l) == 0
test([])
@minor totem :white_check_mark: Your timeit job has completed with return code 0.
1000000 loops, best of 5: 198 nsec per loop
nano sec
how to add items to select row?
Are you sure this isn't just occasional? It looks like a race condition in your library.
Oh, I haven't known much about this timeit command, my apologies
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
the options kwarg
no i mean if u choose a option it sends a certain embed
or Select.add_option
where do I add this embed object
Example
options = []
for sdf in lip:
options.append(disnake.SelectOption(label = sdf, description=anything)) super().__init__(placeholder='Skmething', min_values=1, max_values=1, options=options)
Lip is a list of values
class MySelect(ui.Select):
# your __init__ dunder
async def callback(self, interaction: discord.Interaction) -> None:
# this method is called when a interaction is clicked
I thought he was asking how to add option
hmm ok
It doesn't make a big difference either, hmm
you can access the option that was clicked using self.values[0]
🥲
I literally gave a full-fleshed example 😔 in the morning
question do people still use discord.py? like
import discord```
yeah
yes
i saw a video saying its outdated
not anymore
like this?
the video is outdated as for now
@slate swan
Nowadays things get outdated really fast 
LOL
seems fine to me, do you get any errors?
here is my callback
async def call(interaction):
if interaction.user != ctx.author:
return await interaction.response.send_message(f"**⛔Don't disturb {ctx.author.mention} {interaction.user.mention}!**",
ephemeral=True)
embed = embeds[interaction.values[0]]
interaction.response.edit_message(embed=embed)
AttributeError: 'Interaction' object has no attribute 'values'
seems like discord.py does not have it 😩
does only disnake support that
!d disnake.MessageInteraction.values
property values```
The values the user selected.
why is it like this
hm.
can you try printing interaction.data
yes.
yeah doing that rn
;-;
print something after loading the extensions, and see if they get loaded successfully
{'values': ['Items'], 'custom_id': '2d9c3a0e0c34e0108c7c66b17ebeeaef', 'component_type': 3}
ok
interaction.data.get('values') would do the job of interaction.values for you
yeah...
i wonder why discord.py could not simply add it 🚶♂️
weird though, self.values should work
its not loaded
hm
in disnake, yes, in discord.py no they dont have it
but on_ready is ran
they do
there's Select.values, but thats the list of values in the select, not the selections made by user
bot.start is blocking
?
move the print above that
ok
@slate swan hm
Because discord.py isn't disnake.
Remember they're both different libraries now.
its printed
yeah working now
why do they mention that in their example then???
Where
its self.values not interaction
lemme now try paginating them
but my bot not doing anything
bot.start bugged then ig
:/
thats the point, what they want is the selection made by user, not the first element in the select options
nvm thats it
how do i make it run ;-;
examples/views/dropdown.py line 31
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')```
yeah yeah, i edited the msg
im blind nn
🚶♂️ thats why you dont use multiple libraries
help me after he is done with his problem?
weird though, run it instead of starting it
without the await
so
you should do that in setup_hook instead
Wait how is that causing a failure?
not inbuilt
@loud junco try this
are you subclassing bot or just commands.Bot(command_prefix=...)
remove the last comma after defining Embed
remove the , in the embed var
where can I find the methods available with bot.http?
from discord.ext import commands
class MyBot(commands.Bot):
def __init__(self):
super().__init_(command_...)
async def setup_hook(self): #this function will be triggered automatically on startup and before any event is dispatched, you DO NOT have to run it explicitly
await self.load_extension(...)
await do_more_things_if_required()
```this one?
print(dir(bot.http))
correct
nvm
but i have no idea what to do with that
just load the cogs like you were doing earlier
but i need to await them now
idk how to do them in function
its an async function whats the issue with awaiting there?
sure
command_... what tho
@slate swan
this code that u gave me
from discord.ext import commands
class MyBot(commands.Bot):
def __init__(self):
super().__init_(command_...)
async def setup_hook(self): #this function will be triggered automatically on startup and before any event is dispatched, you DO NOT have to run it explicitly
await self.load_extension(...)
await do_more_things_if_required()
what to write in the ...
command_...
in the callback for interactions can u pass more parameters than just interaction?
ah okay thanks so because this exists, why are the methods that use API calls used?
those methods use these methods
so how would I get back which page the user was on?
use the self and set indexes
i am not subclassing it
Because... 🤷♂️... the real answer is that bot.http methods don't actually return objects (only the payload). It's supposedly considered private API
they look cleaner
you can still assign variables to it
so is it bad if I switch to only that?
how give an example
depends upon your use case
help
select.index = 0
on next page
select.index +=1
on previous page
select.index -=1
what to write in ...
oh ok
the ... simply means "what you should have there" they just wrote some pseudocode
its your command_prefix and intents stuff essentially
If you're only gonna be using the HTTP methods, without the models, why even use discord.py at all?
the init function accepts all the parameters you pass to commands.Bot, self.load_extension() is just bot.load_extension
so what do i write inside
i still dont understand
the stuff you write under commands.Bot
good question...to be honest im not sure what code looks like without using dpy
simple, just make your own api calls
its not but its better to use the library normall, there are things which are confusing
like await bot.http.get_channel(id) you might think that get_channel is an coroutine right?
command_prefix = prefixxx, case_insensitive=True, activity=discord.Game(name="rpm start"),intents=intents
this one?
🚶♂️ its a normal def returning another coro ( self.request ) to be specific
Are you implementing OAuth2 or wanting to only use the REST API? I completely get why one would want to do this, but I am more interested in your use-case.
wha-
there are more tricky confusing stuff inside the http, so ill recommend not using it
what about this
REST API
are there any simple open source projects showing simple examples for a example for me to see?
discord/http.py lines 714 to 716
def get_channel(self, channel_id: Snowflake) -> Response[channel.Channel]:
r = Route('GET', '/channels/{channel_id}', channel_id=channel_id)
return self.request(r)```
@loud junco if I wont get ignored again :')
examples on library abstraction of a discord api wrapper?
i wrote that one the top ...
do you want to make a rest only application?
read the whole message
oo ok
by this it would be like the GET and POST methods right?
yep, you wont be receiving any events
then yes, that's what I want
use hikari then.
(await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py"))
```this?
unlike discord.py, they have a complete different restclient
self.load instead of bot.load
You can use Hikari: https://www.hikari-py.dev/hikari/impl/rest_bot.html#hikari.impl.rest_bot
I've also implemented REST-only with no other strings connected: https://github.com/wumpyproject/wumpy/tree/main/library/wumpy-rest
I still remember making fun of hikari 🥲
cuz u never used it
lets uhh not talk about it now
You can definitly implement it yourself, but ratelimiting is quite difficult!
await do_more_...
isnt a function
ikik
Wait what, this is so odd.
what was the command for delete?
asyncio moment
!d discord.Interaction.delete_original_message
await delete_original_message()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
btw thx for the variable suggestion works perfectly now never new u could do that
asyncio has a method with the same name as a keyword for some reason
class MyBot(commands.Bot):
def __init__(self):
super().__init_(command_prefix = prefixxx, case_insensitive=True, activity=discord.Game(name="rpm start"),intents=intents)
async def setup_hook(self):
(await self.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py"))
#bot-commands for bot commands
Why is asyncio inside of your site-packages?
yw, that works just like botvars and you can do that to any class (only if they dont have a __slots__ attr)
how do i delete it
That's not the asyncio, can't be.
This is replit.com, right? I don't think you can.
i think it is, but maybe cz there's a clone for asyncio on oyoi
pypi*
:/
i download from packages site
!pip asyncio
i hate phone
auto correct
Yeah this is for way older Python versions, before asyncio actually was a thing.
yeah ik bout the classes and bots but never clicked in my mind that select was also a class here dumb me 🥲
is this a package in pypi with the same name space as the stlib asyncio?
as bluenix just pointed, it was for older python versions before asyncio was an inbuilt module
is it fine if u don't add a description in the selection option
python 3.3 to be specific
i dont think that matters
he never said it was?
😔 read the message and that project's description pls
i did
Hm? Yes the asyncio on PyPI is an outdated one designed as the very first asyncio. You should not install it
installs it
This version is only relevant for Python 3.3, which does not include asyncio in its stdlib.
Master repo: https://github.com/python/asyncio
asyncio wasnt a part of stdlib in 3.3
what was used for the purpose that asyncio serves earlier?
remove asyncio from your project dependencies
pyproject.toml or the the tab
can you send me your poetry.lock
so thats not in there, try uninstalling asyncio using pip, if that doesnt work just fork your repo to a new one 🚶♂️
pip uninstall asyncio?
yea
I bet you use 3rd party libs
no they installed asyncio from pip
pointn't
🫂 so you fork it now
uh i mean just create a fork of your repl
what is a fork
where is this
see the image
it's not because of the library
it's a syntax error
you cannot put the word async in the middle of a line
that's old python
but i nvr does that
!pip asyncio the old python
async probably changed it too
they installed this.
what made you think of installing it
oh the syntax error is in the lib
delete pls
me: 
because i dont see it in my packages even i wrote import asyncio
well its a part of stdlib, just like os, random etc etc..
simply uninstalling the library worked for me
but how
yes
pip uninstall asyncio?
yes
try poetry remove asyncio
ok
why poetry
replit doesnt care about pip, so no use
😭 why dont you guys use it
pip on top
uh
Hey everyone, i am trying to get the daily communicator (voice or text) for a community server, can anyone please help with this?
poetry is kinda easier and better to use, its more customisable, you can mention project dependencies, dev dependencies and more seperately and use proper flags to install only the stuff you want
P I P O N T O P
- it works with Venvs so pogg-er
yeah, try running the forked repo now
Guys how can we make custom prefix command with json?
i want to cry @slate swan
Maybe try overwrite poetry?
how
i need the link
Go to #python help and ping python role and ask for help
poetry install ...
poetry uninstall ...
don't. json isnt a database
use an actual database like postgresql or asqlite
i tried
Me actually on mobile
So can't.....
outpt?
hows replit and poetry linked
Bruh cause she/he coding on replit server
so? poetry is not made by replit lmao
And maybe it can be a replit error
Don't argue on such thing
poetry show asyncio
ok
im having little problem can someone help
dont ask to ask
why not just a local ide, its a thousand times better.
this tbh
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
asyncio isnt installed
did you use pip to install or poetry
but me making discord bot
the error.
ok
i use packages to install
spyder is a light weight IDE incase
yes
i dont think it is
he meant the packages tab in the sidebar
I think I do need sleep now
no, notice that its in site-packages folder
It's packager
And yes it's there uninstall option
@loud junco don't use packager to install use pip
i doubt it
Guys is there any database which I can use in my discord bot prefix me asking cause me on mobile
you can use any database, any where until you are able to make a connection to it
they use poetry
Can I use pymongo?
In discord bots
sure, but dont
use motor instead
What motor
thats the weird issue here~
lemme try in my venv
┌──(env)─(sarthak㉿kali)-[~/Documents/testing]
└─$ poetry remove asyncio
Updating dependencies
Resolving dependencies... (0.1s)
Writing lock file
Package operations: 0 installs, 0 updates, 1 removal
• Removing asyncio (3.4.3)
``` worked for me
or even better just use postgresql or asqlite
Bro me on Android
These are only for windows
nope
Can we use the on Android also?
you can use sqlite3 anywhere
@slate swan can you tell mongo is better or sqlite
Ok do you know SQL?
Will you help me if you know SQL cause me at now learning python and cant learn SQL together
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
@bot.command(description='test')
async def group(ctx):
tag = 'group'
async with aiohttp.ClientSession() as sess:
async with sess.get(f'https:/tag/{tag}/popular') as res:
page = await res.text()
tree = html.fromstring(page)
x = random.randint(1, 25)
link = f'https://' + tree.xpath(f"/html/body/div[2]/div[2]/div[{x}]/a/@href")[0]
await ctx.respond(f'{link}')
``` library = py-cord
I am trying to get 1 url from a website using aiohttp but i am having error of
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: IndexError: list index out of range
tree.xpath is an empty list
i tried printing it but it errors in the link statement and even checked the xpath multiple times on the website and its correct
Send traceback?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: IndexError: list index out of range
I mean traceback, not just error
File "C:\Users\Admin\Desktop\pythonProject\main.py", line 45, in group
link = f'https://.net' + tree.xpath(f"/html/body/div[2]/div[2]/div[{x}]/a/@href")[0]
IndexError: list index out of range
this?
Looks like that's an empty list
i checked the website multiple times and its the correct expath and I tried printing the list but it errors out in the link= line
its div[2] the same code was working months ago and now its giving error after I switched to slash commands
help please
nhentai has an API, why not use it instead of webscrapping?
They don't have an api
they used to have one
Not anymore
tf?
@nhentai.command(description='test') 😐
I'm not sure I understand the point of the name
ah, well the wrappers still work, and there's still an unofficial api from the official devs
Maybe you can use css selectors instead? a wrapper for img has a gallerythumb class
Sus
I believe it's still uses webscraping?
i guess yes, because thats the only way to get data without an API
So there's no api then 🤷
@app_commands.command(name = "help", description = "Displays all commands for bot.")
async def help(self, interaction: discord.Interaction):
embed_list = []
for chunk in self.grouper(4, self.bot.walk_commands()):
embed = discord.Embed(
title = "Help & Support",
description = f"{interaction.user} requested for support!",
colour = interaction.user.colour
)
for command in chunk:
embed.add_field(
name = f"`{command.name}`",
value = command.description,
inline = False
)
embed_list.append(embed)
previous_button = discord.ui.Button(label = "Back", emoji = ":arrow_left:")
next_button = discord.ui.Button(label = "Next", emoji = ":arrow_right")
page_counter_style = discord.ButtonStyle
initial_page = 0
timeout = 100
await Paginator.Simple(
PreviousButton = previous_button,
NextButton = next_button,
PageCounterStyle = page_counter_style,
InitialPage = initial_page,
timeout = timeout).start(interaction, pages = embed_list)```
I am making a Help embed pagination but I keep getting error:
```discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'```
I believe it's interaction.response.send_message
ive tried that, i dont think its the error though
I think it is 🤔
Guys is there any way to make per server prefix without database?
🚶♂️ json/pickle files but thats bad
It might be the library I am using, as discord.py-pagination uses ctx not interaction?
Is mongo compass important to use database? Or its possible without compass?
How do I make a bot uptime in Python?
no its not
i mean its not important
Oh
Ok
Will you help me make commmands means i not need all help I'll use my Brain too
from datetime import datetime
bot = commands.Bot(...
bot.start_time = datetime.now()
# whenever you want the uptime use
datetime.now() -datetime.now()```
Amybe he want to know about hosting?
Like we do in replit
well uptime generally means the time for which bot has been running
Ok