#discord-bots
1 messages · Page 873 of 1
PC. Mobile do be uncertain
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Federico\Desktop\AquariusMC Bot\AquariusMC Tickets\bot.py", line 62, in button_callback
ticket_channel = await interaction.guild.create_text_channel(name=f"{ctx.author.name}", overwrites=overwrites, category=TICKET_CATEGORY)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\guild.py", line 1170, in create_text_channel
data = await self._create_channel(
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\guild.py", line 1051, in _create_channel
"id": target.id,
AttributeError: 'property' object has no attribute 'id'```
tf is target now istg dpy internals
could be
TICKET_CATEGORY = bot.get_channel(TICKET_CATEGORY_ID)```
nope not that
@junior falcon can u show the whole command?
sure
Hey @junior falcon!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
@maiden fable hunter hunter
hm?
nothing smh, wanted to ask something
ill take a punt that your overwrites are wrong
whats SEE_TICKETS
a role id
you need to pass role object
or a discord.Object
hence the error - do ctx.guild.get_role(id)
@manic wing👋🏻
hello
tbh i think the green background is wrong color for the syntax highlight hard to see
a dark color would be good
anyone here who is owner of website? maybe can fix a darktheme n light theme?
why is the name the same as what its defined as, does that change anything?
not my code - i just complained on how bad it is to read even
only change font made a big diffrence
I don't see the problem
maybe TICKET_CATEGORY being undefined
@manic wing
what
I really dont get whats wrong with my code
I just wanted to ping you to say sorry
what
Thats my full code:
https://paste.pythondiscord.com/ihovuludeg
@junior falconwhats error?
nah u just didnt use english 😛 it was ur language canale and it was declared on function so that was my bad
yh
How does embed work on bot?
Like how do i set it up to send messages as embed?
send method has an embed kwarg
@junior falcontbh dont know man :S
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
i dont know if this matter but
overwrites = {
discord.Guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
discord.Guild.me: discord.PermissionOverwrite(view_channel=True),
SEE_TICKETS: discord.PermissionOverwrite(view_channel=True), }
``` you ending with ,
Mhm
!e
d = {"h":"b", "c":"b",}
print(d)
@honest vessel :white_check_mark: Your eval job has completed with return code 0.
{'h': 'b', 'c': 'b'}
i guess dosnt matter
oh fixed let me see
Same error
ofc, but here is i think ur error is about
TICKET_CATEGORY = discord.utils.get(GUILD.categories, name=TICKET_CATEGORY_NAME)
ticket_channel = await TICKET_CATEGORY.create_text_channel(f"{ctx.author.name}-{ctx.author.discriminator}", overwrites=overwrites)
if i print this it return the right category
you dont want await TICKET_CATEGORY.create_text_channel()
you want ctx.guild.create_text_channel("name of channel", category=TICKET_CATEGORY)
something like that
weird, it should have been there
i mean his create_text_channel dosnt know what guild
and create_text_channel has a category
krwarg
Use ticket create embed channel category as category
it worked
thank you so much
one more thing
how i get the avatar of a member?
ctx.author.avatar?
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
yea haha
How can i stop that the bot spam the message into the channel?
I tryed that the bot send a message to an channel if a specific person comes online. But if the person comes online the bot spam the message permanently.
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
what command is it using discord py, for making the bot send a message without a member using a a command if that makes sense. I have an auto update code and i want the bot to send a message every 10 minutes. I just need help on how i can make the bot send a message?
Wait
you can use a task to handle timed events
Hello everyone, I'm looking for someone who can finish me a discord bot, I don't know anything and the person who does it for me is absent, I pay for it, I give the details in pm
!rule 9
no problemos
i have that part figured out, but i need the command that makes the bot send a message
that will never happen
Okay
you want the bot to execute a command in the task?
u can tell anyway would be nice to know probally has some invoke todo
yeah i want it to send a message, not when a member uses a command
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function.
sorry i just got here i didn't see, if someone can help me
learn to make a bot urself
discord.js, discord.py and tbh anything are good
@slim ibexthanks wasnt that complex
discord.js is good to run on node
..
@slim ibexthe invoke
Who likes to run it in a node
what about it? I’m so confused 💀
@slim ibex#discord-bots message
not me, i don't even use discord.js, discord.py ftw, but others may prefer it
oh lol
node.js*
Ok
Ok...
btw, await ctx.send() returns a message obj right?
imagine talking about js in a python server 🙃
irony
couldn't be me
maybe u working for a js fork and here to recruit
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
0
lets go here
Ok
How can i stop that the bot spam the message into the channel?
I tryed that the bot send a message to an channel if a specific person comes online. But if the person comes online the bot spam the message permanently.
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
or does anyone know an other way to let send my bot a message if a specific person comes online?
@nimble plumerelax or i call mod on u
?
Alright
!d discord.Member.status
property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
ok
Im not a spammer 🥺
is there a limit on how often you can call chan.edit()?
you could probably get rate limited if you make too many API requests at the same time or close together
you dont seem to bring much to this channel atm
Not me
adding: try be normal and not abuse API that much for no real purpose and ur fine
I'm not making too many at the same time, I'm trying to update a single channel's name to show the number of people in it and after the 3rd call of .edit() it stops refreshing the name, as if .edit() is stuck on a loop or something, making commands like chan.delete() unable to work as well. (each call of edit has at least 3-4 secs from the previous if not more)
channels dosnt update that often its cached - therefor u try edit but wont see a change - untill some time went by
whats the scope of bot variables
You can access them anywhere
Doesn't even have to be in the file
ok
and any idea how to delete a bot variable
hey im trying to sdit the message when click the reaction edit the numbers of the clicks
Don't use json as a database
!e
myvar = "monkey"
del myvar
print(myvar)
@honest vessel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'myvar' is not defined
ok ok
so in my cog, i am subclassing ui View, will bot variables be accesible there
#discord-bots message like this?
it works , but the count stay in 1 elif the json file shows its 1 that need to add 1 to the clicks
yeah i got that
someone knows why?
;-;
Why i get this error? when i try to use an image from local? it worked in another embed
https://paste.pythondiscord.com/pekajosako
so in my cog, i am subclassing ui View, will bot variables be accesible there
hey there! how to host my bot for free for ever
???
raspberry pi
not unless you pass bot as an arg
how to get the author in on_raw_message_edit?
!d discord.on_raw_message_edit
discord.on_raw_message_edit(payload)```
Called when a message is edited. Unlike [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), this is called regardless of the state of the internal message cache.
If the message is found in the message cache, it can be accessed via [`RawMessageUpdateEvent.cached_message`](https://discordpy.readthedocs.io/en/master/api.html#discord.RawMessageUpdateEvent.cached_message "discord.RawMessageUpdateEvent.cached_message"). The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers the [`on_raw_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_edit "discord.on_raw_message_edit") coroutine, the [`RawMessageUpdateEvent.cached_message`](https://discordpy.readthedocs.io/en/master/api.html#discord.RawMessageUpdateEvent.cached_message "discord.RawMessageUpdateEvent.cached_message") will return a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") object that represents the message before the content was modified.
Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the [gateway](https://discord.com/developers/docs/topics/gateway#message-update).
you would have to get/fetch the message from the message id possibly
!e
print(whoisurfather)
@honest vessel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'whoisurfather' is not defined
where can i get this ? ^ python execution as this one usees
is Pythonbot public?
or can i download same lib he uses?
!src e
Run Python code and get the results.
ty bro

!src
It doesn't use a library to eval the code
how to @ a user
!d discord.User.mention
property mention: str```
Returns a string that allows you to mention the given user.
forgot havent done this in ages lmao
another problem with my ascii art, it either escapes the ``` or has leftover backslashes
i guess i could .replace ``` with ''' but id really prefer not to
Any clue why it doesn't ban the person?
# ---- Ban Command
@client.command(description="Bans an user.") #ban
@commands.has_permissions(ban_members=True)
async def ban (ctx, user:disnake.User=None, *, reason=None):
try:
if (user == None):
await ctx.channel.send("You have to specify an user!")
return
if (reason == None):
await ctx.channel.send("You have to specify a reason!")
return
if (user == ctx.message.author or user == None):
await ctx.send("You cannot ban yourself!")
message = f"You have been banned from **{ctx.guild.name}** for **{reason}**! You may be able to appeal your ban at ///
await user.send(message)
await ctx.guild.ban(user, reason=reason)
await ctx.channel.send(f"{user} is succesfully banned for {reason}! Jeez.")
channel = disnake.utils.get(ctx.guild.channels, name="protech-logs")
await channel.send(f"{user} has been **banned** by {ctx.author} for a reason: **{reason}**")
except:
await ctx.send(f"I cannot ban {user}! *(I am unable to ban a bot / an owner).*")```
Here is the code.
if any error occurs in any of that it defaults to the error you're getting
try putting just the ctx.guild.ban inside the try:except
Wdym
the line await ctx.guild.ban(user, reason=reason) is what actually bans the user
Yeah, right
so why have all of the other user.send, ctx.channel.send, etc in a try: block?
it's probably an error on await user.send() because they've blocked the bot or smth
and because it's erroring there it never makes it to the await ctx.guild.ban
also your variable message is never closed
Yeah I get it.. well what should I do?
move the try:except so ctx.guild.ban is the only thing in it
close your message variable
try:except is suppressing syntax errors
keep your pc on
also @modern fiber you can have the bot see if the user you're trying to ban is the guild owner/a bot
iirc member.is_bot() and member.is_guild_owner()
So I should just do that instead of the current error I got? Will it fix?
sorry?
there are some issues with this:
- Bare Except (you can except
CommandInvokeError - Python doesn’t require parenthesis for if and elif blocks
- Don’t use client, use
commands.Bot(I assume you are usingdiscord.Clientbecause of@client.command) - sending the message to the user will fail if they have DMs closed
user.ban- typehint to
discord.Member ctx.sendinstead ofctx.channel.send- why
if user == ctx.message.author or user == None?
thx @slim ibex
I would typehint to disnake.Member instead of user also
also there's a return missing on your third if statement
Should I do it like this?
if it's in the except block it will only run if the ban fails
hh
so I should use else?
user.is_bot()
else:
if user.is_bot():
await ctx.send("yeah")
@modern fiber ^^
Okay, thanks
Can I add like another else under it?
or should I use "or"?
no there can’t be multiple else
!d discord.User.bot
Specifies if the user is a bot account.
and please read up on what or actually does
Yeah but I need it to check both if the user is bot / or an owner
yeah you can use or
or make different messages for either
Exactly, but then I will add another else or "or"?
if user.is_owner or user.is_bot:
discord.SelectOption(label="Supporto Store / Acquisti", description="Per problemi riguardanti allo store e i pagamenti.", emoji=":money_with_wings:"),
discord.SelectOption(label="Segnala Un Player", description="Se desideri segnalare un giocatore.", emoji=":pencil:"),
discord.SelectOption(label="Segnala Un Bug", description="Se desideri segnalare un bug.", emoji=":paintbrush:"),
discord.SelectOption(label="Appella un Ban", description="Per fare una richiesta di unban/unmute.", emoji=":envelope:"),
discord.SelectOption(label="Altro", description="Se nessuna delle opzioni precedenti è il tuo problema.", emoji=":grey_exclamation:")```
Getting this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.0.emoji.name: Invalid emoji
In components.0.components.0.options.1.emoji.name: Invalid emoji
In components.0.components.0.options.2.emoji.name: Invalid emoji
In components.0.components.0.options.3.emoji.name: Invalid emoji
In components.0.components.0.options.4.emoji.name: Invalid emoji
In components.0.components.0.options.5.emoji.name: Invalid emoji
What format i should use?
you won't need an or if you have an if statement for each fail event
mk ty
if is bot:
if is owner:
if is user:
put a backslash before you send an emoji to get the raw emoji.
e.g
📝
with backslash
\📝
but some emoji with backslash return the text
oh that's neat, didn't know that
thats with custom emojis, those work, just copy the text
oke thanks
use emoji unicodes or <:name:id> format
or if its a nitro emoji its <a:name:id>
ive been using it for awhile, pretty handy
Check DMs please.
@client.command(description="Bans an user.") #ban
@commands.has_permissions(ban_members=True)
async def ban (ctx, user:disnake.User=None, *, reason=None):
try:
if (user == None):
await ctx.channel.send("You have to specify an user!")
return
if (reason == None):
await ctx.channel.send("You have to specify a reason!")
return
if (user == ctx.message.author or user == None):
await ctx.send("You cannot ban yourself!")
message = f"You have been banned from **{ctx.guild.name}** for **{reason}**!"
await user.send(message)
await ctx.guild.ban(user, reason=reason)
await ctx.channel.send(f"{user} is succesfully banned for {reason}! Jeez.")
channel = disnake.utils.get(ctx.guild.channels, name="protech-logs")
await channel.send(f"{user} has been **banned** by {ctx.author} for a reason: **{reason}**")
else:
if user.is_bot():
await ctx.send("yeah")
if user.is_guild_owner():
await ctx.send(f"I cannot ban {user}! *(I am unable to ban a bot / an owner).*")```
Can you help me connect those two "if" statements? My brain kinda stopped working.
use elif in your try at the start,
if:
a
elif:
elif:
should I use elif for the second if statement or?
else:
if user.is_bot():
await ctx.send("yeah")
if user.is_guild_owner():
await ctx.send(f"I cannot ban {user}! *(I am unable to ban a bot / an owner).*")
the two if statements arent indented
any if statement in the same indent after the first should be elif
haven't been here in a while lol
@bot.command(name="join")
async def soundFXCommand(ctx):
if ctx.author.voice:
channel = ctx.author.voice.channel
voice= await channel.connect()
choice = random.randint(1,3)
source = FFmpegPCMAudio(executable="C:/Users/pc/Documents/Projects/ffmpeg/ffmpeg/bin/ffmpeg.exe", source='greetings/greeting_{choice}.mp3')
player = voice.play(source)
print("played")
else:
await ctx.send("You aren't in a voice channel!")
This is my code to play something but nothing is played, eventhough "played" is printed
Hello guys. I have been working on my bot for a while now and I was wondering if I can make my bot send a message whenever I type something in my console. Is it possible to do so? I didn't find any implementations that worked for me so far.
no f string, your variable is wrong
oh shit
xd
peepo toilet
lmao
best emoji
Like this?
else:
if user.is_bot():
await ctx.channel.send("yeah")
elif user.is_guild_owner():
await ctx.send(f"I cannot ban {user}! *(I am unable to ban a bot / an owner).*")```
yeah
upvotes
also elif ctx.guild.owner.id == member.id
so it doesnt try to ban the owner
why not use the bot property instead of a method?
the if statement after it isnt indented
It's a public bot, ID won't work
How should I make it to be indented?
highlight the if and elif statements and press tab
aswell as all the code inside of it, just indent it once it should work
or just check the member id with the bots id
i dont even know why people make simple things complex
thats coding in a nutshell
how do I highlight them
just indent them s.m.h.
a ban command shouldn’t be this complicated. You can extract certain things into separate methods so you don’t have this one large command that is hard to track
ctx.channel.send
So i'm building a role selector bot. Is there a way to create a user timeout per use. What i mean by that is something that prevents the same person clicking a ton of roles over and over causing the bot to lag or freeze?
ikr
select
i mean my ban command is complicated because it checks if the user trying to ban doesnt have a lower top role pos than the user they are banning
Like this man?
yes
What's wrong with else statement?
just ban the user from the server and enjoy
How do i see if a user is on timeout?
@modern fiber your code is over complicated and hard to read. I recommend you refactor it and it will be way easier to write and understand
!d disnake.Member.communication_disabled_until
No documentation found for the requested symbol.
Hmm lemme see
I always make shit complicated 😂
Can you just help me whats currently wrong with me "else" statement? Ill work on redoing those sometime I get more time
heh?
hah i don't want to do that
!d disnake.Member.current_timeout
property current_timeout```
Returns the datetime when the timeout expires, if any.
New in version 2.3.
wait i ran the wrong command, im high
Huh
@slate swan have u ever made an antispam?
Wait how do you check if the bot is in a voice channel
Wonder how that came up lol
!d discord.Member.voice
property voice: Optional[discord.member.VoiceState]```
Returns the member’s current voice state.
and if so how do you return the voice object
ctx.guild.me.voice
is there a way to prevent command spam
tok
do you have an if statement above it
What does your linter say about those squiggly lines
command cooldowns
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
does that work per user or just as a whole
you can make it work for users or the whole guild
too bad you can still spam commands and spam the error
depends on the BucketType
then get some rest (:
channel, guild, user, whatever you want
thank you i'll check that out!
def want user
u do know that there is an on_command_error event, right?
I got those
no i mean the message that the error handler sends
Yea, user checks for cross server cooldowns whereas member checks only for a single server cooldown
nothing gonna happen, im tired 24/7
oh that makes sense
else is used like this
if my_dog == "Cute":
print("ok")
else:
...
simply just timeout the person in that case
that sucks 😔
so many pep8 violations
can I dm you?
👀 good thing @final iron isn't here
is there a way to add that to @client.event?
ikr
ot but I just came to know today that I suck at Valo and Apex both (but I suck more at Valo lmao)
prob not i can see how that would be confusing
but im not always online, i might do something like
blacklist = []
blacklist.append(ctx.author.id)
await asyncio.sleep(5)
blacklist.remove(ctx.author.id)
@bot.event
async def on_command(ctx):
if ctx.author.id in blacklist:
return
Yea blacklisting the best
ofc i can make it better, thats just a small snippet
@modern fiber let me give you some suggestions:
- Extract this into separate functions
- Follow PEP8 (ex: no parenthesis in if statements
- Read disnake docs
- It seems like you know some Python, but maybe learn a bit more before continuing
i just need to make a command.before_invoke which im really confused on its syntax @maiden fable
Hey
its just a simple deco
Hi
you are speaking in the presence of a diamond 3 ranked valorant player (ot)
Meh, I wasn't even able to do a single kill today in valo
🗿
Anyone ever managed to make a bot send a message throught the console?
What are unique things one can put in a userinfo command? Like things not seen often
I have been trying for a half an hour and if anyone could help I would appreciate it.
print function in a command ?
what do you mean send a message through the console
the other way around
from the console to the channel
it doesnt work like that for me for some reason
What are you doing right now?
code
🤔 I did voice= await channel.connect() to get the voice object but how would I get this object if I already was in a vc
@bot.command()
async def example(ctx):
await ctx.send("example")
@kindred oracle
Long story short my bot is in a server which I abadoned a long time ago and I would like to talk with them first of all. For now I just made a logger and asked for an invite for me to join.
voice object?
thanks
ctx.voiceclient?
yes that works?
ok thanks
!d discord.VoiceClient.is_connected
is_connected()```
Indicates if the voice client is connected to voice.
will check if its in a channel already or not
yeah
I thought u meant ctx.voiceclient is a thing lol
!d discord.ext.commands.Context.voice_client
property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
I mean, they said ctx.voiceclient and u said yeah, soooooo
@commands.command()
@commands.before_invoke()
async def mycommand(self, ctx):
print("i want to die")
i mean, you can remove the underscore if you want
no thanks
that isn't how it works
@bot.command()
async def cmd(...):
. . .
@cmd.before_invoke()
async def before_cmd(...):
. . .
mess with the internals 
Yes. Time to use a for loop and setattr to remove the _ and set the aliases of each attr :D
and then get bullied by PEP8 followers

worshippers*
PEP8 officers 👀
How can i stop that the bot spam the message into the channel?
I tryed that the bot send a message to an channel if a specific person comes online. But if the person comes online the bot spam the message permanently.
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
or does anyone know an other way to let send my bot a message if a specific person comes online?
oh still didn't fix it?
Yes i dont know how. I dont know the problem
spam?
show yr on_message event
can you show MYID var though
Its his/her ID
Yes
data types
@livid jacinth is it an int?
I just replace my id with the word
What do you mean?
the variable MYID
uh did you put the id in quotes
Is it an int or str?
also, @livid jacinth show yr on_message event
i'll leave, help god here to help 
lmao why tho
why not
No i just have one on_message event
show
cz half my brain cells are already dead 
@bot.event
async def on_message(message):
if message.content == ('prefix'):
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
pre = prefixes[str(message.guild.id)]
embed=discord.Embed(color=0xffffff)
embed.add_field(name="Serverprefix:", value=f'**The server prefix is "{pre}"**')
await message.channel.send(embed=embed)
await message.add_reaction('📧')
very creative username, you have
yeshhh, char the remaining
that is why I am here
That is the on_message event
add this at the top of the function:
if message.author == bot.user:
return
which isn gonna solve the problem
@bot.event
async def on_message(message):
if message.content == ('prefix'):
if message.author == bot.user:
return
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
pre = prefixes[str(message.guild.id)]
embed=discord.Embed(color=0xffffff)
embed.add_field(name="Serverprefix:", value=f'**The server prefix is "{pre}"**')
await message.channel.send(embed=embed)
await message.add_reaction('📧')
``` So?
hmmm idk someone else advised to do it but they most probably missed the message so I am just telling them to do so lol
did you put the id in quotes or not @livid jacinth 
lmao ash do be pissed
No
nah me happy
the emoji says otherwise but okay 👀
okay.....can you run the code again and show the output?
It doesn't send any output..? @slim ibex
# ---- Ban Command
@client.command(description="Bans an user.") #ban
@commands.has_permissions(ban_members=True)
async def ban(ctx, user:disnake.User=None, *, reason=None):
if (user == None):
await ctx.channel.send("You have to specify an user!")
return
elif (reason == None):
await ctx.channel.send("You have to specify a reason!")
return
elif (user == ctx.message.author or user == None):
await ctx.send("You cannot ban yourself!")
return
elif user.bot:
await ctx.channel.send("yeah")
return
elif ctx.guild.owner.id == user.id:
await ctx.channel.send(f"I cannot ban {user}! *(I am unable to ban a bot / an owner).*")
return
message = f"You have been banned from **{ctx.guild.name}** for **{reason}**!"
await user.send(message)
await user.ban(user, reason=reason)
await ctx.send(f"{user} is succesfully banned for {reason}! Jeez.")
channel = disnake.utils.get(ctx.guild.channels, name="protech-logs")
await channel.send(f"{user} has been **banned** by {ctx.author} for a reason: **{reason}**")```
so in my cog, i am subclassing ui View, will bot variables be accesible there
also, pretty sure you ca use a presence event if you are above dpy 2.0 or on forks or api wrappers
No it did't worked
other maintained
The bot spam the message again
Got a question. I'm trying to make a system where if someone tags the channel in their argument, it sends a message in that channel but I'm not sure how to do that
just add a bot argument in the init function and pass bot when you subclass it?
whats an api
bruh
screenshot
Application programming interface 🗿
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
half my brain cells are already dead and am sleepy, don't make me shout at u lmao
LMAO
ok ty
When they tag the channel, it prints out as <#id> I want to turn that into a channel object but I don't know how to do that
wait where u sending 123 in code?
i see its getting triggered multiple times
u r sending idk according to the code
dont make me cry now
actually u solved half the issue by telling them to send a screenshot
yes i but i replaced in my code
just the message
stop playing with us rn and stick to one code please 
lmao
huh, dunno wtf i did wrong, im not getting any events ; - ;
lmao
u need members intent iirc
i do have intents enabled
Ah wait
u using dpy 2.0?
yes
!d discord.on_presence_update if u r using 2.0
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
yes, both members, and presence is enabled, as shown
....?
ow wait
Thanks for killing my remaining brain cells
why even enable intents explicity when you can have them all 
is that different naming for method?
yea...
my bad, thx
on_presence_update smh
I think I will just go away from here 😔
presence event?
u using discord.py?
yes
@slate swan can u try reproducing this bug with disnake/any other fork please? I cannot really open VSC rn
im on phone myself
dpy2.0. . hol up ill try asking in dpy disc
i dont think disnake's gonna have that bug tbh
It shouldn't be
imma head out, good luck both
thx, anyhow the best i can say is adding some form of timer, giving it a 30 second refresh ig
Yea await asyncio.sleep seems like a viable option
spamming idk every 30 sec
BTW imagine if messages were sent through the gateway 😔
lmao your server chat is gonna die
define a common variable, change it to 1 whenever the event is triggered and use conditionals to check that, then put up a task of 5 mins to reset the variable to 0 so that you can flex that your bot runs on cheap binary
I think I will just go from here before all my brain cells die, trying to understand what u just said cz I am a bit too sleepy lmao
go to sleep hunter
gotta complete this chapter first
before you know it you'll be using pop in dictionaries
give me tiktakto code with button ._.
see the dpy repo
what is tiktakto
it has a ttt example
I've do it like u but now the bot dont send anymessage
Tic-Tac-Toe
oh dpy2.0 changes the method name, your <2.0 so should stick with the method name you had
gimme 2 seconds and ill give you a fixed up version . . .
oh okay
hey, try removing the pass
oh when I was looking at the code I was wondering why there was a pass in there lmao
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ActionRow' object has no attribute 'label'
what is that
For using postgresql with a Discord bot, what's a good enough free cloud host?
heroku? maybe
Well the pass keyword is just a dummy keyword just for the sake of completing the syntax to prevent getting any syntax errors, so it is useless there, but doesn't really affect anything
iirc it works only for 22 or smth days a month
Mhm
welp, shouldnt make a difference if theres a pass at the end tho
even the database? ew
yea
it just is weird
It's like 1000 hours a month
it's like a space before the opening bracket in print statements
I mean, u r still getting 22 days on the free plan, what else do u expect from them lmao
Okee
500*
fml, my syntax highlighting just gone whack ; - ;
1000 hours are like 40 days lmao
meh, id rather use the jsonbase api 😔
I'm looking at the thing and it says 550-1000 Dyno hours per month
or just look into https://deta.sh ezzz
Oo, that deta thing seems good, would I be able to use it for hosting a db?
They have their own DB, like postgres is one, mongo is another and stuff
I'd use SQLite3 but I forgot I need to access the db on my pc too
Ohhh, ok.
Deta Drive is a managed, secure and scalable file storage service with a focus on end-user simplicity.
https://docs.deta.sh/docs/base/about
NoSQL DB
Deta Base is a fully-managed, fast, scalable and secure NoSQL database with a focus on end-user simplicity. It offers a UI through which you can easily see, query, update and delete records in the database.
damn , this is some good stuff, I'll use it for my next school project 
I tried to run a discord bot on there, well the only reason it didn't work was cz the website dies as soon as someone logs off off it, soooooooo
Sure it is damn good
So do I use base for the db?
list(bot.commands)
Yea, base for db and drive for files
ahh my basics
its fine
thnx
knowing that help can always be taken, makes a person lazy to try or think on their own
anyways, im going to study now, bye
i didn't try it yet
Ah okay
but yeah it has to work i just couldn't recall it
hello?
uhh, just trying to get it to work . - . seems ive done something wrong
oh nvm, i just didnt wait long enough for my presence to change . -.
right all done
right i understand your not currently using a cog, so heres my implamentation:
where in the initializer im setting self.last_invoked = datetime.now()
what this does, is it waits 30 seconds before being able to invoke the command again
why not just add await asyncio.sleep(30) tho
; - ; or you could do that,
i guess im useto unity, where i gotta keep the update function going . _ .
Hahaha
I can't make an account in deta :/
~~right guess ill just show both implamentations:
my one which is over engineered and dumb: ~~ the working method
last_invoked = datetime.datetime.now()
@bot.event
async def on_member_update(before, after):
global last_invoked
if (datetime.datetime.now() - last_invoked).total_seconds() > 30 and str(after.status) == "online" and after.id == MYID:
last_invoked = datetime.datetime.now()
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
~~the preferred cleaner method: ~~ dont work on testing, asyncio only stops that scope,
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
await asyncio.sleep(30)
Let's take this to #ot0-psvm’s-eternal-disapproval
Oh, nvm, it got filtered as spam lmao
Oh hahaha
Wait I just realized - wouldn't it be able to invoke the command while it's still sleeping, as it won't make a difference invoking
It'll just pause the current invoked instance of the command iirc
Lemme test
Hey, i tryed both methods and at the first i get an AttributeError: module 'datetime' has no attribute 'now' and at the second i dont send anything without an error or something.
oh, you may have imported datetime, ive imported it a tad different
welp, just change the datetime call to datetime.datetime.now() instead
Why does datetime have to be like that lmao
. - . file name is datetime and the class is datetime
yup i was right, asyncio.sleep does nothing, gotta use a var outside of the scope for it to work (aka my not so dumb method)
Okay i've replace it as you've said but it also dont work
@livid jacinth i fixed it so it should work for you now (top method)
0.o what error?
I dont get an error but the bot dont send an message
huh strange. . lemme give it a try on another bot instance that dont use cogs
Hey is there an official documentation?
nevermind
Although i have a question still. Should I be able to make a discord bot just from the documentation?
how to access bot stuff in ui View subclass like bot.commands etc...
Is there a way to write a bot more efficiently than just a bunch of if message startswith blank then message send?
ofc, commands is what they're called
@kindred oracle https://vcokltfre.dev
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
this ;-;
Yes
Oh thanks a lot. But I meant if I should be able to write it by the docs and without any other help. I was reading one when I was trying to achieve something but I got lost pretty fast and had to google stuff.
You mean creating a function for sending a message? Then there would still be a million send_message('!command', 'response')
as long as you don't use YT as a source, you should be fine
ever seen a simple bot using commands?
It helped me with like what atteibutes a guild a member or a role has etc, but writing the code is a bit different
Oke
check out examples etc
uhh how do you get intents to work with client?
.
i only used commands.bot
same thing as with commands.Bot
ah thx,
commands.Bot is a subclass of discord.Client
how to access bot stuff in ui View subclass like bot.commands etc...
intents = discord.Intents.default()
intents.members = True
intents.typing = False
intents.presences = True
bot = commands.Bot(
command_prefix = get_prefix,
help_command=None,
intents=intents
)
No i using discord.bot
ye it working just fine
got it to finally show up ; - ; had to wait 30 sec before changing my presence again . _ .
import datetime
bot.last_invoked = datetime.datetime.now()
@bot.event
async def on_member_update(before, after):
print(";-;")
if (datetime.datetime.now() - bot.last_invoked).total_seconds() > 30 and str(after.status) == "online" and after.id == ~ change to your ID ~ :
bot.last_invoked = datetime.datetime.now()
channel = bot.get_channel ( ~ change to channel ID ~ )
await channel.send(". - .")
ofcourse you will need to change both your ID and chennel ID for it to work
setting your last_invoked as global in your function ain't it
use a botvar instead at least
i dont usually make bots without cogs, but that is how ive done it on my other example
client.last_invoked would be great
does it have access to client tho?
apparantly it do, huh
ofc, that's where the @client.event decorator comes from
i see, didnt realize its accessible inside the scope too,
I'm trying to make a config command, how do I make it so that the bot listens for an answer to a command?
For example
/config
Bot : Welcome to the config menu
Please state the welcome channel:
User : #welcome
The code I have atm is:
import disnake
from disnake.ext import commands
from deta import Deta
import os
from dotenv import load_dotenv
load_dotenv()
project_key = os.environ["project_key"]
deta = Deta(project_key)
config_db = deta.Base("Config")
class Config(commands.Cog):
"""Saves a config to the Deta database."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@command.slash_command()
async def config(self, inter)
def setup(bot):
bot.add_cog(Config(bot))
print(" | Loaded Extension: Config")
print(" | ")
I'm using Disnake btw
what you're looking for is a wait_for
How do I use that?
examples are stated in the docs
@livid jacinth all fixed up, that should be good, lemme know if it dont work
gl hf
GL maybe, HF fuck no
Yess it works < 3
Thank you
👍 that good!!
(logbot)
class HelpMenu(View):
def __init__(self, bot):
self.bot = bot
super().__init__()
options = [opt(label="Fun"),opt(label="Utility")]
@select(placeholder="Choose a category", custom_id="help", min_values=1, max_values=1, options=options)
async def callback(self, select, interaction):
if select.values[0] == "Fun":
embed = Embed(title="Fun Commands!", description = "Have fun with these commands", color = interaction.user.color)
for i in list(self.bot.commands):
if i.brief == "fun":
embed.add_field(name=i.name, value=i.description)
self.bot.message.edit_message(embed=embed, view=self)```
this doesnt seem to add fields to the embed
ever tried printing something in the if statement?
no
well, you should
debugging 101
fuck debbuging
oki
just do print(select)
or print(help(select))
@potent speardont u abuse print when coding?
i do
print("can u see me?!")
I should definitely learn how to properly debug, yes
why nvr need debug causeno you knowur child
you khnowyour own childmy spaceisfuzzed
bye
i want the bot removes the reactions of a specific channel whenever someone tries to react in it... but this code are not working
@client.event
async def on_reaction_add(reaction, user):
if user == client.user:
return
ticket = '📩'
channel = reaction.message.channel
canal = client.get_channel(948352556596351030)
if reaction.emoji == ticket and channel == canal:
await reaction.message.remove_reaction(ticket, reaction.message.author)
I'll do a quick rewrite
!d status
Rich can display a status message with a ‘spinner’ animation that won’t interfere with regular console output. Run the following command for a demo of this feature:
python -m rich.status
``` To display a status message, call [`status()`](https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.status "rich.console.Console.status") with the status message (which may be a string, Text, or other renderable). The result is a context manager which starts and stop the status display around a block of code. Here’s an example:
```py
with console.status("Working..."):
do_work()
``` You can change the spinner animation via the `spinner` parameter...
if reaction.message.channel.id == 948352556596351030 and str(reaction.emoji) == ticket:
await reaction.message.remove_reaction(ticket, reaction.message.author)```
you didnt do discord.Embed()
he most likely imported it
i was just suggesting something
@echo lagoon do you know how i can trigger the event by an activity like playing a game or something?
?
Can I use wait_for in Disnake more than once?
Of course
await wait_for(...)
await wait_for(...)
```?
Oh- ok ty
You can also run it within a loop, which might be easier
say you have a list of questions, you can iterate through that and wait for a response
How would I do that?
questions = ["somethin", "something else", "something else too"]
for question in question:
answer = await wait_for(...)
# do something with answer
The answers are getting saved to a db. Is there a way to make it go to the db within the loop?
yeah the same way you might outside of a loop
The way I'm doing it atm is
config.insert({
"welcome": welcome,
"announcements" : announcements
})
So each of the answers is saved to a variable
I've only tested this on a terminal
You can substitute answer for that
if you're a smart man, you'd make a config question by question, and at the end of the for loop, you just insert it at once
That would work as well, probably would be faster too actually
That's what I'm doing
So each embed has its own name, so welcomeEmbed sends the welcome config, announcementsEmbed sends the announcements config
Instead of a list, you can have a list of tuples that specifies what column it should be inserted into the db
Columns are the ones going down, right?
right xd
questions [
("welcome", "Please mention the welcome channel"),
("annoucements", "Please mention the annoucements channel"),
]
data = {}
for column, question in questions:
answer = await wait_for(...)
data[column] = answer
config.insert(data)
Does anyone have good host recommendations?
Amazon web services
Their EC2 instances are perfect for hosting bots
Are the EC2 instances free?
1 year free trial
They have a free tier
with some limits, I'm currently using one
700 hours each month for 1 year on t2.micro instances
I'm using a full fledged one since I'm paying but it's awesome
- I also have other hosting needs (domain with route 53, storage buckets with S3, and a little bit of machine learning)
it provides everything in one ecosystem
it hasn't worked yet...
when i click on reaction, it don't disappear
Probs check presence change?
What do you mean?
make sure the event even gets invoked first of all
Uhh there should be a user activity - I'm not at home so I'll get back to you on it later
How do I make the bot wait for a channel to be sent?
Okayy
What do you mean by "wait for a channel to be sent"?
You'd just have to wait for on_message
then use TextChannelConverter to see if it's valid
What's TextChannelConverter
You don't even need to do that, unless you want to convert more than just mentions into a text channel
Message has a channel_mentions attribute which is a list of channel objects that were mentioned in the message
Yeah true
!d discord.Message.channel_mentions
A list of abc.GuildChannel that were mentioned. If the message is in a private message then the list is always empty.
It's what's used under the hood when you typehint to discord.TextChannel
Ah ok
But doing what andy said is probably eaiser
And it's a list so just get the first one
@commands.slash_command()
async def config(self, inter):
"""Presents the user with a config command"""
welcomeConfig = disnake.Embed(
title = "Welcome!",
description = "Welcome to the config menu. Each of the menu option will give you 30 seconds to reply. Let's start with the welcome channel."
).add_field(
name = "Welcome Channel",
value = "Please state the welcome channel ([#welcome](/guild/267624335836053506/channel/267631170882240512/) for example)"
)
await inter.response.send_message(embed = welcomeConfig)
await self.bot.wait_for()
Is this the right place for the wait for btw?
(it only says <#id> because there's a welcome channel here)
Where do you host discord bots?
yeah, sure
Thanks
you have multiple options tho, buy PLS don't use replit or heroku
Why not heroku?
Why not replit or heroku?
<#discord-bots message> TL;DR they suck
See my earlier response to a similar question
Ah I see
What are some other good options other than aws
Alright, thank you
Would it be possible to run it on a raspberry pi?
Course
I've done it for quite a bit before I got an ec2 instance
Why'd you switch?
Why wouldn't you?
A raspberry pi will only hold for so long
Not very scalable either
Right
Plus I was also building a web app (dashboard) to go along with my bot and honestly I needed the other services, so it was easier to keep everything in one place
These days I just do stupid stuff with the raspberry pi
Would you recommend doing it with a raspberry pi though?
It depends on how big your bot is
As in the amount of code?
That and how many guilds your bot is in, the size of those guilds
Just the general amount of stress you put on your bot
I see
A raspberry pi has some advantages over a vps but a vps has some advantages over a raspberry pi
It all depends on your situation and needs I guess
Yeah, it can be cheaper than hosts once you pay off the initial investment
Considering it's 8gb of ram it's pretty beefy for such a small thing
And if you're just running a discord bot on the internet and electricity bills are going to be pretty low for it
how much gb do i need to run a discord bot on a server
1 is the bare minimum
ok
Right, I bought one a few months ago and Im not using it for much
What's the advantages of a raspberry pi over a VPS?
A one time purchase, you're in complete control, easy to access
And the advantages of a vps over a pi?
Ah
How do you test it and update it? Do you just have to use ssh?
well you would run it locally (on your pc), test it, make sure it all works and then ssh into it and pull it from your github repo and rerun
you could also make a pull and restart command in your bot for ease of access
its best to just write, test and commit your code locally so its easy to pull and rerun
Would it be able to run on the raspberry pi and locally at the same time?
yes
bots can be ran in multiple places
Sweet
On one server? like, not even 50mb if it's just a discord bot, without a db or any heavy processing going on in the background
usage of git cli is recommended for sshing between servers
Higher upkeep, also not scalable, heavy initial cost
so you'd want to check if they are different on before and after, as the same event is triggered for multiple changes. . .
wouldnt really say its a heavy initial cost
Depends on the model
(thats for both activity change and status change, as the event can be invoked on either of many changes)
I have the 4 which was ~120ish which equates to about a year for many hosts
Lol
I was willing to go with a cheap host for the discord bot itself, and I have some pod autoscaler set up on k3s for the actual backend that does work
depends where you get it from, my dad works for one of the major distributors, got the 4 8GB for a fraction of the price, one of his mates hooked me up with a killer deal for fixing up a couple of he's computers or something . - .
Cheap as in $10 per year. shit's great if you know where to look, on lowendbox
Oh awesome! Mine was from canakit :p
I asked earlier but forgot the message, I got sidetracked 🧍♂️
But yeah, for wait_for, what do I put as the event if I'm expecting a channel? (#welcome for example)
@modest plover There's a check parameter in that wait_for
Yeah unfortunately there's no on_channel or an event like that
. - . think i payed like £50 for 2 of them, aint half bad
You'd want to use .channel_mentions
So what would that be?
They're the aarch64 ones no?
i got too many pi's lying around in my house tbh -- im sure i had 3 pi 2's buried somewhere . _ .
The ones that aren't slow af and outdated
build a "supercomputer" with all of them :p
yup, both 8GB pi4s 64bit -- tho they been 64bit since pi3's
Really now
Make a 16gb super-pi
xD
message.channel_mentions would be > 1 if the user mentioned a channel in the message
Don't think the team updated raspbian to 64 bit, cause I had some trouble with that stuff before
At least for one model of the 4
don't
ye rasp pi foundation only recently officially released their 64bit rasp os or what ever they call it, it wasnt pushed due to stability etc until very recently -- had to go thru a weird download website otherwise (not on main page)
stay stable
self.bot.wait_for('on_message.channel_mentions', timeout=30.0)?
I hate downloading those newest stuff
Sorry I'm sort of confused lmao
Did you read the docs?
You just wait for a regular on_message event
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
You need to use return len(message.channel_mentions) > 0 in your check
def check(message: discord.Message):
return len(message.channel_mentions) > 0
await client.wait_for('message', check=check)
Do note that if you want the user to be able to specify the channel by name or ID, you have to use TextChannelConverter
That was the check parameter I was talking about
Checking message.channel_mentions **will only work if the user pings the channel explicitly **
https://www.raspberrypi.com/software/operating-systems/
if you scroll down, they officially list 64bit version now
By explicitly, you mean like #welcome right?
Correct
(by the way, what you're doing right now would be perfect for the new modals)
rather just create utility functions for all those things, which will test for what seems like a channel ID etc and return them. . . they really streamline the code etc
Yeah, not compatible unfortunately
Or is it, I'm not sure 
That's exactly what TextChannelConverter does
huh, never used the converters tbh ;-; i ended up writing my own, didnt know they existed, couple people mentioned i shoulda used emoji converters . - .
Converters are great
You could also make your own converters as in, you can subclass converter and pass it in as a type hint
welp, guess i was reinventing the wheel,
tho mine is designed for my usecase, like getting all emotes from text, limiting amount gotten from each input type was something i wanted too (and no repeats)
The cool thing is you can use d.py's built in converters in your own converters that makes things incredibly easy
^ yes, stole a bit of regex from somewhere internal for emotes,
yall dont just source dive?
I do but really no point in recoding something that's already given to you in a nice format
That docs page takes forever to load, I just jump to definition if I don't have it open 
What do you mean
What can I say I work with typescript mostly and it's all documented in the intellisense
eh true, but then you dont get to write fun regex like this:
Oh, I see
Wonder how something like pyright handles dpy
oh this ones kinda nice, wanted to grab emotes from views too
there is no escape from my get emote commands, it will grab from anywhere and everywhere . - .
wtf is that function naming
It's like a mix between camelCase and snake_case
ye, we dont question my 3am naming conventions
||for peace of mind, i have rectified that name||
I refuse to rename mine because of water constantly enforcing pep8 lmao
Oh shit I forgot modals existed LMAO
I'm gonna make it as a slash first just so I can see if I can get my other commands working then I'm gonna make it a modal
. - . kinda hard changing habits tho in all honesty
Lol
Just don't develop the bad habits in the first place
dunno why modals exsist and arent just part of views ;-; woulda been nice to have those text fields as part of views too. .
What's the code?
not enough info, dunno the code nor what your using (dpy??)
im using discord.py code is @client.command
. - . could you perhaps show the code?
mhm
the whole thing?
The bit you're working on
alr
atleast the portion around the error
@client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await sleep (60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@client.commands()
async def snipe(ctx):
channel = ctx.channel
try:
snipeEmbed = discord.Embed(title=f"Last deleted message in#{channel.name}", description = snipe_message_content[channel.id])
snipeEmbed.set_footer(text=f"Deleted by {snipe_message_author[channel.id]}")
except:
await ctx.send(f"There are no deleted messages in#(channel.name)")
import disnake
from disnake.ext import commands
from deta import Deta
import os
from dotenv import load_dotenv
load_dotenv()
project_key = os.environ["project_key"]
deta = Deta(project_key)
config_db = deta.Base("Config")
class Config(commands.Cog):
"""Saves a config to the Deta database."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.slash_command()
async def config(self, inter):
"""Presents the user with a config command"""
welcomeConfig = disnake.Embed(
title = "Welcome!",
description = "Welcome to the config menu. Each of the menu option will give you 30 seconds to reply. Let's start with the welcome channel."
).add_field(
name = "Welcome Channel",
value = "Please state the welcome channel ([#welcome](/guild/267624335836053506/channel/267631170882240512/) for example)"
)
await inter.response.send_message(embed = welcomeConfig)
def welcomeCheck(message: disnake.Message):
return len(message.channel_mentions) > 0
print(welcomeCheck)
await self.bot.wait_for("message", timeout=30.0, check=welcomeCheck)
await inter.response.send_message(embed = welcomeConfig)
def setup(bot):
bot.add_cog(Config(bot))
print(" | Loaded Extension: Config")
print(" | ")
It says the interaction was already responded to. How else am I supposed to send another embed?
I'm confused lmao
im having trouble at @client.commands
could you add syntax highlighting -- put in code block with
then end with tripple of them too
@client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await sleep (60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@client.commands()
async def snipe(ctx):
channel = ctx.channel
try:
snipeEmbed = discord.Embed(title=f"Last deleted message in#{channel.name}", description = snipe_message_content[channel.id])
snipeEmbed.set_footer(text=f"Deleted by {snipe_message_author[channel.id]}")
except:
await ctx.send(f"There are no deleted messages in#(channel.name)")
``` @echo lagoon
I mean you told em how to ._.
AttributeError: 'Client' object has no attribute 'command'
yes, but you can only get so far teaching someone how to build a house, without them practically using the tools and doing it for themselves (apply same philosophy to this ; -;)
ok
could you show what client is?
client = commands.Bot(command_prefix=":")
right, i think it should be client.command() ;-;
(for the commands)
then it will give me a diffrent error gimme a sec
How do I keep a .py file running in the background in ssh on a raspberry pi?
client = commands.Bot()
TypeError: init() missing 1 required positional argument: 'command_prefix'
well, there you go, your missing a prefix arg when instancing commands.Bot()
should look something like this
then i get the same error for client object has no attribuite command
which if you look internally, command_prefix is a must have param to instance the class
uhh?
here
have you fixed this?
yes\
right gimme a sec, i wonna give this a try
Don't name your Bot instance client
discord.Client exists
then it doesnt work entirely since apperntly client cant run commands
every said to change to command.Bot
I never said to use discord.Client
k
you have to respond within 3 seconds
otherwise you gotta defer the interaction
I fixed it, it's fine
Well, the Disnake server fixed it lmao
I used inter.channel.send() rather than a second respond.send_message()
I mean it worked :)
tbh should use a list instead of a dict
i fixed the thing
i redifiened client so i fixed it
all is working?
weird, mine dont work lol, dunno what i done
How do I save a user's message to a variable?
That's basic python...
use the assignment operator
a = ctx.message
It's a slash so ctx isn't available
interaction?
Wait fuck my brains just had a moment. Sorry lmao
.
welp, not used slash so i dunno, dont like slash so im not willing to find out
should not make slash commands if your bot isn't gonnna be verified tbh
Slash commands work nice tho, like it's quicker and easier than typing out say !embed_colour #1abc9c
say that again when you have /play and 5 different bots come up

And this is where an icon comes into play.
Plus. You're saying /play brings 5 bots up, !play does the same
i guess it has its usecase but i find doing !!!play + url is easier . - .
Except !play actually executes the commajd
configure a unique command prefix ; - ;
well yeah but most prefixes are taken
you can change prefix for most bots tho
you genuinely think I'm gonna make a prefix of !?!?.play and expect people to remember it?
Most. But not all.
mhm, mine uses !!! -- non configurable atm, no other bot uses it in my guild
or use <, %, ~, *,
^ theres all those options too
@client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await sleep(60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@client.command()
async def snipe(ctx):
channel = ctx.channel
try:
snipeEmbed = discord.Embed(title=f"Last deleted message in#{channel.name}", description=snipe_message_content[channel.id])
snipeEmbed.set_footer(text=f"Deleted by {snipe_message_author[channel.id]}")
except:
await ctx.send(f"There are no deleted messages in#(channel.name)")
now its no t working at all
its starting but the command is broken
like it dont do anything when you call it?
ye
. . ?
wdym in the console?
no, do !help see if it shows up in the help menu
assuming your prefix is !
i dont have a help menu
hi guys, can i ask a question about discord bot ?


