#discord-bots
1 messages ยท Page 754 of 1
disnake.ext.commands.Param(default=Ellipsis, *, name='', description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, ...)```
A special function that creates an instance of [`ParamInfo`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.ParamInfo "disnake.ext.commands.ParamInfo") that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.
See [Parameters](https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#param-syntax) for more info.
Oh I found it
@bot.slash_command()
async def multiply(
interaction: disnake.ApplicationCommandInteraction,
clean: str = commands.Param(converter=lambda inter, arg: arg.replace("@", "\\@")
):
...
``` imagine how this would look with many many many arguments!

Well don't have too many arguments.
what command needs so many args?
That's not a problem you can just ignore
You can also make functions instead of lambda.
eh i don't agree
More based towards JS definitely. No argument there, but how it is handled rn is pretty good.
commands.Param I would say isn't the best though
You can make custom typehints E.g Options[...]
I import Param to keep it shorter.
I'll be doing this to my wrapper as well
But it still takes to much space!
This overall is just more towards discordjs side
๐
Maby embed creator :3
that would be annoying to do if it was a slash command or not
Not tryna have my method/function signature taking up 20 lines just for a somewhat advanced Option menu
x3
true lol
so it does suck!
why aren't you using buttons for that?
you ever typed pls profile?
Ok sure, let me rephrase
Andy has a point here i'd rather have it in the commands aswell rather than a menu every time.
Nvm wrong syntax in my head
don't do that
๐
I'm just trying to say that this takes up to much space
which is also one of my reasons why slash commands suck
This is the amount of space it takes
@slash_command(name="pypi")
async def get_package_info(
self, inter: ApplicationCommandInteraction,
package: str = Param(autocomplete=autocomplete_pypi),
hidden: bool = True
) -> Message:
""" Provide information about a specific package from PyPI """
To maintain readability aswell.
You could smash it together but it will be annoying to read.
how do i make an arg in a slash command required?
Don't define it
Just like in Python
Show a somewhat advanced slash command with sub-commands then
If you only typehint as string you would need to pass a string as arg.
There is just no way this is scalable
makes sense, thanks
Haven't made sub-commands yet. Will see how that holds up.. trying to avoid those as much as i can.
Avoiding cause of the space it takes right?
Well yeah but you don't need subcommands.
@cloud dawn hey again, [WARNING] Failed to overwrite commands in <Guild id=923632089834864690> due to 400 Bad Request (error code: 50035): Invalid Form Body In 1.description: Must be between 1 and 100 in length.
what's up with this error? ^^
God i remember the old interactions command lmao
My point exactly
This is my old slash command back when it launched
@cog_ext.cog_slash(
name="together",
description="Play games together or watch youtube!",
guild_ids=[832595290174914571],
options=[
create_option(
name="activity",
description="Choose your activity",
option_type=3,
required=True,
choices=[
create_choice(
name="Youtube",
value="youtube"
),
create_choice(
name="Poker",
value="poker"
),
create_choice(
name="Chess",
value="chess"
),
create_choice(
name="Betrayal",
value="betrayal"
),
create_choice(
name="Fishing",
value="fishing"
)
]
),
create_option(
name="private",
description="Set visability to others",
option_type=5,
required=False
)
]
)
async def _together(self, ctx: SlashContext, activity: str, private: bool = True) -> discord.Message:
THAT'S WHAT I'M SAYINGG
๐ there is no real good way about implementing a LITE version of this
But it's not like this anymore Andy ๐
?
Discord API requires message command descriptions to be between 1-100 chars
Hmm, yeah what Andy says try printing it.
it had 102 characters xD
Unless you bring out a slash command builder
much wow
And even with this, the only difference you will have is that some-what advanced slash commands would probably get their own file
Andy i hated the previous slash commands libs aswell but Disnake is pretty decent.
naw look at the function signature
Maybe my standards are to high but I like to keep code lite and simple
sadly not possible with slash commands
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ClientUser' object has no attribute 'avatar_url' how else should i be accessing this? this is how i've accessed it in the past
self.client.avatar_url
avatar.url
that's new
No, it's been there since discord.py v2.0
No documentation found for the requested symbol.
new as in new to me
!d disnake.Client.user
property user: disnake.user.ClientUser```
Represents the connected client. `None` if not logged in.
Return an asset object
class disnake.Asset```
Represents a CDN asset on Discord.
str(x) Returns the URL of the CDN asset.
len(x) Returns the length of the CDN assetโs URL.
x == y Checks if the asset is equal to another asset.
x != y Checks if the asset is not equal to another asset.
hash(x) Returns the hash of the asset.
If you were interested :3
Is there a way I can make certain slash commands global?
i was, ty
just remove the guild_ids =
then it should be global, but it will take a bit to register is what i was told
A certain 
Also if I restart my bot, would I have to wait for my slash commands to register again or is it only a 1 time thing
Global commands take up to 2 hours to register
I know
test_guilds are instant
As for global idk haven't done that yet since i don't need to.
Why don't you need to?
Then it would be just None?
Since i'm still developing it
the video told me to leave it out and it would do it to all of them automatically ยฏ_(ใ)_/ยฏ
but it would take a while
You didn't really answer my question
You got any docs perhaps?
If you could.
Today I show you a basic way on how to use slash commands with Disnake.py, a fork of Discord.py. If you'd be interested in something different or more tutorials, please leave a comment!
that one :3
Since i'm still using the test_guilds so it will be instant
If I restart my bot would I have to wait for the slash commands to be registered again (for global) or will it do it instantly since they had been registered in the past
@cloud dawn he says it around 3:53
I was referring to my original question
Ohh yeah you would need to wait if you changed the name or added commands. But if you just edit the commands code it will change instantly. However not the autocomplete or choices etc since discord still has to update that then.
Okay
So what if I reload the cog?
any thoughts on that vid?
Would I have to wait for the command to register again?
Alright i figured it out:
If you pass test_guilds or guild_ids it will be only those that are specified who will get the slash commands. And like you said if you remove them they will be going global. Around 1 hour i read in the docs.
oh oki! are they registered to those servers that i passed in guild_ids once i remove them still?
Most likely not. Unless like i said you changed the name/added or messed with the passed args/kwargs
Most likely they would need to register first as well, but not certain.
interesting
Nice
does the bot need to stay online whilst it registers?
I was just worried that even if I was messing with my prefix commands and restart the cog I would have to wait for my slash commands to register again
Very good for starters. Only the try exception at bot run is a bit odd since it will crash anyways.
ye
I don't know i would have to test that, i don't want to give false info. But I think it does have to be online.
Looks good. Its basically the information from the getting starting part of the docs
Grabbing the slash docs now.
If you are up for it could also show some cogs to get started. They are very nice :3
alright, i'll run it on replit since i can't host it for the next hour :3
i know how to use cogs, my original code was inside of a cog already
Ah you coded bots before?
ye
the one i'm doing rn is on my github
i wonder if this button works for you lol
@cloud dawn
An app can have the following number of commands:
100 global CHAT_INPUT commands
5 global USER commands
5 global MESSAGE commands
nice, doesn't work for me lol
._. only 5 user commands?
User specific commands i think don't confuse them with commands.
i made the one /ping and the other /invite command using slash commands atm
what do those count as?
they just send a single message
Can you explain what those are?
100 global CHAT_INPUT commands
interesting
Return a chat output and accessible for everyone.
What are user specific commands?
Reading now..
uh
I don't really understand a use case for those
Well you can have 5 of those xD
that's fine
I don't really like how they have the cap
Global commands are available on all your app's guilds. Global commands are cached for 1 hour. That means that new global commands will fan out slowly across all guilds, and will be guaranteed to be updated in an hour.
Looks like your bot doesn't need to stay on @severe rampart
._. i already set it up in replit lol
Sorry ;-;
Well they already increased it to 100
does it take an hour to load the commands then?
No they are getting cached by Discord.
I'm still only going to make specific commands with them
I was going to change my reload command to a slash command so it can auto complete my cogs but with the cap idk if I want to do that
Auto complete is still very nice
I mixed the normal and slash commands for now, slash for the users and normal command for the development/debug
Later if my bot ever gets verified i will move my reload to my dashboard.
Wonder if there is anything stopping people from just registering to every guild under bot.guilds
Perhaps the 50/1s global ratelimit
Most likely they thought of that.
Feel like it would only be the 50/1s ratelimit here
There must be a valid reason why they are doing it like this.
Well
50 commands per 1/s?
It's because guild specific slash commands are registered to the guild which has a unique int 64 id
registering global commands don't require a specific guild ID thus have a different endpoint
Meaning 1 request but 1 hour to register for global
While registering to all guilds manually you can just do 50 in a second
I know my mind is still thinking about how to make the docs command.
Using choices instead of autocomplete so they can't input an invalid input :3
So I have this command (going to be a task event which runs every 6 - 24 hours, eventually) which searches through a channels history to find msgs that have embeds which match a list of keywords. I
- want my bot to look through the fetched msgs chronologically (oldest to newest)
- then for every message in that list I want to check if the message ID is not in my list of checked messages
- then I want it to check if the author of the msg is the same as the provided ID
- then I want it to check if the message contains a embed (It should do every time but doing this to be on the safe side)
- then I want it to check if any of the words in my
key_wordslist appear in the embeds title- if the
key_wordsdo appear then I want it to construct a new embed from the field values of the original embed- then I want it to add the ID of the message it just checked to my list of checked msgs so that it won't check it again in future
I think I have all of that logic correct but does someone mind checking over my code to double check this for me?
I also have some additional stages that I'm not too sure how to implement so some idea's on how I could do them would be appreciated.- I would like to be able to know which of my
key_wordsit triggers on so that I can add that to my new embed inside of the{action}variable- I would like to write the datetime timestamp of the last checked message to my
last_chackedvariable so that it won't check msgs before that again (jut saving on having duplicate new embeds)
Below is my code, thank for you reading```py
@commands.command()
@commands.has_permissions(administrator = True)
async def moderation_logs(self, ctx):
key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] # Add in Captilised versions of each word to account for the Dyno logs
checked_logs = []
case_count = 0
last_checked = 0
#dict = {}
moderation = self.bot.get_channel(id = 885569667861717042)
clifford_log = self.bot.get_channel(id = 500768218257031168)
with moderation.channel.typing():
messages = await clifford_log.channel.history(oldest_first = True, limit = None, after = last_checked).flatten() # 10000
for message in messages[0:]: # Making bot search history chronologically
if message.id not in checked_logs:
if message.author.id == 776782769312628746:
if len(message.embeds) > 0:
if key_words in message.embeds[0].title:
embed = discord.Embed(title = f"Case {case_count} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp)
embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url)
embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url})
embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True)
embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True)
if message.embeds[0].fields[3]:
embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value)
if message.embeds[0].fields[2]:
embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value)
checked_logs.append(message.id)
await moderation.send(embed = embed)```
Yea because the endpoint registering the commands fall under the global ratelimit iirc
So what's stopping people from just doing it manually?
No clue lol
You'd be adding more stress onto discord by doing that, so wondering if discord has a safe guard or something
but so far I don't think so other than the ratelimit
I have no idea if it would work, my suggestion is to just run it and set the timer lower for debugging.
I would make the nesting a bit less since it is a bit much.
Some lines are also way too long, PEP8 suggest <120
How do I make a bot ignore a channel?
How would you suggest I do that? Adding a bunch of if this then that and if this then that? Also other than the complexity does my logic of if statements look correct?
async def on_message(ctx):
if ctx.channel.id == 899133612656558080:
...
if 'https' in ctx.content.lower():
await ctx.delete()
await ctx.channel.send(f"{ctx.author.mention}, you aren't allowed to send Links/Invite Links")
await bot.process_commands(ctx)
I said if the channel that the message is being sent to should be ignored
but it isn't
what's the problem?
Actually pep8 says 79 flat is the max
also how could I go about finding out which of my key words it triggered on?
That's even better
But i keep <120 since otherwise it's way too long.
Most of the times i don't reach 120 but i have set my IDE to give warnings if it is longer.
Thanks, I can't implement those suggested changes bc my laptop just died and since it's 12.30 in the morning I'm going to take that as a suggestion I should go to bed ๐ I'll probs keep the key words checker separate since I want to know which word it triggered on, which I'm still stuck on how to check but heyo that's something for another day
Tbh if is is only one channel i would cache the whole text channel.
Makes it a lot cleaner.
Well said text channel has 48, 628 msgs in it, also... How would I go about caching the channels history and how would doing so make my code cleaner?
I'd make an on_message event just log the whole channel.
You could then already do some checks to throw away unnecessary messages. And it would be much faster.
The speed it does it isn't really all that important to me, the purpose of the feature is to be a supplementary source of moderation logs for my members as the bot I use for moderation annoyingly doesn't support separate logging channels for each type of log
Then i would've just made a database for it and put it there.
Using a Discord channel as database isn't really efficient.
who even thought of that lmao
you know how some bots have slash command messages only available to the user?
how do i recreate that
send ephemeral messages'
Guys how can i modify this code
if any(word in message.content for word in ["Ghoul", "Town"]):
await message.delete()
sent_message = await message.channel.send('Ghoultest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Ghoultest")
so it can detect words instead of
["Ghoul", "Town"]):
and execute this
if "MASSIVE" in message.content:
with a different
await hist[message.author.id].edit(content = "Massive Ghoultest")
Thanks
!d disnake.abc.Messageable.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, ...)```
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://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.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://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") objects. **Specifying both parameters will lead to an exception**.
NP
can i make my bot react to old messages
hola
fetch the message/context and react
for example someone said !hello a long time ago can i make it respond
well, i guess in the on_raw_react func, you can check the react and fetch the message_id and react to it
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
@left crater
i have a server with a memes section i want the bot to append all the images into a list
thats why i want it to work with older messages
like, embeds from each message?
like whenever someone says !meme it will post a random meme from there
async def on_message(message, ctx : commands.Context):
if message.channel.id == 699577970117050399:
meme_list = []
if message.attachments.url.endswith('png') or message.attachments.url.endswith('jpg') or message.attachments.url.endswith('jpeg') or message.attachments.url.endswith('mp4') or message.attachments[0].url.endwith('gif'):
url = message.attachments.url
meme_list.append(url)
list_len = len(meme_list)
rand = random.randrange(list_len)
await ctx.send(meme_list[rand])```
this is my code but not working
so, if member does ?meme it gets a random meme from the memes channel and sends it?
yup
!d disnake.Message.embeds
A list of embeds the message has.
yup
im pretty sure that images are in embeds
so just get the embed, get images from them
im using discord.py
!d discord.Message.embeds
A list of embeds the message has.
same thing
Guys how can i combine this two
if any(word in message.content for word in ["Ghoul", "Town"]):
await message.delete()
sent_message = await message.channel.send('Ghoultest')
hist[message.author.id] = sent_message
return
--------------------
if "MASSIVE" in message.content:
if message.author.id in hist:
await message.delete()
return await hist[message.author.id].edit(content ="Massive Ghoultest")
so if the first if-statement executes, it also executes the second if-statement
since i'm going to copy+paste this and change some things.
just put the second if in the first if
Guys how to make it so that a if-statement will only be executed if there's a specific value stored in a hist?
!ban 932451931492843590 self-botting is against discord's terms of service and our rules
:incoming_envelope: :ok_hand: applied ban to @silver panther permanently.
yes
Guys how to make my discord bot automatically stores the id of the recent message ? since the recent message will not always be the same.
I don't know exactly what you mean but you can use a database
i mean that, if someone sent a message, the bot will automatically get the ID of it
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
The message ID.
I was trying to create a self bot just for fun, but the user was only answering himself, not others users. Does anyone know how to fix it?
i am using cogs
why do only 1 of these commands work
self bots are against ToS do not talk about them here.
what are self bots
basically code that would run a bot running a normal user account.
oh damn
yo quick question, which wrapper should i be using?
probably a fork
^
of dpy
I mean, i used to use d.py long time ago, but just came back and saw its been stopped, so i have no clue what to use
like disnake
ouu disnake, okay
disnake is good, nextcord is also good
hasnt been stopped but not maintained
you can totally maintain it yourself
many forks that are good but i like disnake more imo
not really
thats what im doing
add a listener
listener?
forgot the ()
yep
cant you name events in @bot.listen()
@bot.listen(name="on_message")```
correct
oh? for me in cogs, you need to name it if you wanna use multiple on_message events
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
got it thanks
I would know how to do all of this if i started the way everyone else is starting, but i started with cogs and forced myself to learn how they worked by trial and error 
cogs arent really different
show the on ready
HI
in a way they arent and really are
gotta add code to that listen so it doesnt error things below
well you have a random decorator there
okay so no decorator
its on on_ready right
yes
ur talking about the decorator on on_ready
okay @client.listen needs to be removed
if you need to have an on_message event or any event for that, use @client.listen
yes
surwe
should i keep my library of swears in a .json file, since they are very large, and they're sets
client.event doesnt have a decorator but sure
i could use tuples instead tho
on message event can only be used once or it will be overwritten so thats why it will stop all of your commandsand thats why you can process the commands or use a listener which doesnt overwrite itself
in this screenshot, you have @client.event above your @client.listen()
i just use a list in a py file lmao
oh so its like a personal listener for each command
so it cant overwrite itself am i right
oh, so i don't have to move these 1400 swears to a .json?
doesnt really matter but i just use a py file so i can just import it and check the var
understood
alr
Undefined name 'message'. Do I need to import anything?
ahh
you have context
so the bot.listen thing worked so i tried in a chatlogs channel
well
i literally just said a
and it spammed it like 10 times
oh yea i figuired out the problem
maybe if the user is administrator dont send message in chatlogs
yea i can just do that
still does the spamming
check the author
it will keep sending the messages since its waiting messages from all users including itself
I just forgot, ๐ข. It's in COGS
self.bot.user
Wait what's commands.listen?
ikr
๐คทโโ๏ธ
I was goings to do event but people said listen is better
@commands.Cog.listener()
is the cog instance
Cog being the name of the folder right?
ok
Okay. Mine is class Miniboss(commands.Cog):
nice
ive written admin false tho
and my bot has admin
so it wont check my bot right?
dont think so
use an if statement and compare the author id with the bot id
you don't use that decorator on on_message events
It's meant for commands
!d discord.Member.guild_permissions . administrator will be true if the member is an admin
property guild_permissions: discord.permissions.Permissions```
Returns the memberโs guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
It won't , it takes context as an arg which on_message won't provide
oh so thats the reason lol
yeah ik
@commands.has_permission(admin=fakse)
ik
how do i use that
youre trying to make the bot ignore itself right?
yes
@green bluff you are doing something like if member sends a message , and they are not an admin
The message gets logged , right?
then a if statement
^
Ah , use use if message.author == bot.user : return
same thing
what do i put in the function tho
you put it in the function?
there's a return already
in that
wut
oh
dmcap2 = await cap2.send(embed=dm2)
await dmcap2.add_reaction('1๏ธโฃ')
await dmcap2.add_reaction('2๏ธโฃ')
await dmcap2.add_reaction('3๏ธโฃ')
def check(reaction, user):
return str(reaction.emoji) in ['1๏ธโฃ', '2๏ธโฃ', '3๏ธโฃ', '4๏ธโฃ'] and user != bot.user and \
user == cap2 and reaction.message == dmcap2 and isinstance(reaction.channel,
discord.DMChannel)
try:
reaction, user = await bot.wait_for('reaction_add', timeout=45, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('timeout')
return
else:
if str(reaction.emoji) == '1๏ธโฃ':
team2_ids[game_id - 1].append(b[0])
await cap2.send(f"You have chosen <@!{b[0]}> as your first pick")
b.remove(b[0])
if str(reaction.emoji) == '2๏ธโฃ':
team2_ids[game_id - 1].append(b[1])
await cap2.send(f"You have chosen <@!{b[1]}> as your first pick")
b.remove(b[1])
if str(reaction.emoji) == '3๏ธโฃ':
team2_ids[game_id - 1].append(b[2])
await cap2.send(f"You have chosen <@!{b[2]}> as your first pick")
b.remove(b[2])
My bot doesnt seem to be picking up reactions from users in dm's, any ideas?
could be my check but idk 
so return
!e if 1==1 : return #ez
bruh
nvm , there was not function
what was that sarthak
I'm used to my bot's eval
LMAO
Return can be used only inside a function
ik
isinstance(reaction.channel , discord.DMChannel)
this?
you don't compare channel type with the instance
was that for me orrr
oh what is it? just reaction.channel?
Use == instead of is
Yessir
is there an attribute for message to check if it starts with something, on a message event
sure but someone told me to use is over == before
!d str.startswith
str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
thanks!
whats the difference just saying
Basically , message.content.startswith
alrighty
message.content.startswith("") *
ruby is the same
but functions are called methods lol
Same for every language
yeah
@client.event
async def on_message(message):
await client.process_commands(message)
if not message.content.startswith("["):
await message.channel.send("x")
this just spams "x" over and over
even in python a function is method
as said to 0_0
check author
they never refer to it as a function in ruby tho lol
check author for what exactly?
this isnt supposed to be a user-specific event
it will keep sending the messages since its waiting messages from all users including itself
oh
^^asher
ohh, because the message "x' is from the bot,,,, right
yessir
Why don't they , I mean most of the languages do
i mean in the tutorial i watched they didnt so idk
but methods are like functions in python but less complicated
def double number = 0
puts number * 2
end
this doubles the arg given
not sure why define isnt highlighted
when im using the ruby code block but i like
end
in ruby it just shows where the actions ends
They got that in lua and tons of other shits as well.
i like it its cool
Shit like thag doesnโt exist in python because everything is dependent on indentation.
dmcap2 = await cap2.send(embed=dm2)
await dmcap2.add_reaction('1๏ธโฃ')
await dmcap2.add_reaction('2๏ธโฃ')
await dmcap2.add_reaction('3๏ธโฃ')
def check(reaction, user):
return str(reaction.emoji) in ['1๏ธโฃ', '2๏ธโฃ', '3๏ธโฃ', '4๏ธโฃ'] and user != bot.user and \
user == cap2 and reaction.message == dmcap2 and isinstance(reaction.channel,
discord.DMChannel)
try:
reaction, user = await bot.wait_for('reaction_add', timeout=45, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('timeout')
return
else:
if str(reaction.emoji) == '1๏ธโฃ':
team2_ids[game_id - 1].append(b[0])
await cap2.send(f"You have chosen <@!{b[0]}> as your first pick")
b.remove(b[0])
if str(reaction.emoji) == '2๏ธโฃ':
team2_ids[game_id - 1].append(b[1])
await cap2.send(f"You have chosen <@!{b[1]}> as your first pick")
b.remove(b[1])
if str(reaction.emoji) == '3๏ธโฃ':
team2_ids[game_id - 1].append(b[2])
await cap2.send(f"You have chosen <@!{b[2]}> as your first pick")
b.remove(b[2])
Any other ideas why it just goes to timeout even after the user interacting?
am I doing something blatantly wrong
yeah
nice pfp looks clean
@bot.listen()
async def on_message(message):
mbcommand = bot.get_channel('932479943441543238')
if message.author == bot.user:
return
if message.channel.id == 932479913565511710 and message.content.startswith('Congratulations to'):
await mbcommand.send(f'`RPG miniboss {message.content.split("Congratulations to ")[1]}`')
await message.channel.send(f'The miniboss command to copy and paste was sent in `[#932479943441543238](/guild/267624335836053506/channel/932479943441543238/)`')
I'm trying to send the (f'`RPG miniboss {message.content.split("Congratulations to ")[1]}`') to another channel and i get error
@client.event
async def on_message(message):
await client.process_commands(message)
if message.author != client.user:
if message.channel.id == 930302167825403944 or 930301694389129276 or 930302000791437402 or 930302065715064853 or 931374309962838076 or 931374741560918036 or 931376262142914611:
if not message.content.startswith("["):
....
the if loop to check message channel id is passing even if the message was not sent in one of those channels
its supposed to be
await client.process_commands()
afaik and moved it to the bottom
It still needs a message object lol
does it?
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageโs author is a bot and doesnโt call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
it does ic
can I?
Sure
Do dropdown menus have a time in which after that time they don't respond to the interactions?
the last interaction was like 8 hours ago or more and I didn't put a timeout on the dropdown menu but it's saying the interaction failed
you make the dropdown with ui.Select
and you use View for the view of the dropdown why not use the timeout kwarg?
Because I want users to be able to press it anytime
Won't restarting the bot do the same though?
Why replace it though?
so its a new one which can be interacted with
but i want the users to be able to use the dropdown anytime
without me having to replace the view
it can't be permanent?
well yes when a bot restarts it will stop listening from interactions so just replace the view with a new one of the same thing tldr edit the message with a new view
but the bot didn't restart, other commands still work
ah ic idk then why it stopped
apparently when i replaced the views they still don't work not sure why it is working yesterday and I didn't change anything
weird
You have to setup a persistent view
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py Check this example out
Oh i see thanks
async def on_message(ctx):
for word in naughty_words:
if word in ctx.content:
if ctx.author.guild_permissions.manage_messages:
...
else:
await asyncio.sleep(3)
await ctx.delete()
await ctx.channel.send(f"{ctx.author.mention}, you aren't allowed to say that!")
await bot.process_commands(ctx)```
The bot keeps malfuctioning every time a swear word is said
how do i fix that
Ping me if you know how to solve
And I've still haven't had any assistance here so if you know how to solve this ping me too
why the for loop
no need to iterate through it
!e
a = ["something","somethingelse","badstuff"]
if "badstuff" in a:
print("dont say that")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
dont say that
you are passing Context in on_message...
it should be message
argument naming
?
The argument can be named anything
^ :))
Yea ik
still looks weird ngl
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.
tysm
yw
there's no loop though
for word in naughty_words:
Just message
.
its argument naming doesnt matter
does anyone know why ctx.author.avatar_url doesn't work when I use it in an extension?
it was fine when I had it in my main file
Any tips on growing a discord bot?
what's the error?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
no idea why it's hapenning
which library are you using?
for now discord.py
which version of discord-py are you on
you can run pip show discord.py in your terminal
2.0.0a3575+g45d498c1
you're on v2
oh no there's a v3 right
be unique
oof, one of the most difficult things nowadays
just implement external API's... so it's actually useful
Should i do;
if message.author_id == {id} and message == .... :
....
For check message from an user.
????
message.author.id
Also what are you going to compare message with?
why a set?
that will return false
message.content*
I guess he just put it for example, there's no brackets in code
How can i check content from a specific user
Compare message author's id and user's id
if message.author.id == 580332673289945099 and message.content == "hello":
....
id is an int
Like that?
Not a string
Ah
So compare it with int
K
Like that?
Yeah
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Thx
Show code
Remove token from there bro
You don't need to process commands in on_command_error iirc
to send a message continuously at certain intervals, should I do this?
@tasks.loop(seconds = 10 )
async def message(ctx):
if message.author.id == 580332673289945099 and message.content == "hello":
await ctx.send("hello")
For Check message content and user
Just remove it from there
talk in yr own dms
Where is message defined
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Wdym ๐คทโโ๏ธ
It should only be in on_message but there's no that event
i get a lot of notification
Disable all messages notifications?
tysm
Lmao do you really have them on
for telling,
btw how to make bots?
?\
k
did it
how to make discord bots
hello?
bc?
wats bc?
Why does it look like your trying to handle errors and new messages in the same event?
okay
can anyone explain why 4 are locked? all i did was move each role to position 99 or 1
how do I invoke a command using a command but the author is someone else? kinda like jsk's jsk exec @user command command
Your top role is purple, so you can't edit the roles above the purple role
idk
@boreal ravine but why arnt orange locked etc they all are roles created with no perms
because your role is purple
orange is below the purple role
oh
You cannot edit your role and the roles above yours.
that kinda messed up
i mean its just for colors
cant timeout one if they have pink etc
even tho i have admin they not
Hi
hi
hi
bye
The embed part (Last 3 lines) looks off
Is there any problem?
It looks alright
What is ur problem
Wdym
Usually servers with colour roles, have rest of the roles (staff roles and others) with no colour so the colour roles can be at the bottom of the hierarchy
code and traceback if any
the code, and the full traceback (error)
what does it say? that is what a traceback is
full traceback means, complete error
show the event
this then ^
on msg doesnt take all of that
why do you have a error handler in a on_message event...
and error handlers are for commands
U r looking for on_command_error
nvm u don't
Also it takes ctx and error as args only
who
Okay so all your error handlers go in on_command_error
who was that monster
Totally not me
Not in on_message
your jk right๐งโโ๏ธ
as on the name on_command_error
this is my old pfp :D
infact you don't even need an on_message event if all you had inside it is what u showed
btw
help ;-;
with?
this one
more than one if statement, change it to elifs
Replit db? Whatever it is you are accessing it in a weird way dunno certainly tho
it is replit db
Also why do you want to call attribute of function
You probably need to declare an object of custom class
i dun wanna repeat the same var everytime i use them
any docs?
That's common python OOP
class MyData():
def __init__(self):
...```
Yes
okok
There must be a better way anyway
Dont use replit db
=.=
it's sync, wont work well with discord bots
ok
im tryna do pip install praw, but it says I have invalid syntax, bcos I need to get a meme api
go to shell
you install it in the shell
how, im pretty new to python so im not sure how to do that
not the IDE part
u know where is the shell?
that is basic python lol
and type in pip install blahblah
A template for creating user-defined objects. Class definitions normally contain method definitions which operate on instances of the class.
help ;-;
__init__ can only be a normal method/function, not an async one
what are you even trying to do?
im trying to make those variable accessable everywhere
without scoping error
cuz i dun wanna call them everytime i use it
make it a bot variable then
but why not use a real database?
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
i cant use bot.var cuz
all the var needs a var that is call userid
and userid = ctx.author.id
Can i add a few libs to my code?
sure
i.e. i imported cv2 but not working....
as long as u need them just add them
go to shell
and type
pip install [packages]
i'm using vsc
oo
i just need import it to my code but there is error
i have ....
smh
?
hi guys
i just am saying"i have cv2 lib" but when i import this lib, an error occuring....
hi
ooo
lemme send u the solution
wat are going?
i saw it somewhere in stackoverflow
ok๐คฃ
@devout iris this one?
Well. When I try to do next command, it doesnt appear blue. Even the = between the embed=embed
Anyone
no idea either
are u trying to run the code?
heres the tutorial im following
basically, im tryna grab memes from reddit, and thats what it says to write
ok
Anyone?
idk no idea
don't blatantly copy code if you don't know what it does
Maybe just visual code studio acting up
Sometimes it happens to me
Ahhh, I did ] instead of } ๐คฆโโ๏ธ
That isn't even an error
Where
true
Well, I could'nt start a new command
**__Message__**
Ahh, That wasn't the prob
U forgot } in **__Message__**{arg}
Yes
A mistake
LOL ok
I fixed it, Thank You
:D
making music bot?
yepp
which library?
-_-
so yeah idk
what did you import
lol
to make music bot
how do I start a coroutine thread while bot is running?
i changed pc in my past pc it worked perfectly @brittle axle
same code just other pc
copy paste it here
from discord import activity, channel
from discord import embeds
from discord.embeds import Embed
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import math
import itertools
import random
import functools
import platform
from discord.ext.commands import has_permissions
import discord
from discord.ext import commands
import platform
import datetime
import json
from datetime import datetime
from asyncio import TimeoutError
from discord.ext.commands import BadArgument
from discord.ext.commands import Context
from discord import Member
from discord.ext.commands import EmojiConverter
from discord.ext.commands.cooldowns import BucketType
from discord.flags import Intents
import praw
from discord_components import *
import DiscordUtils
from discord_interactions import verify_key_decorator, InteractionType, InteractionResponseType
import datetime
import aiohttp
import requests
from discord.utils import get```
lmao
told ya
discord utils used to work but the library dosent work anymore since yt discontinued the dislike button
oh
use another library like youtube dl or switch programming languages from python or js
so what can i do
pretty much any library other than youtube dl dosent work for music bots with python
any library i know of
cant do anything
you can switch to js though im making a music bot with that
so i must code again ?
yes
welcome
@bot.listen()
async def on_message(message):
Unlock = discord.PermissionsOverwrite(send_messages=True)
Lock = discord.PermissionsOverwrite(send_messages=False)
Role = ctx.guild.default_role
if message.channel.id == 814207750342705164 and message.content.startwith('RPG miniboss', 'rpg miniboss'):
await ctx.channel.set_permissions(Role, overwrite=Unlock)
What i'm trying to do is, get the BOT to open the channel when someone says rpg miniboss then lock the channel after 5min. How do I do so?
Can you help?
?
This.
oh ok
I feel like I've done half of it. (Correctly I believe) and i'm stuck now
Ok. If anyone is online, you can also try help me
which role's id is it?
There's no role
reading it from first glance i think the code is correct
output it and see if there are bugs
Ok
did it work correctly? any bugs?
I've got 2 on_message commands and its not working. What can I change it to?
lemme think
do you want it to be specifically on_message or can you turn it into a command
No. It has to be an on_message
can you show any errors youve got?
Woah, No errors. But I have the green line
green line?
that means python updated its defenition of what on_message is from the previous line
Ok
thats why a green line is there
So what do I do? Is that a prob?
is the older command working or is this the only command that is not working?
just a sec
lemme take the api docs for a second
My WiFi is lagging
do you have intents.messages enabled?
oh ok
I'm so sorry. Send it and i'll see it once its stable
I'm so sorry. All I see is a rush of messages
oh ok
did you enable this
Hello! How can I add more embeds to a button?
ๆ่ฎฒไธญๆ็ๅ
ๅชๆฏไธ้ป้ป
wut
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
IDK. How do i check?
Check your bot constructor
bot constructor
Nope
so intents.messages=True ??
How do I add it?
guys, why not work the 5. embed?
go to discord developer portal
go to bot section
intents
and enable all
yes after that you have to do this i think i dont have message intents for my bot so idk wether this is correct
Done
this simple embed why not work?
There is still the green line
thats not because of the intents
Ok. So what do I do for that?
Will COGs work?
idk probably
Ok, Give me a moment. Let me write the code.
Can you think of a way to lock the channel after 5min?
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Tasks
Sorry?
!d discord.ext.tasks
No documentation found for the requested symbol.
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
That
Give me a minute. Can you help me with it?
Whats the error
embed.add_field(name="Moderation",value = "Moderation Commands")
^
IndentationError: unindent does not match any outer indentation level
Just start a task that runs after 5 min, locks the channel and then stopa
Stops
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
nothing space
๐