#discord-bots
1 messages · Page 815 of 1
Well
If you blindly copy paste the code won't expect everything will work
are someone already did temp channel bot ?
correct
is it possible to let a bot use buttons like the pronoun bot(https://support.discord.com/hc/en-us/articles/1500012528941-Pronoun-Picker-Bot-FAQ , the second picture)
read from here, lasseo
that's right
We don't help on those project, even if it it is yourself.
oks, thanks for letting me now! appricaite that
does anyone know what is this part called "695515721436876841" in "https://discord.com/api/v9/channels/695515721436876841/messages". what's the name of that?
alr
not asking anything just interested
in this
channel id
no
why do you want the bot to watch a video..
so the bot has fun
ayo chill
im making it for a reason
?
Why when I unban a person by id, other people are unbanned there, why?
something with computer vison?
wdym
Show your code
Ok
#unban
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475)
async def unban(ctx, member):
banned_users = await ctx.guild.bans()
for ban_entry in banned_users:
user = ban_entry.user
await ctx.guild.unban(user)
emb=discord.Embed(title="Разбан пользователя", description="**__Информация:__**", color=discord.Color.from_rgb(0, 255, 0), timestamp=ctx.message.created_at)
emb.set_footer(text="© Все права защищены The Greatest", icon_url=ctx.author.avatar_url)
emb.set_thumbnail(url = user.avatar_url)
emb.add_field(name="**Нарушитель:**", value=f"**{user.name}**", inline=False)
emb.add_field(name="**ID нарушителя:**", value=f"**{user.id}**", inline=False)
emb.add_field(name="**Разбанил:**", value=f"**{ctx.author.name}**", inline=False)
await ctx.send(embed=emb)
return
You are unbanning the first person the bot finds in the ban list
🤔
You aren't even using the member arg
Why
Read your code again, it's looping through the guild's bans and banning the first person it finds, not the one referenced while invoking the command
Unbanning*
@slate swanu kinda been asking for help for a week still same commands
🥦
maybe try less copy pasta and learn ?
Не все
dasvidania
da da d ada
Да
nacho
Ты слкпой?
net blyat' calm down
net pararuska
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
^ davaj
Sorry, he provokes
How do I determine if a channel is dormant or as they say “dead chat” for a specific amount of time using discord.py (or pycord)
After he writes in transliteration, trying to prove something
maybe track time since last msg
and if > than X deadchat
Hmm
what is ur error friend?
I might have to make an infinite statement that can end when the time difference is large
i didnt translate why my russki was so bad 😛
🤔
u can just have a variable that is like last_msg = time.time()
and if that time in (unix seconds) is above like what ever u want 3hours, u can react and call it deadchat
An on_message event and async for 1 hour and compare current time with last time
Correct?
@slate swansto sto priviet, what is ur error?
@bot.command()
@commands.has_permissions(adminstrator = True)
async def off(ctx):
everyone = ctx.guild.get_role(761116759709057074)
embed=discord.Embed(title = "**השרת סגור לרגל תכנות ** `🛠️`", description = '**השרת יחזור בקרוב, תשארו מעודכנים !**' "\n")
embed.set_thumbnail(url = ctx.guild.icon_url)
embed.set_footer(text = f'{ctx.guild.name}', icon_url=ctx.guild.icon_url)
msg = await ctx.send({everyone.mention})
await ctx.send(embed=embed)
await msg.delete()
someone can explain me why @commands.has_permissions(adminstrator = True) in not working
Why when I unban a person by id, other people are unbanned there, why?
cause my friend, its obvious. you are running throu all members in banlist and unbans all
banned_users = await ctx.guild.bans()
for ban_entry in banned_users:
user = ban_entry.user
await ctx.guild.unban(user)```
you want to unban 1 specific user that command is so wrong
copy ur ban command, and edit .ban to .unban
and u have ban/unban commands
that code u show is basicly massunban of all users that are banned
why copy pasta codes arent good if u dont understand what u copying
@slate swanyou understand my comrade?
Yes
da, good
not really
because you can unban in many different ways
and cant pass discord.Member
@manic wingtrue
?????????
but you can post ID and it fetch
his code he want unban 1 person but its a massunban
it will raise membernotfound if discord.Member
@flat solsticei dont know maybe message object has a atrribute saying it was sent from webhook?
someone???
i dont know my friend, can it be the spaces?
@has_permissions(administrator=True)
@slate swanare u sure @bot.command() is correct? or is it a cog?
hmm, well it seems there's a discord.Message.webhook_id, guess that would work for my use case
that should be None if not a webhook so yeah
@slate swanlet me explain your own code for u
async def unban(ctx, member): # gets member
banned_users = await ctx.guild.bans() #fetches all banned users
for ban_entry in banned_users: # goes throu all banned users
user = ban_entry.user #each user (who is banned)
await ctx.guild.unban(user) #unbans
Okay
priviet comrade
Ptivet
Anyone know how to setup persistent view for Buttons and Drop-Down menus? (Nextcord)
A maintained fork of Danny's discord.py. Contribute to nextcord/nextcord development by creating an account on GitHub.
should be similar for nextcord
infact let me get the nextcord repo link
there, edited
Thanks
Wait, it only has persistent view documentation for Buttons, how do I go about adding it for dropdowns?
its the same! you just need to add the view item once your bot starts up
Uh?
I am doing this, actually
class jobDropdownView(nextcord.ui.View):
def __init__(self, bot):
super().__init__()
self.add_item(job_dropdown(bot))
job_dropdown is the class with the info for the actual dropdown
How do I implement custom_id in this scenario?
hello, I haven;t been here in a bit but i want to know if this is correct or not if not please correct me py if role.id is not in roles: await ctx.send("I can't remove that role because it is not on the list") await asyncio.sleep(10) await ctx.message.delete() return
the is can be removed, should be fine then if roles is a list of valid role IDs and role is a role object
roles is a list of valid roles id
so ok thanks for confirming
hmmm just a warning but still code: py @commands.command() @commands.has_role(940009737246892103) async def addrole(self, ctx, role: discord.Role, member: discord.User = None): if ctx.channel.id is not 939309364785872956: ctx.channel.send(f'Please do these commands in the <@&939309364785872956> channel!!!') return
#define the role
role = get_role(role.id)
if role not in (guild or member roles):
#your stuff
if ctx.channel.id == id
already fixed
and i want to do if any channels that are not that one channel send an message
If ctx.channel.id != id
ugh it works fine on the first but i get the error below when they are the same code doing 2 different things this works fine ```py
@commands.command()
@commands.has_role(940009737246892103)
async def addrole(self, ctx, role: discord.Role, member: discord.User = None):
if ctx.channel.id != 939309364785872956:
await ctx.channel.send(f'Please do these commands in the #939309364785872956 channel!!!', delete_after = 10)
asyncio.sleep(10)
ctx.message.delete()
return
member = None or ctx.author
roles = [938945700060856332, 938605431020986389, 933104091066941530, 936481481113632839, 936712347211419708, 936712664950931476, 842254098266718219, 842253873376264222, 842254463309316136, 842260259417489448, 842260429044842572, 893308041699680337, 816838497159610369, 826636738306506794, 841144860966125568, 902989589332000828, 902985326451130379]
if role.id in roles:
await member.add_roles(role)
await ctx.channel.send(f"You have added {role} to your role list!", delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
channel = self.client.get_channel(934171178426306560)
await channel.send(f"I have added {role} to {member.mention}!!")
return
if role.id is not roles:
await ctx.send("I can't give you that role because it is not on the list")
await asyncio.sleep(10)
await ctx.message.delete()
@addrole.error
async def addrole_error(self,ctx,error):
if isinstance(error, commands.RoleNotFound):
await ctx.send("I Can't give you that role because it's not a role.\n You need the id of the role or else I will give you an error!", delete_after = 10)
await asyncio.sleep(10)
await ctx.message.delete()
return
@commands.command()
@commands.has_role(940009737246892103)
async def removerole(self, ctx, role: discord.Role, member: discord.User = None):
if ctx.channel.id != 939309364785872956:
await ctx.channel.send(f'Please do these commands in the [#939309364785872956](/guild/267624335836053506/channel/939309364785872956/) channel!!!', delete_after = 10)
asyncio.sleep(10)
ctx.message.delete()
return
(line 90 bellow)
member = None or ctx.author
roles = [938945700060856332, 938605431020986389, 933104091066941530, 936481481113632839, 936712347211419708, 936712664950931476, 842254098266718219, 842253873376264222, 842254463309316136, 842260259417489448, 842260429044842572, 893308041699680337, 816838497159610369, 826636738306506794, 841144860966125568, 902989589332000828, 902985326451130379]
if role.id in roles:
await member.remove_roles(role)
await ctx.channel.send(f"You have removed the role {role} from your role list!", delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
channel = self.client.get_channel(934171178426306560)
await channel.send(f"I have removed {role} from {member.mention}!!")
return
if role.id is not roles:
await ctx.send("I can't remove that role because it is not on the list")
await asyncio.sleep(10)
await ctx.message.delete()
return
@removerole.error
async def addrole_error(self,ctx,error):
if isinstance(error, commands.RoleNotFound):
await ctx.send("I Can't remove that role because it's not a role.\n You need the id of the role or else I will give you an error!", delete_after = 10)
await asyncio.sleep(10)
await ctx.message.delete()
return```
line 90 in the second section
is this the correct way to delete the command msg?py ctx.message.delete()
yes or that how i use it
thought so and was wondering why it wasn't deleting and just realised I hadn't awaited it
that would get you i have done that a few times
yeah
100%
u can also do ctx.delete() i think
!d discord.ext.commands.Context.delete
No documentation found for the requested symbol.
well
idk, it doesnt have docs
figure it out
lol
same as msg = ctx.send("shithole")
msg.delete()
Is it possible for a bot to read a reply from question for example if bot asks.
Are you ok?
And you reply. Kinda it will say ok back
can someone aswer my question above please
@slate swanyes lookup, wait_for()
?
Yes but the message isn’t a certain answer it can be any answer
@quick gustur answer was 100%
ah okay
@honest vessel basically I want the bot to read the reply to use for the code
i still think u wanna get wait_For it can be msg or reactions
yes like .hello
bot > tell ur age
you input 12
bot > ok ur 12.
and it can be reactions too
ok i dunno this bot 😄
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
that will do for now
https://mystb.in/AlbaniaTigersConspiracy.python
when i tip vc/help it shows this error
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\L3\desktop\auto-voice-channels\auto-voice-channels.py", line 1028, in on_message
perms = message.author.permissions_in(channel)
AttributeError: 'Member' object has no attribute 'permissions_in'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\L3\desktop\auto-voice-channels\auto-voice-channels.py", line 1028, in on_message
perms = message.author.permissions_in(channel)
AttributeError: 'Member' object has no attribute 'permissions_in'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\L3\desktop\auto-voice-channels\auto-voice-channels.py", line 1028, in on_message
perms = message.author.permissions_in(channel)
AttributeError: 'Member' object has no attribute 'permissions_in'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\L3\desktop\auto-voice-channels\auto-voice-channels.py", line 1028, in on_message
perms = message.author.permissions_in(channel)
AttributeError: 'Member' object has no attribute 'permissions_in'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\L3\desktop\auto-voice-channels\auto-voice-channels.py", line 1028, in on_message
perms = message.author.permissions_in(channel)
AttributeError: 'Member' object has no attribute 'permissions_in'
thats alot of erros 😛 tho
permisssions
wrong spell?
can u show where Member comes?
idk 
yes
https://mystb.in/AlbaniaTigersConspiracy.python this is a very fuckedup code to begin with
You edited dpy source code?
yes
Pain
@pliant nacellebasic python but how u have that code n not knowing?
@client.event
async def on_message(message):
perms = message.author.permissions_in(channel)
perms_required = [
perms.manage_channels,
perms.manage_roles,
]
and nothing
I cnat help u man thats is pain
and so wrong in all ways
u are prob einstein
thats prob sickest codes of a discordbot using libary iv ever seen 😄
its nice to debug huh
?
sadly to hear that
I don't even understand anything of that
why are there so many tasks
hope you don't have them on 24/7
how can i make it do something when a specific message has found
I'm getting this error when my bot tries to run a function from different file, the function is inside of a classpy Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 268, in on_member_join await Info().timestamps(member, embed, True) TypeError: __init__() missing 1 required positional argument: 'bot' this is the importpy from .info import Infothis is the functionpy async def timestamps(self, member, embed, avatar): embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True) if avatar == True: embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True) embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)I'm not sure why it's telling me it's missing bot arg
Can we see your __init__ method?
for which file? the one I'm trying to run the function or the one that has the function?
i did to late now i went though and checked everything
does changing someones nick name get rate limited?
hlep
is anyone here good at disnake ?
plugin_list = commands.option_enum(["Moderation", "Commands", "Levels"])
@client.slash_command()
async def help(inter: disnake.ApplicationCommandInteraction, plugin : plugin_list = None):
if not plugin:
embed = disnake.Embed(color = disnake.Color.dark_purple())
embed.set_author(name="SkySMP Plugins", icon_url=client.user.avatar_url)
embed.set_thumbnail(url = client.user.avatar_url)
embed.add_field(name = "Commands", value = "`/help Commands`")
embed.add_field(name = "Moderation", value = "`/help Moderation`")
embed.add_field(name = "Levels", value = "`/help Levels`")
await inter.response.send_message(embed = embed)
return
if plugin.lower() == "moderation":
embed = disnake.Embed(color = disnake.Color.dark_purple())
embed.set_author(name="SkySMP Moderation Plugin", icon_url=client.user.avatar_url)
embed.set_thumbnail(url = client.user.avatar_url)
embed.add_field(name = "Mute", value = "`.mute [user] [minutes]`")
embed.add_field(name = "Unmute", value = "`.unmute [user]`")
embed.add_field(name = "Kick", value = "`.kick [user] [reason]`")
embed.add_field(name = "Ban", value = "`.ban [user] [reason]`")
embed.add_field(name = "Unban", value = "`.unban [user]`")
embed.add_field(name = "Nick", value = "`.nick [user] [nick]`")
embed.add_field(name = "Nickdel", value = "`.nickdel [user]`")
await inter.response.send_message(embed = embed)
if plugin.lower() == "commands":
embed = disnake.Embed(color = disnake.Color.dark_purple())
embed.set_author(name="SkySMP Commands", icon_url=client.user.avatar_url)
embed.set_thumbnail(url = client.user.avatar_url)
embed.add_field(name = "Avatar", value = "`/avatar [user (optional)]` Shows a Users Avatar")
embed.add_field(name = "Ping", value = "`/ping` Shows the bots Latency")
await inter.response.send_message(embed = embed)
if plugin.lower() == "levels":
embed = disnake.Embed(color = disnake.Color.dark_purple())
embed.set_author(name="SkySMP Level Plugin", icon_url=client.user.avatar_url)
embed.set_thumbnail(url = client.user.avatar_url)
embed.add_field(name = "Level", value = "`/level [user (optional)]`")
embed.add_field(name = "Levels", value = "`/levels`")
await inter.response.send_message(embed = embed)
else:
return
``` dis not working 
what did i do wrong ?
explain "not working", is there an error?
dont judge me im new
this is the __init__ for the file where I'm trying to run the functionpy class Events(commands.Cog): def __init__(self, bot): self.bot = boand this is the __iniit__ for the file where the function is locatedpy class Info(commands.Cog): def __init__(self, bot): self.bot = bot
Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1322, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 595, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ClientUser' object has no attribute 'avatar_url'
i c but whats different at disnake ?
icon_url=client.user.avatar_url
capital U ? someone told me that
client.user.avatar.url
avatar.url?
Well you need to pass in bot
discord.py 2.0 update
so py await Info().timestamps(bot/self, member, embed, True)orpy await self/bot.Info().timestamps(member, embed, True)
@commands.Cog.listener()
async def on_user_update(self, before, after):
if before.name != after.name:
book = Webhook(self.hook)
embed = discord.Embed(color=0x303136, title="Username Updated", description="")
embed.description += f"**Member:** `{user.name}`\n"
embed.description += f"**Before:** `{before.name}`\n"
embed.description += f"**After** `{after.name}`\n"
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text=f'Author: {user.id}')
book.send(embed=embed)
NameError: name 'user' is not defined
ye because not defined in the func
Why do you need user.name
just use after.name
Because that'll be the latest username
i have this
@client.command()
async def ban(ctx, user_id, *, reason):
user = await client.fetch_user(user_id)
await ctx.guild.ban(user, reason=reason, delete_message_days=0)
but i keep getting MemberNotFound
You can typecast user_id to discord.Member
that way you can ping, give id. or even their name
i am passing in bot, i just hadn't copied the t when I copied the code
won't it not work if im trying to ban someone that isn't in the server
Can't you typehint to discord.Object?
user_id is a string, not sure how the library would deal with it. you should try type casting it to Member, User, or Object
hi robin
Hm just checked and doesn't look like you can typehint to discord.Object
then try discord.User
you can
ok
you'd probably have to do Union[int, discord.Member] though
whats that
i think apply multiple types to a variable?
for some reason my bot isn't sending my admin account a dm when the account gets banned. ths is my on_member_ban event```py
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
if user.id in self.bot.config.admins:
await user.unban(reason = "This account is a test acount for SnowyJaguar#1034")
invite = await self.bot.comm.handler("invite_guild", -1, {"guild_id": guild.id})
if not invite:
await user.send(embed = discord.Embed(description = "No permissions to create an invite link.", colour = self.bot.primary_colour))
else:
buttons = [create_button(style = ButtonStyle.blue.URL, url = f"https://discord.gg/{invite.code}", label = f"Invite Code: {invite.code}")]
action_row = create_actionrow(*buttons)
await user.send(content = f"You can rejoin {guild} by clicking the button", components = [action_row])
button_ctx: ComponentContext = await wait_for_component(self.bot, components = action_row)
await button_ctx.edit_origin(content = "You pressed a button!")```and this is my list of admins```py
admins = [446290930723717120,381998065327931392,365262543872327681,448404519790051330,791394319075377243, 757750333144563724,]```
do you have GUILD_BANS intents?
what do i import?
import typing
or is some specific part of that not working
then you can do typing.Union[]
or, alternatively, for a more polluted namespace, from typing import Union
not sure, guess I'llcheck
and you can pair that with importing annotations from __future__
and doing the whole if TYPE_CHECKING: ... thing
ty it worked
can you remind me which intent that comes under? is it the server members one?
# this makes any annotations you perform a simple string
from __future__ import annotations
from typing import TYPE_CHECKING
# this will not execute during runtime, but will be evaluated by your linter
if TYPE_CHECKING:
# import any objects you're gonna use to typehint your code here
# not that they *CANNOT* be used as if they were regular imports, only for annotations
from typing import Iterable
def foo(bar: Iterable) -> Iterable:
return bar
@dire folio
hm no just add bans = True to wherever you create your discord.Intents obj
cool
for example:
intents = discord.Intents(
...,
bans=True,
)
client = discord.Client(intents=intents)
to type hint their code
okay so it's now unbanning the user correctly but it seems to be unable to dm the userpy Ignoring exception in on_member_ban Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 479, in on_member_ban await user.send(content = f"You can rejoin {guild} by clicking the button", components = [action_row]) File "/usr/local/lib/python3.8/dist-packages/discord_slash/dpy_overrides.py", line 323, in send_override return await send(channel, *args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/discord_slash/dpy_overrides.py", line 300, in send data = await state.http.send_message( File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 248, in request raise Forbidden(r, data) discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user ```py
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
if user.id in self.bot.config.admins:
await user.unban(reason = "This account is a test acount for SnowyJaguar#1034")
invite = await self.bot.comm.handler("invite_guild", -1, {"guild_id": guild.id})
if not invite:
await user.send(embed = discord.Embed(description = "No permissions to create an invite link.", colour = self.bot.primary_colour))
else:
buttons = [create_button(style = ButtonStyle.blue.URL, url = f"https://discord.gg/{invite.code}", label = f"Invite Code: {invite.code}")]
action_row = create_actionrow(*buttons)
await user.send(content = f"You can rejoin {guild} by clicking the button", components = [action_row])
button_ctx: ComponentContext = await wait_for_component(self.bot, components = action_row)
await button_ctx.edit_origin(content = "You pressed a button!")```
you can't send messages to users if you don't share guilds with them or if they have dms off
just wrap it in a try catch
it's not mandatory, but it's better to use that method over just importing them
so if I want it to Dm someone when they get banned how would I do that? as part of on_member_remove?
can a bot use ffmpeg and record voice in vc?
What lib are you using for buttons, it looks terrible
Not with discord.py
hmm
what else tho
Hi.
Im getting this error: on_member_ban() takes 2 positional arguments but 3 were given
Code:
@commands.Cog.listener()
async def on_member_ban(self, member: discord.Member):
cursor = await self.db.cursor()
iddb = await cursor.execute(f"SELECT channel_id from audit Where guild_id = ?", (member.guild.id,))
idt = await iddb.fetchall()
id = idt[0][0]
channel = self.bot.get_channel(id)
em = discord.Embed(title="Member Banned", description=f"The memeber {member} got banned!!")
em.add_field(name="Memeber banned at:", value=datetime.datetime.utcnow())
em.set_thumbnail(url=member.avatar.url)
await channel.send(embed=em)
Idk what to remove / add in the async def
Why would you need to record voice with a bot 👀
Nothing in python that I'm aware of unless you want to go through the bare api
i need it as im the developer for my school discord bot
!d discord.on_member_ban
hm ok
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
Takes guild and user
Ok, thats a bit more understandable. Data collection is always iffy with bots
hm tru
is there any way to add the terminal of my bot in some command
self is needed if it's in a class
I dont know enough about bots and voice to help specifically but i would just say for tos and other privacy factors that you make the people in the server aware that it collects voice recordings when you get it working
yes i got the perms from my school
I asked Andy about it and apparently the packets are dispatched
So it is possible
It just hasn't been implemented yet
Just implement it yourself

ffmpeg python package url [https://github.com/jiashaokun/ffmpeg]
iddb = await cursor.execute(f"SELECT channel_id from audit Where guild_id = ?", (member.guild.id,))
AttributeError: 'Guild' object has no attribute 'guild'
You put them in the wrong positions
Error
is discord.py the best to code bots, or is discord.js better
discord.js is JavaScript
ik
subjective
which is the best to code discord botds
if you like javascript better use discord.js, if you prefer python use discord.py
neither, both are equal
i mean which is more easier
Whichever language you know better
!guilds
Communities
The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.
Bot didnt like that lol
Check in here
...
that's for discord.js
aren't they asking for a JS server?
like this is a py server
Ah, my appologies
I got question
?
What
I want to do command like !Test
And bot responds. Reply here with string. User writes: gkfk38 and bot saves the response by user as variable
Uh i asked for help. you typed !guilds didnt do anythingg soo yea
That wasn't directed to you
I also told you your issue
OH
Then i send another error...
No you didn't
...
Read 2 messages below that
why is it not it not doing the asyncio.sleep? py @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.CommandOnCooldown): msg = "**Still on cooldown!!!**, please try again in {:.2f}s".format(error.retry_after) await ctx.send(msg, delete_after = 5) asyncio.sleep(5) await ctx.message.delete()
It's a coro
You have to await it
okay so I'm still getting this error when my bot tries to run a function from different file, the function is inside of a classpy Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 268, in on_member_join await Info().timestamps(member, embed, True) TypeError: __init__() missing 1 required positional argument: 'bot' this is the importpy from .info import Infothis is the functionpy async def timestamps(self, member, embed, avatar): embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True) if avatar == True: embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True) embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)I'm not sure why it's telling me it's missing bot arg. this is the __init__ for the file where I'm trying to run the functionpy class Events(commands.Cog): def __init__(self, bot): self.bot = botand this is the __iniit__ for the file where the function is locatedpy class Info(commands.Cog): def __init__(self, bot): self.bot = botso should i be doingpy await Info().timestamps(bot/self, member, embed, True)orpy await self/bot.Info().timestamps(member, embed, True)sorry if this is chat flood
i haven't before
What do i need to see?
@client.command()
async def info(ctx):
url = "https://media.discordapp.net/attachments/939662743605231616/941051130794872922/microbe.png?width=212&height=212"
em = discord.Embed(title = name, value = f"Microbe")
em.add_field(value="**BUY** - 5,000",inline=False)
em.add_field(value="**SELL** - 5,000",inline=False)
em.add_field(name="Rarity",value="```Common```")
em.add_field(name="ID",value="```microbe```")
em.set_thumbnail(url = url)
em.set_footer(text=f"{types} | You made a nice reddit post", icon_url=PmCtx.author.avatar_url)
await ctx.reply(embed=em)
What I said...?
Why is this not working
@pure tartan
@client.command()
async def info(ctx):
url = "https://media.discordapp.net/attachments/939662743605231616/941051130794872922/microbe.png?width=212&height=212"
em = discord.Embed(title = name, value = f"Microbe")
em.add_field(value="**BUY** - 5,000",inline=False)
em.add_field(value="**SELL** - 5,000",inline=False)
em.add_field(name="Rarity",value="```Common```")
em.add_field(name="ID",value="```microbe```")
em.set_thumbnail(url = url)
em.set_footer(text=f"{types} | You made a nice reddit post", icon_url=PmCtx.author.avatar_url)
await ctx.reply(embed=em)
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
ok i'll await it
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
how do i mek butttons in disnake
Oh sorry. discord was laggy and didnt show the msg. thx. Another question (sorry) can i gget the moderator that banned?
Uh
^
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
@client.command()
async def info(ctx):
url = "https://media.discordapp.net/attachments/939662743605231616/941051130794872922/microbe.png?width=212&height=212"
em = discord.Embed(title = "Info", description = f"Microbe")
em.add_field(title="Info",value="**BUY** - 5,000",inline=False)
em.add_field(title="Info",value="**SELL** - 5,000",inline=False)
em.add_field(title="Info",name="Rarity",value="```Common```")
em.add_field(title="Info",name="ID",value="```microbe```")
em.add_field(title="Image",value="https://media.discordapp.net/attachments/939662743605231616/941051130794872922/microbe.png?width=212&height=212")
em.set_footer(text=f"| You made a nice reddit post", icon_url=ctx.author.avatar_url)
await ctx.reply(embed=em)
Oh yea mmmm i forgot my other account was i here. i typed from his
@client.command()
async def info(ctx):
url = "https://media.discordapp.net/attachments/939662743605231616/941051130794872922/microbe.png?width=212&height=212"
em = discord.Embed(title = "Info", description = f"Microbe")
em.add_field(title="Info",value="**BUY** - 5,000",inline=False)
em.add_field(title="Info",value="**SELL** - 5,000",inline=False)
em.add_field(title="Info",name="Rarity",value="```Common```")
em.add_field(title="Info",name="ID",value="```microbe```")
em.add_field(title="Image",value="https://media.discordapp.net/attachments/939662743605231616/941051130794872922/microbe.png?width=212&height=212")
em.set_footer(text=f"| You made a nice reddit post", icon_url=ctx.author.avatar_url)
await ctx.reply(embed=em)
```py
does not come out properly
if anyone has docs or any command to see the bot terminal directly from the bot please can you send me
Just send a screenshot of the code then
I'm not sure if you can
my guy PEP8 compliance officer
And whaf was the error it was giving?
nothing
indents are wrong
Okie ill leave
it just never outputted anything
2 spaces for each level its 4 to follow pep8
wait relly ?
yes
it should show up with an error
if the indentation is wrong
2 indents arent wrong
its just not following pep8
alrighty then
join the PEP8 regulation gang 😎
Print em to the console and see if it contains what it should
no im pep464
didnt help
I need to get into better formating
@slate swan you're right
>>> def foo():
... print("hello")
...
>>> foo()
hello
black?
and the title kwarg doesnt have a value lol
prints out nothing
i know
?
wdym
Not sure, tbh. Never really had indenting errors its just more spacing between lines and functions etc
also why use f-strings when you're not gonna use them
look at your title
lemme check something rq
I know, that wasn't directed at you
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
there's no title kwarg 
is that what you're saying?
Br-
look at this one
.
it wont send if you have somethign invalid like dekriel has said
OH WAIT
Not sure what style this would fall closest under
i HAVE TITLE AND NAME
why the
why the space
@slate swan Why did you remove doc strings in the cache class
also iirc just 2 spaces between the functions in a class
cause they arent supposed to be in docs so i removed them so autodoc doesnt doc them because i dont trust in it
Ah
Its just a thing i do to help make finding things easier because they are grouped together and seperated by spaces
@final iron You said I had to Well you need to pass in bot which i am doing, I just had a spelling and copy paste mistake before
I'm still mad I can't even do anything
Imma open a help channel

yeah sphinx gets the same thing
IDK WHY
Does your code run?
yeah ofc but in other computers it doesnt

smh
So is this an issue with sphinx?
Because I'm trying to fetch a user and its showing this error
I tried deleting the __init__ file and it's still throwing this
nah its not an issue with sphinx its probably imports or the init file
ill try to trouble shoot it real quick
__init__ file isn't even there
is this related to akeno
Yes
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
dek mad he cant contribute
murder is the only option

not bothered
here 🔪
arent you timedout?
yes?
Okay lets move
bozo
why?
🔪 I got a knife
🏃
I'm not afraid to use it
sure you are
let's keep it on topic guys
yes?
@slate swan Okay just answer my question, is my error an issue with my environment or is the issue with the code?
code
maybe imports
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Can i cash this now?
Hm?
I was taking a reign check on it and was wondering if you had the time to go over it now
Sure, what do you want to know about it specifically
disnake users
hlep
Traceback (most recent call last):
File "C:\Users\Niclas\Desktop\Other\Python\NcZ Discord Bots\Disnake\NcZ Testing\main.py", line 93, in <module>
class TestButtons(disnake.ui.View):
File "C:\Users\Niclas\Desktop\Other\Python\NcZ Discord Bots\Disnake\NcZ Testing\main.py", line 102, in TestButtons
async def button1(self, button: disnake.Button, inter: disnake.MessageInteraction):
TypeError: 'Button' object is not callable
How you made a custom decorator and i suppose how it would compare to the slash commands
class TestButtons(disnake.ui.View):
def __init__(self):
super().__init__()
self.choice = None
@disnake.ui.Button(label="Button 1", style = disnake.ButtonStyle.blurple)
async def button1(self, button: disnake.Button, inter: disnake.MessageInteraction):
self.choice = True
self.stop()
@disnake.ui.Button(label="Button 2", style = disnake.ButtonStyle.red)
async def button2(self, button: disnake.Button, inter: disnake.MessageInteraction):
self.choice = False
self.stop()
Alright the thing is
You can use discord.py to only listen for slash commands
To actually register them you should use the API
Or you can build your own wrapper that helps register slash commands
Registering them is the hard part
Listening for them is much easier
Oooo, so essentially it would just register a "blank" slash command and then listen for that and then perform the actual command?
Basically
When you first register it, and if you call it nothing will happen since it's not listening for it
In discord.py, you can make a decorator tied to the bot instance, so whenever you use that decorator, it'll add a new entry in the form of a dict, with the function name as key and function as object
@my_deco
def func():
# callback
def my_deco(func): # func = function being decorated
someDict["function name"] = func
So would that mean that the decorator just takes the command and "imports" it into the slash commands format to be used?
More like it adds it to a dictionary
def on_interaction(interaction):
await func = someDict[interaction.slash_command_name]
very crude but it works
Registering commands is super tedious yet super easy, I recommend making a to_dict method bound to your slash command's class
I lowkey love the idea of that
Yeah like i mentioned registering is the hard part
The hard part is subcommands and options
Honestly how I've done it is used an online web tool callled "postman" which is used for API testing and sending requests
Registering is easy as hell
These you would actually need to write a parser
Well you can register all of it with a single post request really
Im familiar with what postman is and im making bots to help learn apis for web development
^ yep just use that to register it then
or write your wrapper class that makes it easier
It would be better to procedurally register it, if you plan on adding more commands that is
So use postman to register the dict or wrapper it?
Yep more flexibility that way
Whichever really but postman would be easiest
just for a proof of concept sort of thing
Damn ok
I think discord.js has their own slash command builder which you can draw inspiration from
it's a seperate js file you run whenever you want to add a new slash command
Do you have a link or copy of it?
No but i'm pretty sure it's on the guide section of their website
Ok, next question about this. Would the prefix portion have to be dropped in the bot.py file? And if so would that not break the commands?
Nah this would be seperate from the commands extension
from __future__ import annotations
import rin
import asyncio
import os
token: str = os.environ["DISCORD_TOKEN"]
client = rin.GatewayClient(token, intents=rin.Intents.default())
@client.once(rin.Events.READY)
async def ready(user: rin.User) -> None:
print(f"Logged in as: {user.id}")
@client.on(rin.Events.MESSAGE_CREATE)
async def message_created(message: rin.Message) -> None:
print(f"Received a message! {message}")
@rin.AppCommand(rin.ChatCommand)
class HelloWorldCommand:
guilds = [907106240537169980]
description = "A demo description."
name = "hello"
@HelloWorldCommand.on()
async def callback(interaction: rin.Interaction) -> None:
await interaction.send(f"Hello {interaction.author}!")
asyncio.run(client.start())
``` Heres some extra inspiration as well from my own impl
the command framework is strictly not compatible with slash commands
discord.js's builder is way to bulky for it to work in python
Not with the ```py
Something()
.attr
You could do that in python though, but requires round braces
nah the syntax wouldn't work
a = (Foo()
.attr
)
they do some weird things like
slashCommandBuilder
.setName()
.setOptions
.setChoices
.set*
didn't like it all that much
!e ```py
class A:
def init(self,) -> None:
self.a = "foo"
b = (A()
.a
)
print(b)
Ill copy this elsewhere to check out when i start trying to write it
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
foo
What is this?
You'd only be copying the frontend, I haven't pushed my internals for this yet
It makes me phisically ill hahaha
How so
I may be able to reverse engineer portions of it or at least get the idea from it
How can I get an ID from a discord.Member object
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.id "discord.User.id")
Simple as that
Sure, If it helps. I use the decorator (which is a generic command builder), I give it a type, and it builds it. While looking through the decorated classes namespace as the metadata holder
This is also the how discord.py registers the normal commands, it adds your command to a list of commands, and calls it whenever it detects a message with the format <prefix><command name>
so some ideas in the source code if you wanna look at that
If thats the case could that just be registered instead?
Ok
Dumb question. Would stuff like dpy and disnake not just be things that turn the commands and whatnot into http requests to talk specifically to the discord api?
Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1322, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 595, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: call_param_func() got multiple values for argument 'interaction'
``` what to do
interaction_list = commands.option_enum(["Slash", "Buttons", "Other"])
@client.slash_command(name = "interactions", description = "Shows the Disnake Interactions")
async def interactions(inter: disnake.ApplicationCommandInteraction, interaction : interaction_list = None):
if not interaction:
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Interactions", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.add_field(name = "Slash Commands", value = "`/interactions Slash`")
embed.add_field(name = "Buttons", value = "`/interactions Buttons`")
embed.add_field(name = "Other", value = "`/interactions Other`")
await inter.response.send_message(embed = embed)
return
if interaction.lower() == "slash":
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Slash Commands", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.add_field(name = "interactions", value = "`/interactions [interaction]`")
await inter.response.send_message(embed = embed)
if interaction.lower() == "buttons":
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Buttons", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.add_field(name = "Buttons", value = "`/buttons` Shows some simple test buttons")
await inter.response.send_message(embed = embed)
if interaction.lower() == "other":
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Other", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.description = "Nothin in here..."
await inter.response.send_message(embed = embed)
else:
return
would require some messing around in the source code
better to build it yourself
Full exception?
Ignoring exception in slash command 'interactions':
Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 586, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
TypeError: call_param_func() got multiple values for argument 'interaction'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1322, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 595, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: call_param_func() got multiple values for argument 'interaction'
Hmmm, ya i suppose wrapoing over it wouldnt really do much because it would just be all new functions given none already do that. And also kinda brings us back to the initial idea
@desert badger iirc you don't typehint with commands.Param or things similar to it, but you set this as a default value, try it
What argument are you giving in your command?
How would I check if a member is in a guild?
interaction_list = commands.option_enum(["Slash", "Buttons", "Other"])
@client.slash_command(name = "interactions", description = "Shows the Disnake Interactions")
async def interactions(inter: disnake.ApplicationCommandInteraction, interaction : interaction_list = None):
if not interaction:
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Interactions", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.add_field(name = "Slash Commands", value = "`/interactions Slash`")
embed.add_field(name = "Buttons", value = "`/interactions Buttons`")
embed.add_field(name = "Other", value = "`/interactions Other`")
await inter.response.send_message(embed = embed)
return
if interaction.lower() == "slash":
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Slash Commands", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.add_field(name = "interactions", value = "`/interactions [interaction]`")
await inter.response.send_message(embed = embed)
if interaction.lower() == "buttons":
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Buttons", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.add_field(name = "Buttons", value = "`/buttons` Shows some simple test buttons")
await inter.response.send_message(embed = embed)
if interaction.lower() == "other":
embed = disnake.Embed(color = disnake.Color.blue())
embed.set_author(name="Disnake Other", icon_url=client.user.avatar.url)
embed.set_thumbnail(url = client.user.avatar.url)
embed.description = "Nothin in here..."
await inter.response.send_message(embed = embed)
else:
return
can someone pls review my calculator code bcoz im using eval for it and i just need to know if its safe
If member in ctx.guild.member
Delete the = None
oke
Eval is never save
You can use a lib
!pypi py-expression-eval
btw look in ncz testing there are buttons 
Gj
eval is gonna let people run RCE on your host lol
but i am trying to make sure illicit codes dont get used bcoz i blocked some words and symbols that would screw my bot up
Still not safe exposing eval to the public
They are easy to avoid, and this is completely safe
Is it done with buttons?
Why not use a safer option
I don't think would work, as members are bound to specific guilds. Thus the statement would fail when checking for a guilds member in another guild. You could use mutual_guilds property of discord.Member perhaps?
no. no buttons used
^ fundamental difference between discord.Member and discord.User
how do i make the interaction not required? it only lets me choose between these 3
@weekly.before_loop
async def wait_until_monday():
now = datetime.now().astimezone()
next_run = now.replace(hour=0, minute=0, day=0)```I got this but I dont get how to specifily make for every monday
Oh, then i think user instead of member.
but i will add at the nearby future
Would still be false as users aren't members
!d datetime.datetime.weekday
datetime.weekday()```
Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as `self.date().weekday()`. See also [`isoweekday()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoweekday "datetime.datetime.isoweekday").
Essentially if unique user is in the member list of the guild the command was sebt in
you could in theory compare their ids but it might be a bit slow
That is extremely unsafe then
but cant i just send the code here then u can hav a look?
Add it to the interaction_list
I already know that it's unsafe...?
so i cant just leave it empty ?
!d discord.Member.mutual_guilds
property mutual_guilds```
Equivalent to [`User.mutual_guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.mutual_guilds "discord.User.mutual_guilds")
all fun and games still someone sends in
!calculator "rm -rf /"
When it is passed you set it to None, like adding "Not required" and then checkin it in an if
but im trying to block some words and added round
What did you block?
ill show u now
Ok
@jeanne_slash(description="Do a calculation")
async def calculator(self, interaction: Interaction, calculate):
not_allowed = ['_', 'exec', 'getattr', 'memoryview', 'import']
await interaction.response.defer()
if any(not_allowed in calculate for not_allowed in not_allowed):
nice_try=Embed(description="Ahh... I see you wanna try something funny?\nWell, nice try!")
await interaction.followup.send(embed=nice_try)
else:
answer = round(eval(calculate), 10)
calculation = Embed(title="Result", color=0x00FFFF)
calculation.add_field(name=calculate, value=answer)
await interaction.followup.send(embed=calculation)```
im using nextcord
how about os.system
He prohibited to import anything
This is def not safe
nah
__import__
But this is not safe at all
Still extremely unsafe
👁️ 👁️
very dangerous
great...
Still would get spotted
you're barely blocking anything
!e py print('import' in '__import__')
@vale wing :white_check_mark: Your eval job has completed with return code 0.
True
I guess import == __import__ now from that logic
Yk
oh they are using in
what if they send in ops that would take a long time
Guess you can just use eval plus chr() to slowly but surely write import
But it's still better to make separate commands - one owner-only for executing custom commands and one for math with usage of py-expression-eval @brave moth
couldn't you just like
!calculator "while True: print('a')"
Haha yes
!e ```py
a = (chr(c) for c in (105, 109, 112, 111, 114, 116))
print(list(a))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
['i', 'm', 'p', 'o', 'r', 't']
👁️ 👁️ .join + eval
!e
a = (chr(c) for c in (105, 109, 112, 111, 114, 116))
print(''.join(a))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
import
kek
Showing someone how insecure a calculator designed like that is
so if i use this lib, then im safe?
eval = bad, don't use it that's what we're trying to say basically
Totally
while True:
print(99999999 ** 999999999)
Ah, right
It only evaluates math expressions
or you could parse math yourself
i did a basic calculator that way in java once with stacks and queues
I would probably only use an external API to do commands like this
Otherwise use regex patterns to look for operators and ones that check for digits only
Btw about exec can anybody tell me why does this literally eat all the errors https://paste.pythondiscord.com/edubosazox.py
Thinking of something else
or you could spin up a docker container just to run 2 + 2 😉
I cant wait till monday to debug this can you tell me if i did this right. https://mystb.in/AlgeriaDealersUnder.py
I feel like that still would be suspect
Um you could use a formula instead of those elifs
You'd be safe if you used nsjail as well
what's a formula?
Basically 7-weekday lol
piston/nsjail/docker basically the same things
oooh lmao
At that point it would be more than a calculator though
my code will run every monday right
Why not just put
if datetime.now().weekday() == 0:
... # stuff
And add an indicator that the code has been runned on monday
yeah... im just gonna use the lib
that does pretty much nothing to stop someone
!e ```py
a = (chr(c) for c in (105, 109, 112, 111, 114, 116))
print("".join(a) + " os; os.system('sudo rm -rf / --no-preserve-root')")
How would I do something if an argument is a mention, and do something else if it isn't a mention
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
import os; os.system('sudo rm -rf / --no-preserve-root')
alright, i used the lib. it worked and i tried to use dir() hoping it will not show the list but instead, met with this error
raise Exception('undefined variable: ' + item.index_)
Exception: undefined variable: dir```
Depends on argument
use regex to check if it matches a pattern
@cog_ext.cog_slash()
async def rgi(self, ctx: SlashContext, id):
await ctx.message.delete()
if ctx.author.id != 404264989147529217:
return
with open(add_path, "r") as f:
bypass = json.load(f)
if str(id) in bypass:
bypass.remove(str(id))
await ctx.reply(f"`{id}` Has been removed from the database!", ephemeral=True)
with open(add_path, "w") as f:
json.dump(bypass, f, indent=4)
But mostly you can just typehint with typing.Union
typing.Union is so gross tbh, me and the bros use union pipes
what the fuck
Indeed
How would I do that?
wait can you provide context?
Regex would make this pretty over-engineered though
not really
You could just check the context messages mentions attributes perhaps
Or User.mentioned_in
@dry kelp can you scroll up in the traceback a little
ye
well what if the mention was elsewhere in the message? maybe as the prefix or another agument?
yeah, but it wouldn't be ideal for what they're doing
Anyone help?
No it's just going to be in one argument
It won't be anywhere else
i mean why do you need to do that? you're gonna have to use MemberConverter inside the command in that case i would imagine
because i need it to be done as close to midnight as possible
How so, it would be the same thing your regex option is doing but different detection. You just detect it, control flow, etc
@dry kelp search for issubclass() usages in your code although I totally don't know what the hell is wrong with this
I'd personally use disnake to make slash commands instead of this
and not to be run twice on the same day if i restasrt the bot
@command_decorator_idk()
async def foo(ctx, arg):
# you can regex match the argument
can u send an example?
!pypi disnake
Yea, so either way the only difference is how you detect the mention, Isn't using User.mentioned_in or checking Message.mentions a lot faster then doing a regex search
@pliant gulch can you tell me why does this eat all exceptions that happen while execution and how to fix it
https://paste.pythondiscord.com/edubosazox.py
Also depending on how good/bad the regex is, speed changes
I'm assuming it has something to do with the try-except block you have inside of the code being evaluated
Is there a reason why you don't just use the error handler on exec
I have 2 error handlers lol
Inside and outside
Outer works only with syntax errors
Haven't seen inner ever working
When there's a certain non syntax error in code it just sends nothing
-exec py import os os.system("rm -rf")
@client.command()
async def slap1(ctx, user: discord.Member, user2: discord.Member = None):
"""*SLAPS*"""
user2 = user2 or ctx.author
user, user2 = user2, user
data = await self.get(
ctx,
"/slap?avatar1={}{}".format(
user.avatar_url_as(static_format="png"),
f"&avatar2={user2.avatar_url_as(static_format='png')}"
if user2 is not None
else "",
),
)
if isinstance(data, dict):
return await self.send_error(ctx, data)
data.name = "slap.png"
await self.send_img(ctx, discord.File(data))```
Can someone explain me this?
Owner-only 👌
thats what i thought
i don't understand what you're saying given the context
how do i create something like commands.is_owner() but for a slash command
they're asking how they can differentiate between an argument being a mention or not.
@pliant gulch so basically it does this
in nextcord
The zerodivision is eaten
Yea, so what I said would work, cause either way unless MemberConverter fails the argument will capture a discord.Member instance, if the member isn't in the message's mentions they weren't mentioned
- Shouldn't it work for slash commands as well?
- Maybe there's something like
cog_slash_command_check(in disnake there's such thing)
using User.mentioned_in() is flawed as they didn't mention having a user object. checking message.mentions is also flawed as user/member mentions aren't the only one that exist.
doesnt work as well
MemberConverter was an example that i provided of a converter
in discord_slash i know there is something like this
Sorry can't help with nextcord :(
what is your point?
The point being, how is it flawed to use mentioned_in
You don't need call it on a user object, it calls it internally on the user object behind the member
because it can also be a channel or role mention too
Oh that is true, what a big oversight hmmm
btw is it possible to use both js and py simultaneously to make a bot?
Is there a way to check if a discord.User object has a specific role?
I guess you could just do a simple member.id in [obj.id for obj in message.mentions]? You could also use raw_mentions but that does regex search internally
It would be a given that the objects inside of mentions would be snowflakes (for the list comp)
prolly not
peak cronge
Although the raw_mentions does seem quite a bit slower here, as it does a list comp along with a regex search. You could also speed up the first method I showed via constructing a set on the generated list of ids, then using in which is O(1) for sets worst case O(n)
users dont have roles
is it possible to creat a discord bot which is h24 online ? I have a bot rn but when I close my program it logout so I wondered
Can a car drive without its engine
It tends to be that way. Consider a VPS or something of that sort.
@sage otter It depends how you define driving
Well was asking because I was a bit curious
Also btw how do I go about with creating a command like this
what is pillow
!pypi pillow
Thanks
how do i add a embed colour to my on_member_join command pls?
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
color kwarg
@bot.command()
async def e(ctx):
choose = ["e", "2"]
e = random.choice(choose)
await ctx.send(e)``` how do i add a timer to this command
import discord
import asyncio
import random
import praw
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "-", intents = intents)
@client.event
async def on_ready():
print("Bot is ready")
print("-------------------------------------")
reddit = praw.Reddit(client_id='T-OdEbfZQFXYLfRzxOz7Hw',
client_secret='W0F30XopqXJ1MQAcsAfvYC97qR21Ag',
username = "Joseph-Memestar",
password = "48667866@#Xx",
user_agent='cumzone',
check_for_async=False)
@client.command()
async def meme(ctx):
check_for_async=False
subreddit = reddit.subreddit("izlam")
all_subs = []
top = subreddit.hot(limit=50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title=name, url=url, color=0xE0AE69)
em.set_image(url=url)
await ctx.send(embed=em)
# Purge Command
@client.command(aliases= ['purge','delete'])
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount : int):
if amount == None:
await ctx.channel.purge(limit=1000000)
await ctx.send(f"{941087269673119816} Messages are being sent to the afterlife!")
await asyncio.sleep(1)
await ctx.send(f"{amount} messages have been deleted!")
else:
await ctx.channel.purge(limit=amount)
await ctx.send(f"{941087269673119816} Messages are being sent to the afterlife!")
await asyncio.sleep(1)
await ctx.send(f"{amount} messages have been deleted!")
client.run('token')```
` raise RuntimeError('Event loop is closed')`
`RuntimeError: Event loop is closed`
can anyone tell what's the issue here?
so my bot sends each user a code in dm when command used but i wanna do something like ?code and bot says: ur code is? then u send ur code and the bot checks code then
bro lmao
😰
oh sorry i thought its something else
do you know the issue tho
i think you should move the " client on_ready " under the code and above the client.run token
im not sure but for just thinking
so my bot sends each user a code in dm when command used but i wanna do something like ?code and bot says: ur code is? then u send ur code and the bot checks code then
well ik how but hard to explain
this is the correct way to delete a msg in on_messsage event right?py await message.delete()bc my bot doesn't seem to be deleting the msg
i reccomend ctx
from discord.ext import commands
yeah but this isn't a command, it's a on_message event for auto moderating msgs that contain 'bad' words
yep, but on_message doesn't take ctx
bro what
@flat solstice also someone told me to use wait_for
ctx is context of the msg?
its for a filter
so no
ye
there the same
true
@slate swan so is that the correct way to do it?
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
that is the way
praw isnt async
so use asyncpraw
!pypi asyncpraw
isn't that what I'm doing? 😕
can your bot delete msgs?
await msg.delete()
depends on params
it should be able to, it has admin
oh mb i thought that was a question haha
Can we see all your code?
https://sourceb.in/X4TF3GwLav py await message.delete() It's this bit that's not working but everything following does (well about from the commented out if statement for @everyone but I'm hoping message.mentions_everyone will fix that
probably doesnt work because of indentation
and have you loaded and added the cog?
yep
try printing something
got it to print message, but even tho it's not deleting the msg it is sending the first msg
okay it's deleting the msgs now but if another bot gives the member a role which denies that member from sending msgs then the bot won't delete the message, interesting.
I'm also not sure what is going on but msgs with @everyone in them don't seem to be getting deleted, even tho that's also a default bad word, and the bot's not sending the user any msgs about it
can you elaborate? are there any errors being thrown, etc?
?? lol what
hi timtoy lol
Is possible to create
DmAllUsers on server where can i type command with self bot
Im try to make but it didnt work
nope
against tos
On my server 5 membrs
For bot update messages
dm all users in a server is against tos and a selfbot is against tos as well
so pls move on
what server are you from
wdym by server
how do u recognize me
here
oh
yesterday
im the guy with the dog pfp
Ok i will move to classic bot
Then can i create
!botupdate
And bot will send message to all user on server
Bot Updated datetime?
o ok
still no
stop trying to message all users on a server
Kk
don't expect help when doing something that is inherently bad
guys please help me to hack nasa
You'll get rate limited
So there's no point
even if you sleep on the action its still against tos
nope I'm not getting any errors
okay it's deleting the msgs now but if another bot gives the member a role which denies that member from sending msgs then the bot won't delete the message, interesting.
well as I said; if bot-b gives the user a role, that has send msgs permission denied, whilst bot-a (the bot i'm writing rn) is going through it's message checks then bot-a is unable to delete the message
I also have @everyone as a bad word which the bot should be deleting like the other bad words but isn't for some reason. I was doingpy if "@everyone" in message.content: and then tried doing py if message.mention_everyone: but that didn't work either
Ping everyone and check what the message content is
Is it actually @everyone?
I wanted something like this how do I do it with embeds a little lost any videos or documentation on it?
slash command?
Do users have permissions to mention @everyone?
^ they shouldn't in thje first place
weird thing, it's not printing msg content
yep with allowing user to input
nope they don't have perms for that
depends on what lib you use. disnake would be best
discord.Message.mention_everyone is only true if the message actually PINGS everyone
using nextcord bruh
Thus would only be true if everyone was mentioned and the user had permissions to do so
Not sure why it isn't detecting @everyone using in
don't think they have slash commands yet
they do
its available to all though
all I need to knw is what to use I am not finding the right term to search there docs
!d nextcord.slash_command
What are you trying to do? Sending an embed?
class nextcord.slash_command(name=..., description=..., guild_ids=..., default_permission=..., force_global=False)```
Creates a Slash application command from the decorated function. Used inside [`ClientCog`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ClientCog "nextcord.ClientCog")’s or something that subclasses it.
!d nextcord.ext.commands.Bot.slash_command
slash_command(name=..., description=..., guild_ids=..., default_permission=..., force_global=False)```
Creates a Slash application command from the decorated function.
title, link, reason
I know how to create embeds but dont know how to create the slash command to give multiple prompts lol
params in the function
@slash_command(name="name")
async def command(ctx, reason: str = None, ...):
...
ah okay, also weird that it's not printing the msg content of the @everyone msg, it's like it can't even see that in the msg contentpy else: print(f"\nMessage event: {message.content}") await message.delete() try: await message.author.send(f'Your message had `{", ".join(bad)}` in it, This word is conssidered a "bad" word on this server so your message was removed.') except discord.HTTPException: await message.channel.send(f'{message.author.mention} `{bad}` is conssidered a "bad" word on this server.') if "@everyone" in message.content: #if message.mention_everyone: try: await message.author.send(text) except discord.HTTPException: await message.channel.send(f'{message.author.mention} {text}')
What is message.content printing out as
nothing, it's not printing it when the content is @everyone but If i use something else like act2 it prints
Are you able to print the repr of the message object
so I manged to get it to print @everyone by bundled it in a msg with something elsepy Message event: @everyone act2and what do you mean by repr, do you mean the full message object?
Yea just print the message object
And perhaps do you have another message event that might be blocking this one if it detects an @everyone?
Message event: @everyone
<Message id=941135879995555880 channel=<TextChannel id=777221027125657610 name='🤖│commands' position=27 nsfw=False news=False category_id=500590783548620800> type=<MessageType.default: 0> author=<Member id=791394319075377243 name='SparseSpace' discriminator='9108' bot=False nick=None guild=<Guild id=448405740797952010 name='GTA Online Friendly Sessions' shard_id=0 chunked=True member_count=379>> flags=<MessageFlags value=0>>```This is after I removed the print statement above the logic, so I think the `@everyone` is getting eaten up by that```py
if bad := [word for word in data[28] or self.bot.config.default_bad_words if word in message.content]:```
what?
where is the rest of the command
weird
dpy or are you using a fork
well its old and discontinued
prolly disnake
or you can use a non fork
like hikari
it shouldn't be too much
Do you have some other on_message event that is calling .lower() manually? The wrapper will never lowcase a messages content unless you do so yourself
can someone help
im installing an tar.gz from my cogs folder and i need to put it in requirements.txt
ffmpeg==1.4
ffmpeg @ file:///home/runner/cogs/ffmpeg-1.4.tar.gz
um is that right
its in a github folder
i need to knwo the directory of the file
im hosting it in heroku
For testing
Or smth
You can verify you didn't touch source code by removing and reinstalling the package
I'm trying to use schedule to close and open a channel on certain days but I'm getting this error
What does this mean and how can I fix it? I'm following this (https://pypi.org/project/schedule/) pretty closely I think...
Guys important question...
How do i make a dropdown ui (on nextcord) one use only, I noticed that you can reuse it even after its been used which I do not want
!d nextcord.ui.View.stop
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
class disnake.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://docs.disnake.dev/en/latest/api.html#disnake.ui.Select.values "disnake.ui.Select.values").
New in version 2.0.
Stopping the view stops all parts of the view including the select
Ah
typechart = {
"Normal":[1,3,2,5,1]}```
how would I get the word "Normal" from the dictionary?
!e
typechart = {
"Normal":[1,3,2,5,1]
}
print(list(typechart.keys()))
@mortal dove :white_check_mark: Your eval job has completed with return code 0.
['Normal']
@hardy wing Is that what you're asking?
#python-discussion is a thing
oh didn't see that channel
no just like how to get only the word "Normal" not the entire list
like if there's multiple elements I'd just want the string normal
or is that impossible
Not really, because dictionaries are unordered
dam 😔
Although I still don't really understand what you need, can you elaborate?
I'll just put a member of the dictionary called "name" and make t defined as normal
just wanted to get the name of the element
I don't see what that would do, because you would need to know the name of the key to access only it
the dict is plugged into a function and wanted to get it's name
They are ordered by insertion
dictionaries as of like, 3.7 are ordered based on insertion
You also have things such as collections.OrderedDict for older versions
how do you fix this?
from what I see
ig it's just that your python version doesn't support whatever you're trynna install
This error might be because the module is not compatible with your system or python version. It happens sometimes on my rpi.
are you running an elevated prompt
do you know which i should python i should download?
what do you mean i’m not that good with coding and stuff
Which version do you have rn?
did you run cmd as administrator
i have a bunch of versions could that be an issue
yes
you really shouldn't unless there's a requirement to do so
you think that’s the issue?
no, more of a principle thing.
do you know how to fix?
what is python3 --version
let me get it
what cmd do i run to fix it
For windows it would be python -m pip install --upgrade pip
...
i know what it is... im asking them to do it...

@slate swan chances are if your python is <3.8 then this library won't function for you.
so under 3.8 it’ll break?
according to their setup.cfg it requires >=3.8
okay
imma download 3.8
@bitter perch what if i have a bunch of python versions installed
what happens?
py -<version> to select one.
Pip should have a more verbose error when it comes to python version constraints
PS C:\Users\austi> py -3.9 --version
Python 3.9.5
PS C:\Users\austi> py --version
Python 3.10.0rc1
avoid pip, embrace poetry, never deal with that shitty thing
Exactly 💯
okay holdup let me try all your ideas
Poetry is just great
do you have guild member intents?
idk you mentioned something about checks and whatnot
