#discord-bots
1 messages · Page 1111 of 1
unreal or unity
Java
Tbh I know both java and c# and they are pretty similar but for some reason java is less readable
Probably because of different naming conventions
Both are garbage too
Well ur opinion
No, fact
get over everything and use rust
And flex others that you use rust, also I use arch btw
and also take this to an ot
i use fedora, does that count?
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
file = discord.File("./ImageO/Экономика/Эмодзи/Железо.png", filename="Железо.png")
embed_dict = embed.to_dict()
embed = discord.Embed.from_dict(embed_dict)
embed.set_footer(
text = "| Шахта SK",
icon_url = "attachment://Железо.png"
)
await interaction.response.edit_message(attachments=[file], embed = embed)
Dear, please tell me why it does not see the file, although I checked the correct path in the folders
how to send a interaction.response when a view is shown?
Give absolute path
C:\bot py\ImageO\Эмодзи\Ресурсы ?
Yeah try
Full path
C:/bot py/ImageO/Экономика/Эмодзи/Железо.png
It shud work normally too :thonk:
Hello World
Goodbye worl 😩
hmm i mean i have classed a buttons
classed a buttons.....what
Goodbye Mars
classed a view
subclassed*
YES
ok and what do you mean by "shown"
hmm
You know how I outclass you in good looks
so i send the view like with embed
when the button is clicked?
no i mean
i doubt if this would work, Discord changes the name of the file which are not in English or alnum characters
eh, everyone is prettier than me here, i agree
i wanna the first responded embed from the ctx stay, then send a new embed for be edited with the views
can or cant?
you can, totally can
um how ?
you want to edit the original embed or keep it as it is?
i wanna keep the original
and edit a embed from the view
await ctx.send(embed=initial_embed)
await ctx.send(embed=next_embed, view=ViewObject())
easy as that
oh i got it
so i can just edit the response because num 2 embed
ik" thx
yep
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="Железо.png")
embed_dict = embed.to_dict()
embed = discord.Embed.from_dict(embed_dict)
embed.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://Железо.png'
)
await interaction.response.edit_message(embed = embed)
Dear, it does not give errors, but it does not load the picture in the footer either. help me please
discord python question: how to make my discord bot update its status in real time (every 1min), show in status how many guilds it is in?
@client.event
async def on_ready():
version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(client.guilds)} servers!")
await client.change_presence(status=discord.Status.online, activity=version)
print(f'{client.user} has connected to Discord!')```
@slate swan
you can filename="image.png" and "attachment://image.png" , that will work
Use tasks loop
Negatory
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed_dict = embed.to_dict()
embed = discord.Embed.from_dict(embed_dict)
embed.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.response.edit_message(embed = embed)
Oh, for some reason it also does not display a photo
the footer gets displayed?
nah it doesnt work, its error
yes
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.response.edit_message(embed = embed)
(((
so how to do it?
I forgor
bruh
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
yep
just pass the time to repeat each loop in the decorator
example ```py
@tasks.loop(seconds=10)
no
discord python question: how to make my discord bot update its status in real time (every 1min), show in status how many guilds it is in?
@client.event
async def on_ready():
version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(client.guilds)} servers!")
await client.change_presence(status=discord.Status.online, activity=version)
print(f'{client.user} has connected to Discord!')```
Don't do it in on_ready
look i only want the activity part to repeat, but the last two lines i dont want it to
what do you mean no
Change activity in tasks loop and set presence in bot constructor
wait
they will have to use a task loop for this
yes
just put the code you have in the oin_ready function except the print statement into the task loop
on*
why does it have to be in task loop?
cuz it can crash the bot
doing API calls on the on_ready is not good
and also how would code which is put on on_ready repeat every one minute
like this?
@tasks.loop(minutes=1)
async def bot_servers():
version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(client.guilds)} servers!")
await client.change_presence(status=discord.Status.online, activity=version)
bot_servers.start()
#on_ready
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')```
Yes
Unhandled exception in internal background task 'bot_servers'.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 48, in bot_servers
await client.change_presence(status=discord.Status.online, activity=version)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
error @grim oar
r!whois and wdym how do you use it
Aaa
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
You probably need to use it like r!whois User#1234
Yes
put this where
If you typehinted the argument correctly
Put that right below function declaration
where?
async def f():
await bot.wait_until_ready()
...
i assume his bot instance is client so just change that when using that code
Yes
Unhandled exception in internal background task 'bot_servers'.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 47, in bot_servers
await wait_until_ready()
NameError: name 'wait_until_ready' is not defined
still error
client.wait_until_ready
it's a method of commands.Bot
Warning (from warnings module):
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 47
client.wait_until_ready()
RuntimeWarning: coroutine 'Client.wait_until_ready' was never awaited
Unhandled exception in internal background task 'bot_servers'.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 49, in bot_servers
await client.change_presence(status=discord.Status.online, activity=version)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
np
Does that even change anything? Putting await...
That error means the bot isn't even ready lol
yes and awaiting wait_until_ready will make it wait until the bot is connected
i’m stoppid
that work, but then how i can change the embed based on the view?
eh nvm i think my fault
wait
Slash command important for bots?
like when a button is clicked, you want to change the first embed?
If you plan on expanding your bot and going big, yes
Big?
it's not important important
it's just recommended since slash commands are based on webhooks not messages
slash commands are into the light due to the discord api privileging message content.
so, all your normal commands such !ping/.ping/etcetera (ext.commands) are basically advanced on_message commands
and that's why they will stop working until and unless your bot gets approval for the message content intent from discord
Ok thanks
Note that this does NOT apply to unverified bots, they will continue to work as usual
nice
Sorry i need an explanation
how does a thread join?
Anyone here have any experience with PyCord?
i made some slash commands for my Discord Bot, and for some reason they're only visible to admins
if no slash command, discord didn't verify my bot?
no they can
@slate swan
3rd last message
this is when a member joins a thread
no
ew
this is
?
hm I see
Not true. My bot doesn't have even a single slash command, still they verified it last December
Ok sir
That was before they were enforcing was it not?
I meant December 2021, they started enforcing slash commands before that
that's common sense.....
Or was it Jan 2022? I remember my bot getting verified just a day before discord staff went on a holiday
No? It's going to start being enforced September 1, 2022
Ah, I meant when discord announced that message content gonna be a privileged intent and forced suggested everyone to move to slash commands
There was this rumor that time that discord won't verify your bot if it doesn't have slash commands and apparently a few people still dk that it's false
Indeed
https://support-dev.discord.com/hc/en-us/articles/4404772028055-Message-Content-Privileged-Intent-FAQ
for all the details
As the popularity and number of Discord bots grow, it's important to keep our users and developers safe and healthy. This means from time to time, like any maturing platform, we need to update our ...
i think my bot is accidentally calling from the wrong library, how do i fix this?
wdym
@has_permissions(manage_guild=True) # Guild managers only.
async def setrank(ctx, username, rank: int):
if 255 >= rank >= 1: # Make sure rank is in allowed range
group = await roblox.get_group(9258046) # Group ID here
member = await group.get_member_by_username(username)
await member.setrole(rank) # Sets the rank
await ctx.send("Promoted user.")
else:
await ctx.send("Rank must be at least 1 and at most 255.")```
its supposed to call from roblox library
instead it calls from discord library
error:
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\DiscordBot\main.py", line 53, in setrank
await member.setrole(rank) # Sets the rank
AttributeError: 'MemberRelationship' object has no attribute 'setrole'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: 'MemberRelationship' object has no attribute 'setrole'```
The member of roblox api wrapper doesn't have setrole
isn't it the discord one?
because its discord.ext.commands.errors.CommandInvokeError
that doesn't matter
CommandInvokeError wraps all the errors
ohh
alright so i need to find the substitute for setrole then right
Yes
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.response.edit_message(embed = embed, view=None)
await asyncio.sleep(2)
embed1 = discord.Embed(
description= "Проверка пройдена. ожидайте подписи генерального директора...",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.response.edit_message(embed= embed1)
Dear, tell me how to fix the change error
You can only respond to a button once
Is there any way to answer more than once?
Well, it's good that there is an opportunity)
you can use interaction.followup.send
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
or interaction.edit_original_message if u just want to edit the message again
work!!!! thanks
❤️
❤️
👍
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.response.edit_message(embed = embed, view=None)
await asyncio.sleep(2)
embed1 = discord.Embed(
description= "Проверка пройдена. ожидайте подписи генерального директора...",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed1.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.edit_original_message(embed= embed1)
await sleep(2)
embed2 = discord.Embed(
description= "Поздравлю ты шахтер",
color= 0x00b300
)
file = discord.File("C:/bot py/ImageO/Эмодзи/Ресурсы/Железо.png", filename="iron.png")
embed2.set_footer(
text = " | Шахта SK",
icon_url= 'attachment://iron.png'
)
await interaction.edit_original_message(embed= embed2)
Oh, why doesn’t he want to change 3 times? (
make a counter or something and at each counter increment the message is edited
Oh, exactly 😅 ... how embarrassing sometimes for your inattention
Hi people !
Hi 👋
👋
how can i get the activity name and the time a user has been playing a game for
like if im playing fortnite
i wanna get the name of the activity and the time ive been on it for
member.activites
alr ill check it out
I need your help on a serious concern.
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
Here's a link explaining what I need to solve the following problem:
I'm storing pairs of discord IDs in a table, as 'main_id' and 'alt_id'.
When you use !showalts <ID>, the command should get a list of all connected pairs, which would represent all the accounts a single person uses (all accounts stored in the table of course).
With python, this could be very slow especially due to many users using the same bot for these requests. So my question is: Did one of you achieve such a thing and can give me some clues on what approach I should use?
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
thanks
is there an example
i cant find any examples anywhere
it's a list i think just print it and parse
what is alt_id and main_id for?
just use a db, why do you think python would be slow? any particular reason?
storing a person's alts so when you research someone with a command using the id, it shows all their alt accounts
what db are you using?
I'm using a DB already. Python would be slow because there is many command runs simultaneously and python is generally slow. The command itself won't be slow, but the async code being ran by too many people at the same time will cause overloads.
sqlite DB
is it async?
how many people are running the command at the same time?
depending on the times could be few hundreds
wdym the database is async?
can you show me the code of the command
like if the lib u r using to interact with the db is async or not
what command? The code is split around many files, what part do you want to see?
where you interact with the db
oh I'm using sqlite3 lib
def db_add_alt(arg):
con = sqlite3.connect(os.path.join(BASE_DIR, "salus.sqlite"))
cur = con.cursor()
alts_add = 'INSERT INTO alts(scammer_id, alt_id) VALUES(?, ?);'
if arg['alts']:
for alt in arg['alts']:
alts_payload = (arg['subject_id'], alt)
cur.execute(alts_add, alts_payload)
con.commit()
cur.close()
con.close()
return True
ya see, thats sync
Here's what I use to store the alt accounts in it
thats ur problem, not python being slow
Ok so getting a list from pairs of tuples is not slow on python?
!pip aiosqlite
@cerulean folio use this ^
or postgres....
ya there are multiple async-dbs, thats the first one that came to my mind, you can pick the one you like 😄
Aiosqlite is really good if you're making a small bot. If you're making a bot that is supposed to be added in 10k+ or used too much, then postgreslq will do
I see...
!pip asyncpg
I'm scared to switch tbh
XD
carl?
carlbot
sqlite isnt bad tho?
who said it is?
no i mean if u have a big bot is there reason to migrate from sqlite3 to any other?
yeah, what if those files get deleted?
oof
I mean, why are you even asking that...
curios lol
in case of a hosted db like mysql or pgsql that wont be the case.
you can back up the data
i migrated from sql to postgres by doing that
RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
Anybody knows why?
async def load_extensions():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
#.....
async def main():
async with client:
await load_extensions()
await client.start('token')
asyncio.run(main())
Anybody an idea?
still not just relying on the sqlite module right
you need to await the add_cog now, setup would be an async function
await add_cog in your cogs' setup function
wdym
So basically async def setup(client): await client.add_cog(user(client))
In every cog?
yes
Ok then call it with asyncio?
postres is also sql....?
well, user is neeeded to be replaced by the class name but rest is fine
no nothing
async def setup(...):
await add_cog(...(...))```
changing databases
i mean, isnt using a database on a permanent server is easier than using it as a backup?
blue await 
when you forgor the :
i liked it like that 😩
why change
I didnt forget 😔 I'm on phone and I mistakenly pressed backspace instead of newline
yea it is, but if you want to migrate from one database to another, you can backup the data from the previous database and just copy it to the new one
totally doesnt happens to me
async def setup(client):
await client.add_cog(user(client))
asyncio.run(setup(client))
So i basically did this but it says missing argument client
u dont asyncio.run setup function, its loaded by load_extension
yeah i did that while migrating to mysql
@shrewd apex
does the member.activity only work with spotify?
activity = discord.utils.find(lambda activity: isinstance(activity), self.member.activities)```
or would somethin like that also work
no
isinstance takes two arguments, the instance and the main class
or can i do
what are you trying to do?
Can someone help me I don’t get this
message.author == client.user:
What does this mean in discord’s api I’m reading through it nd I don’t get it
message.author means the user who wrote the message, client.user basically means the bot itself
and ur checking if they are equal
just making a troll command to ban a user if they play league for more than 30 minutes
just testing with this but would this work
how would i get the timing
That’s one useless thing lmfaooo
loop over acitivites, LOL might be under some other acitivity they might be doing
💀
why would i need to loop over it i just needa ban if its league
wtf
its for the cause
Ohk
But i still don’t get why they r using it here
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('your token here')
Why do they need to check if the author nd client is = what’s the logic
they basically dont want to say hello if the bot said $hello in chat
what even
you aint even checking any member, its ctx.guild.members, not ctx.guild()
Ooo yo i didn’t through of that
frick!
i forgot the syntax i havent done dpy in months
Thanks
He said the no no word
You can check when they started and see if its over 30 mins
just dont use replit
how would i check when they started
it does lol, but still dont use it
member.activity.timestamps
its a shit bot that ima use for like 5 min utes then throw it away 😭
thanks
!d discord.Game.start and subtract it from the current time
property start```
When the user started playing this game in UTC, if applicable.
This also works
all i like discord.py for is the Spotify class
But since you already have the check, if you use mine it will work fine and if you use that it will work fine also
does discord.game.start return seconds
that's still ew
no, datetime.datetime object, imagine reading the docs
💀
i dont read docs mb
😔 docs are bad
agreed
Hello,
maybe someone could help me and tell me how to implement this Javascript code in Python.
Mine returns in milliseconds if that helps idk
yeah it does
i aint gonna read docs for datetime
forgot how that stuff works
this not related to discord bots, take it to a different channel
ion see docs for timestamp
Nvm its the same
the code is from a discord bot so I should actually be right here
😭
The output you get from what Ashley sent and what I said is the same, so it doesn't matter
i hate datetime
Same
What did it print
no, they are banned
Lol
formats like this
you can just ```py
@commands.command()
async def foo(context: commands.Context): ...
_bot.add_command(foo)
Ok so we just want minutes and hours from that
Do you want to ban ppl that are playing league for over 30 mins right?
yea
Ok then we just want mins
In range(60).
^
Hours don't matter cuz we only have to check the mins
wait no, you're using start, subtract it from datetime.datetime.now() to get a datetime.timedelta object and use minutes on it
!e ```py
from datetime import datetime as d;
import time;
start = d.now()
time.sleep(5)
now = d.now()
td = now-start; print(td)
print(td.seconds)
see its a timedelta object when you subtract them, you can get seconds and convert it to minutes or whatever you want
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 0:00:05.024657
002 | 5
☠️
why are you using ; after imports
java and python gettin mixed up
i was initially thinking to import it in one line
ah i see
and ; is not a java thing, thats something 80%+ of languages have
out of the really used ones
ah i see
!e
import datetime
e = datetime.datetime(2022, 6, 20, 18, 4, 46, 971000)
print((e.now() - e) > datetime.timedelta(minutes=30))```
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
True
^
so if this is true
then ban
Yes
time = datetime.datetime.now()
if (time.now() - time) > datetime.timedelta(minutes=30):
...
no~
oh what
time will be user's activity time start.
oh you right
one second
Can I accept images in slash commands??
im not even sure what im doing at this point but py time = datetime.datetime.now() start = member.activity.start if (time.now() - start) > datetime.timedelta(minutes=30):
u can just do start.now()
ya datetime returns self
time.now() - start.now()?
no start.now() - start
oh
?
if (start.now() - start) > datetime.timedelta(minutes=30):```
ah you mean that, i thought you were asking to use start.now() instead of start
need to check
@bot.command()
async def check(ctx):
for member in ctx.guild.members():
start = member.activity.start
if member.activity.name.lower() == "league of legends":
if (start.now() - start) > datetime.timedelta(minutes=30):
await member.ban(reason = "Playing League")
```
Um can u pls
members is not a callable
just typehint an argument to discord.Attachment
oh one second
What 💀
image: discord.Attachment
the thing in front of : is called a type hint
if they are someone using discord-py-slash-commands im out 💀
async def ...(args, image: discord.Attachment):
i think thats what he sayin
yessir
Alr
im not sure what you mean
Idek what I'm using at this moment tbh
remove parens from guild.members(), its a property
def foo(): pass
foo() # callable
bar = 1
bar() # you cant do this, its not a callable
Im just laying on bed and started wondering if this was possible or not lmao
ohh
thats how you do that in discord.py, this differs with what library you use
got it thanks
Ooo not using nextcord and all just the old one
is it possible to make a command that determines whether a user is on mobile or not?
!d discord.Member.mobile_status
property mobile_status```
The member’s status on a mobile device, if applicable.
is_on_mobile if you;re looking for the
icon specifically
ok
Hey how I can set a bot more than 1 prefix?
how would i do something where when a reaction gets to 5 it does something
pretty sure u can just put a comma
i want to do a public vote for the banning 💀
Say
client = commands.Bot(command_prefix='+', '!', intent=intents)
command_prefix = ("prefix1", "prefix2")
yea
Oh
pretty simple :)
I was think it's hard xD
lol
i thought it was a list
how can you give permission to a role?
Role.edit
ok
doesn't work
@client.command()
async def op(ctx):
role = await ctx.guild.create_role(name=f"{ctx.author.name}", color=0xffffff)
await role.edit(administrator=True)
await ctx.author.add_role(role)
embed.add_field(name = f"User: `{member.name}`", value = f"{member.name} has been playing `{member.activity.name}` for {d}")```
tryna do the datetime shit where it shows the time like for example:
! has been playing `League Of Legends` for `33 minutes`
@paper sluice do you know how to format it
Use member.activity.created_at
I believe you can subtract current time and member.activity.created_at to get a timedelta object
gotcha ty
How can i get number of online members on server?
You can use guild.members, and filter users who are online
Something along the lines of
[m for m in Guild.members if m.status == discord.Status.online]
how?
new_list = [(0 if str(x.status) == 'online' else 1 if str(x.status) == 'idle' else 2 if str(x.status) == 'dnd' else 3) for x in ctx.guild.members]
online, idle, dnd, offline = [new_list.count(x) for x in range(4)]```
ok
you can use something like that
i'll try
What the hell lmao.
hey how i can set role id for a cmd
works nicely lmao
He literally just wants a list of all the online members. Whatever you have is over complicated
heyyy how i can set a role id for a cmd and only that role can use ittttt
he asked for the amount of online members
Then call len on that list
it doesn't work good, i get raw json
Call len on it and try again
or something like that
so put it in len?
you can use mine and just call it like await ctx.send(f"Online: {online}")
No. That’s just a list.
heyyy how i can set a role id for a cmd and only that role can use ittttt
add a check in the command
how
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@warm tulip ^
you can use @commands.has_role("name")
hmm
"name" of the role
I knew it would. There’s no need to overcomicare things.
cant i use id
im sure u can
@commands.has_role(id)
@bot.command()
async def...
for this import commands from discord.ext
ye
you mean something like : @commands.has_role("2828398283", "22434343434")
no
💀
dont use ""
ohhh
i literally have no idea what other events would raise that error
@commands.has_any_role(2828398283,22434343434)
has_role is for one role and has_any_role is for multiple
its not about the spaces its about has_role and has_any_role
@commands.has_any_role(2828398283, 22434343434)???????
yes
and that will work if the user has one/all of those roles
ok
you can list 3 roles there and the user can have 1 of them and still have access to the command
worked
thanks
can someone pls tell me how to create a noob decatetor
i mean they type !noob and bot will say randomly a number between 1 - 100% and ot shows the user % noob
like you say !noob
the bot :
you are 49% noob
use random
howwwwwwwwwwww
!e
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
random.randint(...)
💀 tell me all of that XD
!e
import random
percent = random.randint(0, 100)
print(f"{percent}%")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
58%
ok
^^
why are you doin it like taht 😭
XDD
is that in a cog?
💀 im new
why u doin print asw
whats cog
okay so its in a cog
import random
@commands.command()
async def noob(ctx, member: discord.Member):
await ctx.send(f"{member.name} is {random.randint(0,100)}% noob.")```
you can do something like that
lmk if you dont get a part of it
i imported random at top
yeah tahts fine
no just import it once
Could we not spoonfeed in the future please? Thank you 🙂
wait a min
alr mb homie
! whats the cmd name
its noob
n!
then its n!noob
its not working
where did you put the code
What do you mean by "not working"? Be more specific please
send the entire file contents minus anything private
in a pastebin or something
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
when i use cmd it will not send anything
Have you got any errors?
ya
😭
Those would be incredibly helpful
wait a min
wym
send them
Could we see the errors?
It's almost impossible to tell what's wrong without any code or errors
ok wait
Ignoring exception in command noob:
Traceback (most recent call last):
File "/home/runner/Negin-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/Negin-Bot/commands.py", line 39, in noob
await ctx.send(f"{member.name} is {random.randint(0,100)}% noob.")
AttributeError: 'Commands' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Negin-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Negin-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Negin-Bot/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: AttributeError: 'Commands' object has no attribute 'send'
^C
AttributeError: 'Commands' object has no attribute 'send'
Ah wait, is this inside a cog?
can you copy paste your entire file and paste it here http://hastebin.com/
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah commands.py
LIterally theres nothing else to know
not sure if they set it up correctly
Then your first argument should be self
^^
cant i type it in your dms?
@commands.command()
async def my_command(self, context: commands.Context, ...): # notice how self is first?
...
you can
copy and pasted this and expected it to work with no problem. This is why you dont spoonfeed
you create more problems and dont help anyone learn anything.
mb homie

😭
im learning rn
Doubtful. You didn't even know what the relevance of the error was.
Learning python as a language first may serve you well in the short and long term
You may want to go and do that first
I don't mean to turn you away from discord bots, but discord.py and discord bots in general aren't really all that beginner friendly. You're only going to be hindering yourself if you jump in without much python knowledge
ay could i possibly get help with something
so actually
let me try some stuff and ill lyk
Paste any relavant code and errors, and I'll see what I can do
well okay so basically im tryna make a command that bans anyone playing league for more than 30 minutes
and just for some fun im doing it so it pings everyone in a channel and does a reaction thing where if it gets 5 reacts then it bans the person
I've seen that meme before haahaha
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah sadly it didnt work
ah wtf 💀
let me find a pastebin that doesnt make you download
Have you considered using on_member_update event?
You should check if that member has been doing a certain activity for a certain amount of time there
import discord
import datetime
from discord.ext import commands
def setup(bot):
bot.add_cog(league(bot))
class league(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.channel = 980250201723899914
@commands.command()
async def check(ctx):
for member in ctx.guild.members:
start = member.activity.start
if member.activity.name.lower() == "league of legends":
if (start.now() - start) > datetime.timedelta(minutes=30):
channel = bot.get_channel(channel)
embed = discord.Embed(title = "League Detected", description = f"{member.name} has been playing `{member.activity.name}` for over 30 minutes!")
await channel.send(f"@everyone 5 Reactions to ban {member.name}")
message = await channel.send(embed=embed)
await message.add_reaction("a:tick:912173533151514655")
await member.send("You have been banned for playing league of legends.")
await member.ban(reason = "Playing League")
@bot.event
async def on_reaction_add():```
well thats what i did so far
now i needa do the reactino stuff
Right, but looping through every single member on command doesn't seem ideal
Wouldn't you want it to be automatic?
i would
i was just doing this for testing and gonna figure out how to do it automatically later
In that case use the on_member_update event
cause ion wanna do a command either
First things first it should be start = member.activity.created_at
oh shi alr
You can also get the current time using the following:
from datetime import datetime
now = datetime.now()
so datetime.now() - start?
now - member.activity.created_at should return you a timedelta object
datetime gives me aids
Then use .seconds on the resultant timedelta object, and extrapolate the minutes from that
Check if minutes is greater than 30, perform any given action depending on that
😭 i understand what you are saying
im just confused on how to do it
and im also confused on how to implement on_member_update
@commands.Cog.listener()
async def on_member_update(self):
for member in ctx.guild.members:
start = member.activity.created_at
if member.activity.name.lower() == "league of legends":
if (datetime.now() - start) > datetime.timedelta(minutes=30):
channel = bot.get_channel(channel)
embed = discord.Embed(title = "League Detected", description = f"{member.name} has been playing `{member.activity.name}` for over 30 minutes!")
await channel.send(f"@everyone 5 Reactions to ban {member.name}")
message = await channel.send(embed=embed)
await message.add_reaction("a:tick:912173533151514655")
await member.send("You have been banned for playing league of legends.")
await member.ban(reason = "Playing League")```
so would i add a second arg
as member
@bot.listen()
async def on_member_update(before: discord.Member, after: discord.Member):
...
You can probably guess what's going on. If you can't before is the member object before the event happened, after is the object after the event happened. Pretty self explanatory
If it's inside a cog, self should be the first argument, that goes without saying
bot.listen() is the equivalent of @comands.Cog.listener(), outside of cogs
oh gotcha
in this case of a command why would i need before and after wouldnt i just need something like member: discord.Member?
It's an event, not a command
how would i use them though
see here
In your case before doesn't matter all that much, just check if after activity is what you want (league for 30 minutes)
The event runs every time a member's profile updates (including when an activity "ticks up" meaning they've been doing the activity for example, from 17 minutes to 18 minutes)
ahhhh
that makes so much sense
would i switch the member to after?
so like start = after.activity.created_at
Yup
gotcha
If you really want to you can also check if before activity is LoL and has been playing for < 30 minutes or 29 minutes
Good idea, get the core functionality and figure out the extras later
do you know why my thing is tweaking
You probably meant to write self.bot.get_channel(self.channel)
ah alr
repl...........
yea im like out of it today
Anyway, I've gotta run now. If you've got any more questions ping me with em and either I or someone else will help you out later
short term project 💀
alright man thanks for your help cya
@discord.ui.button( emoji = f"{e_checkMark}", style=discord.ButtonStyle.green, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
description= "Проверяем вас на судимость наличие должности в другой компании..",
color= 0x00b300
)
img = Image.open("./ImageO/Экономика/Work/Договор_Железо.png")
url = str(interaction.user.display_avatar)
url1 = requests.get(url, stream = True)
url1 = Image.open(io.BytesIO(url1.content))
url1 = url1.convert('RGBA')
url1 = url1.resize((152, 152), Image.ANTIALIAS)
url_m = Image.open("./ImageO/Экономика/Work/Маска_для_авы.png").convert('L')
img.paste(url1, (165, 160), url_m)
img.save("./ImageS/Договор.png")
file4 = discord.File("C:/bot py/ImageS/Договор.png", filename="D.png")
embed.set_image(url= 'attachment://D.png')
await interaction.edit_original_message(attachments = [file4], embed= embed2)
Dear, tell me what could be the problem? The name of the mask is exactly the same
Ask in #media-processing, this question is out of scope for this channel
How to convert milliseconds to something like 4:20 (4 minutes, 20 seconds)
Or there 2:40:03.
?
timedelta is your friend
I tried
mhm, that's good
can you print search.duration?
204200
you can also make a datetime out of it
datetime.datetime.fromtimestamp(search.duration/1000.0)
milliseconds
woops, that's not
>>> from datetime import timedelta
>>> t = timedelta(milliseconds=204200)
>>> print(t)
0:03:24.200000```
Here is what it outputs
so it's 242, not 24200
Sorry I got confused
anyways, since the ms is under 1k, you could just display 242 ms
seems pretty readable to me
would u guys be interested if i did a tutorial on making a level system something like mee6
where it creates the img and all of that and sends it
https://discord.com/developers/docs/topics/oauth2#client-credentials-grant is this what i use so the oauth user token wont refresh?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
if it's written, you could try
wym by if its written
if your tutorial is a video and people have optimization suggestions, you can't edit it
i am so confused but ok
Not a fan of discord bot tutorials to be honest
Or tutorials in general
true me neither
might just optimize it and upload it on github
as the code looks very beautiful right now
@client.command()
async def banner(ctx, user : discord.User = None):
user = ctx.author if not user else user
req = await client.http.request(discord.http.Route("GET", "/users/{uid}", uid=user.id))
banner_id = req["banner"]
if banner_id:
banner_url = f"https://cdn.discordapp.com/banners/{user.id}/{banner_id}?size=1024"
myEmbed = discord.Embed(title="Banner", color=discord.Color.from_rgb(54, 57, 63))
myEmbed.set_author(name=user, icon_url=user.avatar_url)
myEmbed.set_image(url = banner_url)
await ctx.send(embed=myEmbed)
this command works properly, but gif banners dont work
and for default banners
oh wait wrong script
How can i request the application commands of the bot?
url generator and click bot and application cmds
no like request them.. to get the application commands ids
i have to manually delete 2 commands
wait i deleted the link omfg
lol
help plis
?
Show code
async def msg(ctx,*args):
message = ""
for word in args:
message += word+" "
await ctx.channel.send(resp.text)
resp = reqs.get(f"https://mcapi.xdefcon.com/server/{message}/motd/text")
content = resp.text
stripped = re.sub('<[^<]+?>', '', content)```
message isnt defined
what the hell is the point of
message = ""
for word in args:
message += word+" "
and message isnt a global variable
@slate swan i suggest doing
message = ' '.join(list(args))
Hi ppl, I don't know why my task loop doesn't run on my Linux Server. But on my normal Pc it works normally.
The Bot itself works but just not the Loop. Here's the code:
async def channelclear():
print("This is not even printed out.")
await bot.wait_until_ready()
await asyncio.sleep(5)
while True:
# difference_time definition and stuff..
if difference_time >= timedelta(minutes=10):
print(f"Purge begins now. ({time_now})")
await bot.pic_chat.purge(limit=10000)
await bot.pic_chat.send("Channel purged.", delete_after=15)
Seems like a wonderful way to get ratelimited and banned
Do you really want to be sending API requests inside a while True loop?
looks like he is doing it every 10 minutes
It shouldn't matter as it's still a while true loop
i dont see the issue can you explain?
You're sending API requests inside a while True loop
What should be the minimum then
It's gonna get them ratelimited and potentially temprarily banned
I believe it's 5 requests/5 seconds?
It does change depending on bot size though
Different endpoints may have different rate limits as well (e.g you can edit a channel name 2 times/10 minutes)
So it shouldn't be a while True instead a loop that runs once every 5 seconds for example
but he is making API requests every 10 minutes? atleast its what it looks like
Yes that'd be a better idea
No, they're making one constantly, every few milliseconds
Would be a asyncio.sleep of 5 seconds after the while enough?
I suppose but I don't see the point of a while True inside a loop?
^
my general problem is that the loop is not even run
I have a feeling it has to do with the while loop
discord probably filtered you out as spam or something
Also not sure if you're leaving out the necessary decorators and the .start() method on purpose or just don't have it at all
loop.create_task(channelclear())
I have this at the bottom
and it worked so far everytime. Since I moved it into my Linux Server it seems not to be working
Let me get something straight, are you asking for help with discord.py's tasks extension or asyncio's create_task?
If this is indeed a discord.py tasks extension issue then you're missing a few crucial pieces
no, asyncio's
loop = asyncio.get_event_loop()
I am using on_message_delete but I noticed that it doesn't say who deleted a message. If a person with permissions deleted a message, how can I know whether it was a moderator or the author?
Try bot.loop instead
You can't, unfortunately. You can try to see if it shops up on the audit log, but the audit log is a bit unreliable
alright thanks man
i wanna learn smthng about multi arg calculator
how can i add multi arg?
async def calc(ctx, num1:int, num2:int)
i dont wanna that
that's how you do it lmao
async def calc(ctx, num1: int, num2: int)
I'm not seeing what the issue is, you already have multiple arguments, don't you?
bro
what if i enter 3 args in command?
or 4 or 5?i want to add unlimited args
In that case either use * or the greedy typehint
oh yeah, you can do this
async def calc(ctx, *nums: tuple[int])
is * a list or tuple?
yes you can, if you enter !calc 1 2 3 4, then nums will be [1, 2, 3, 4]
cus if i don't get 2nd numbger from list, it won't work....
just perform a check if the list size is less than 2
i know, find the sum of all the numbers in that list
guys I'm struggling with currency bot stuff
what is it
so let's say I have an inventory
of items
I need to efficiently delete or add these newly added items
e.g. the user registered their account before the update and it looked like
item1 item2
0 0
and now I added an item3, they need to have this item now
it would be extremely inefficient to query everything and update everything at bot start
and there are query limits
bandwidth issues
that'll drop everything
make it a list/array of strings that contain the ID of the items?
wdym
what db r u using?
it's like json but not quite
mongo?
not documented based either
eughuheugh what
it's a sql-json mixed db
huh??
how i can run my bot with token ?
bot.run("TOKEN")
okay so i meant like items TEXT[] if you're on postgres for exaemple
in the main.py
it's not any type of SQL
but it's not anything like document based JSON serialized DB like mongo either
btw why the label on :onpage doesnt changed when :before button pressed?
i mean before after should add 1 to self.page
but it doesnt change
because you're not editing the view with the new buttons
Anyone?
from discord_slash import slashcommand
slash = slashcommand(client, sync_commands=True)
@slash.slash(description = "lol")
async def hello(ctx):
await ctx.send(f'Bot speed -{round(client.latency * 1000)}ms')
``` now correct?@fading marlin
tias
Tias?
try it and see
could you send the traceback?
@fading marlin
you haven't installed discord_slash then
also client isn't defined so that would also throw an error
No wait it is
It's just cut off from the code
Why are you using a third party lib?
Just use discord.py 2.0
hey does anyone know how to achieve this:
@bot.command()
async def color(ctx, arg):
colors = {'white':['White', '#FFFFFF', '(255, 255, 255)']}
e = discord.Embed(
title = f"__{colors[arg][0]}__",
color = discord.Color.from_rgb(colors[arg][2])
)
i want the color of the embed to be the rgb value from the dictionary
I installed now?
Are you asking me if you installed it
You just installed it and changed nothing in the code
You have to change your code
Example?
remove the quotes from the last item in your colors list, then add * at the beginning of colors[arg][2]
I'm a disnake user so wait for someone like sarth to pop up
Kk
yes
worked perfectly thanks!
Ii thanks
idk what the * did but it needed it to work
which awesome ide you are using?
visual studio code
!d discord.ext.commands.Context.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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
which extension?
ctx.send has a embed kwarg
doki doki theme : D
ahh okay ty
ye
😄
😄
Oh i know that code
dpy
Weren't you the dude that was asking for help with multiple exception handlers
no
oh
consider reading this then, it might be useful in the future https://realpython.com/python-kwargs-and-args/#unpacking-with-the-asterisk-operators
ah lmao, i forgot embed = embed
yeah he was me
thank you!
even though im not sure if i should continue with discord.py
since i think the creator stopped updating it
Idk how i forgot you that easy when i told you there was a i earlier
development has resumed!
@brave flintwhich doki theme you using?
from discord import app_commands
@app_commands.command(
name = "lol",
description = "hey"
)
async def hello(ctx):
await ctx.send(f'Bot speed -{round(client.latency * 1000)}ms')
``` correct code?
Bot is online but command is not working
why don't you try discord.ext.commands ?
are you beginner ?
no, that's for slash commands

Please elaborate, "not working" doesn't tell us much
Does the slash command show up? Do you get any errors? Does it show up but doesn't do as intended?
it's probably the fact that global slash commands take up to an hour to register
Nope, no error
just wait for it
Ok
robin halp
what's up
Does it show up?
No
Slash commands takes up to 1 hour to show
and there's an inventory for each user
Did you sync and pass in a guild?
Unless you specify the test guild
Okay
Nope
it's a hashmap that looks like (string)"itemname": (int)amount
There you have it
That's why
so my issue is
And it's a relational database?
well no
NoSQL?
relational databases are too hard to scale horizontally
Mmm, okay are you using like, MongoDB or?
unless I use smth like cockroach
it's a free db that's literally just json
Alright then
idea is similar to mongo but instead of _id it has key
what's the name of the db
What's the issue?
so when I add new items to the shop
the database doesn't automatically sync (and it can't do that)
why would u want to make a db for shop tho it dosent change much and frequent updates arent required

