#discord-bots
1 messages · Page 915 of 1
I was thinking about making a base class for all of my cogs as the majority of them are/will-be inheriting from both discord.app_commands.Group and discord.ext.commands.Cog, I think making a base class which sub classes both of these and then sub classing this new class might be a better way to go about it instaed of subclassing both every time. If I did sub class both of those I would only need the super().__init__() in this base class right, not in all of the others? ```py
class CogBase(app_commands.Group, commands.Cog):
def init(self, bot):
super().init()
self.bot = bot
async def setup(bot):
await bot.add_cog(Owner_Cog(bot), guild=Object(id=default_guild))``` and I would still need to do the setup func for this new class in each file right?
next question, I think that is file is starting to get quite chunky and will only get more so, so I was thinking about splitting it out into separate files, one for each class but I'm torn on whether I should make more files in the same utils directory or if I should make a sub folder called helpers (so utils/helpers) and then make each file in there hold one of the classes. What do you think? https://github.com/SnowyJaguar1034/Zupie/blob/master/bot/utils/helpers.py
Hello I’m using discord.ext how do I make it so bot doesn’t response to messages in Dm
where do i add a color to this, it doesnt work when i try putting it
embed=discord.Embed(colour=discord.Colour.blue(), title="Franchise Owner"....)```
you can use hex codes
, that's mostly what I use
Guys how can i keep my code running consistently on Visual Studio
keep your computer online 
i don't understand these nested try except blocks
Hey @delicate epoch! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
oi post it again i didnt see it
wait wait thats confusing as fuck
its ok if your english is not the best, but try to explain it the best you can
What's ur native language?
Send it in German, I'll try to translate
Why do you store it in a dictionary tho?
U could just send the attachment
Do you want to store it tho? Create some kind of logging message with the channel it was sent in and the attachment
Its just fetching a channel and sending info in it
guys i have an issue so my bot currently only sends images and messages at only one time however i want it sent all at once messages and images included how would i do this please help.
also when i post an image it posts it everywhere
Um, there are a lot of things wrong with this
Perhaps you should read up the documentation on getting started with discord.py?
how would i make it work for the lowercase version also
you can make the bot case insensitive if you would like or you can add aliases
i read it but when joinning the stuff it just wont work
properly that is
That's because there's like at least 10 things wrong there, no offense
also i removed the codes and everything
just for sec
if thats what you were referung to
- Don't nest
on_message - Move your client instance out of a function
- No need for payloads, discord.py has native methods for things like sending messages,
channel.send()for example - Move
client.run()outside of your function as well, it should be in the main scope - time.sleep is blocking use
asyncio.sleep()instead
that's for the command name, i mean the arg
aka user
ah you can just lower the argument lol
user.lower()?
can i see the functions params im not sure what you mean/want?
so i got 245 just dont get 1 and 3
how would i send the messages
do i just send the post request
client = discord.Client(...)
@client.event
async def on_message(message: discord.Message):
await message.channel.send("You sent a message!")
client.run(...)
You don't have to
how do i make it where when you say a role name it sends the list,
Your call to retrieve_messages is never actually fired, this is because client.run blocks for the lifetime of your client
It will only be called after the client is no longer running
so how would i send to to other servers
This causes some issues with what you are trying to do, but also client.event won't register at run time here, but only when retrieve_messages is called
the message that is
Do you want the message to be sent to the message that the original message was sent in?
You can do
client.get_channel(id)
to get a channel
somat like this ?
IndentationError: unindent does not match any outer indentation level
gave me this error
uhh
would you know how to maybe fix the bot just need it to grab messages and relay to other chanels
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
Still nesting on_message
@client.event
async def on_command_error(ctx, error):
embed=discord.Embed(timestamp = datetime.datetime.utcnow(),title='**You do not have the permission(s) to run this command.**')
embed.set_footer(text = ctx.author.name, icon_url = ctx.author.avatar_url)
await ctx.send(embed=embed)
if isinstance(error, commands.MissingPermissions):
await ctx.send(embed=embed)("You do not have the permission(s) to run this command.")
else:
raise error```
How do I make the embed cleaner
ctx.message.created_at returns the datetime object anyway
so it works and the send message works so how would i send it to other chanels the same message
It works but I get a TE
TypeError: object datetime.datetime can't be used in 'await' expression```
nvm fixed it
Thanks
So i want to have a member be able to close a ticket when they finish chatting with a mod/admin but before i run this code i want to make sure it's right before i get rate limit
@client.command(pass_context=True)
async def ticket(ctx):
guild = ctx.guild
embed = discord.Embed(title = 'Ticket system',description = 'React 📩 to make a ticket.',color = 0)
embed.set_footer(text="ticket system")
msg = await ctx.send(embed=embed)
await msg.add_reaction("📩")
def check(reaction, user):
return str(reaction) == '📩' and ctx.author == user
await client.wait_for("reaction_add", check=check)
ticket = await guild.create_text_channel(name=f'ticket - {ctx.author}')
await ticket.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
await ticket.set_permissions(ctx.author, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
channel = client.get_channel(ctx.channel_id)
if not channel:
channel = await client.fetch_channel(ctx.channel_id)
if channel.name == f"ticket {ctx.author}":
emoji = ctx.emoji.name
if emoji == "❌":
await channel.delete()
You are not going to get ratelimited to the point where you can't make any calls to the api if you test a command like that one.
No i have many client.event()
I already been rate limited 5 - 7 times
Are you using repl.it as a hosting platform?
That would be your issue, not the events. repl.it shares IPs amongst it's servers, so this means if someone using the same IP given to you is RATELIMITED, you in return are ratelimited as well
As, discord ratelimits are based by IP
Oh okay
The most consistent solution here is to probably find a different hosting platform
Some others may suggest workarounds, but they are workarounds
ah well the rate limits are that big of a problem for me. It gives me time to look over my code to make sure I didn't mess up any syntax
Alright, good luck
Thanks and you too
I do that when i can't figure out something so yeah
Stackoverflow is my first stop when im stuck
I didn't, I have changed it up on my end
yeah?
pass_context has been pretty much deprecated for 5 or so years now
It's no longer required
I'm mainly looking right here
em = discord.Embed(title = 'Ticket system',description = 'React 📪 to close a ticket.',color = 0)
em.set_footer(text="ticket system")
msg2 = await ctx.send(embed=embed)
await msg2.add_reaction("📪")
def check(reaction, user):
return str(reaction) == '📪' and ctx.author == user
await client.wait_for("reaction_add", check=check)
ticket = client.get_channel(ctx.channel_id)
if not ticket:
ticket = await client.fetch_channel(ctx.channel_id)
if ticket.name == f"ticket {ctx.author}":
emoji = ctx.emoji.name
if emoji == "📪":
await ticket.delete()
it doesnt
nvm i figured it out
if isinstance(error, commands.MissingPermissions):```
does anyone know why this keeps running if someone writes a command incorrect?
Its only meant to run if they don't have permission to run a command
do you have the permissions set in the code?
discord.ext.commands.MissingPermissions
!d discord.ext.commands.MissingPermissions
exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
That needs you to implement the has_permissions decorator on the command too, make sure you added it
in my code i have bot.commands later and then this never works
@client.event
async def on_message(message):
username=str(message.author).split("#")[0]
user_message=str(message.content)
channel=str(message.channel.name)
print(f"{user_message}:{username} ({channel})")
if message.author==client.user:
return
if (client.user.mention in user_message) or (f"<@!{client.user.id}>" in user_message):
await message.channel.send(f"<@{message.author.id}> Pinging me does not do anything.🤣🤣\nType ""mp.help"" for more commands.")
and is@bot.event a thing
yes bot.event is a thing
- member class has a name attr which returns the members name as a str
- the content attr of the message class returns a str already
3.no need for the parenthesis in the if statement and theres probably a better way of doing that
youre literally using it
client=discord.Client()
bot = commands.Bot(command_prefix= ["mp." ,"Mp." ,"mP." ,"MP."], case_insensitive=True)
.event deco is bound to a Bot class instance which in your code its named client its just class instance naming???
...
hi binds
👋
will discord take down your bot for using youtube-dl in it for music
like if someone reports it
or is it up to youtube themselves to take action
i mean its breaking yt tos which discord says if you break a platforms tos in their platform it will break their own tos so probably
oh ok
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
AttributeError: 'Message' object has no attribute 'send'```
i dont understand this
something is off with your ctx prolly
Message doesnt have that attr so it would be ctx.channel
argument naming its in a on_message
🗿
🗿
since ctx.channel returns a TextChannel obj just use the .send method
ok it works now thanks

Are you guys using discord.py or pycord?
is there a way i can make a command called "random" without the random module interfering with the function
Umm like I just shifted to it and it aint working at all....hbu what do you use?
how can the module interfere with a function
Yea name it Random
Umm yea
i used disnake but idk how its doing because i dont do bot dev anymore
How about no
nah its better to name it _random
UpperWord is for classes
Aha Ill try that one
Umm yea we can do that too
!pypi disnake | but you should main imo
but tbh i would stay in disnake because at this point i dont trust Danny too much
Umm ok ill try that one majorly I just want functionality to add buttons which seems difficult
Yeah but you said to use main and then to use disnake
So make up your mind
well dpy will add it but disnake has a good guide and examples
suggestions
Aha then good enough and does it have code similar to discord.py so I like dont need to change the whole code
1.7.3 with disnake not really much but main to disnake yes their is allot of changes
Aha Ill checkout it thanks a lot again for the help!!
there will be the 2.0 breaking changes when u update from 1.7.3 to disnake
Wow disnake works....ill try to fix my code in it!!Thanks
what does this mean
!e print("lol"[5])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | IndexError: string index out of range
only 3 elements which their positions are 012 and youre trying to index the one in position 5 which their is no 6th element
huh
I'm confused on how you could be confused by that explaination

how would i make this react to the bots msg not the one u send ?
reaction = "👍"
@bot.command(name = 'order')
async def order(ctx: commands.Context, *, echo: str = "```oops! make sure you say something! EX: !order [example]```") -> None:
await ctx.send(echo)
await ctx.message.add_reaction(emoji=reaction)
oops i have ``` in the middle
u get the point tho 🤷♂️
cheers 😄
i would
Not everyone likes making things complicated, and this method is easier if you trying to make checks or something
await (await ctx.send()).add_reaction()

not a critical error but: await client.send_message(channel, '{} has added {} to the message: {}'.format(user.name))
AttributeError: module 'http.client' has no attribute 'send_message'
Outdated methods
wait thats not bc of ur code nvm
guess thats what happens when forums are ur teacher
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
i got it tysm <3
in saving a few bytes yes in readability ha no
but people always say its not readable when it is
add an actual message to it and you will understand
still do
Class name bitch
argument naming
it has something to do with that?
Class name
you arent even indexing
Context is the class, not the argument name
idc do it right
ctx is the name most users use as an instance of the context class so use the argument
idk why indexing is.
Sending an empty message huh
Your code tho?
you got me their sarthak
*there

(nvm that, it's common here)
worl
If you're looking for a serious chat, you're at the wrong place 🤡
yeah go to #esoteric-python

I wanted to use hata but the docs are making me hate it
Hata is an asynchronous Discord API wrapper built on top of scarletio. It is designed to be easy to use, with also providing rich API offering everything what an advanced developer might need.
Named after Hata no Kokoro from Touhou Project.
is there smtn that can detect if a user reacts to the reaction?
ill take a look, thanks
use some markdown which suits your usage
i gotta use embeds lol im still using ```
Like codeblocks
its something like a console?
bro sarthak you blind
make a new line
python3 main.py
# your markdown
$python3 - main.py
# what I'm asking to do
oh
use bash or other type of markdowns
Which are actually meant for terminal
and not cmd
idk what cmd windows use
isn't it like a completely plain console
no the command prompts screen always starts with the dir of the user iirc
it can run py
kali terminal is cool
yes i agree
and you should have a footer of the file thats being used and a avatar of the user who requested the terminal
sorry i ment avatar*
lol
what is the issue here
how would i make it so the bot doesnt set off the reaction reaction?
@bot.command(name = 'order')
async def order(ctx: commands.Context, *, echo: str = "oops! make sure you say something! EX: !order [example]") -> None:
msg = await ctx.send(echo)
await msg.add_reaction("👍")
await msg.add_reaction("👎")
if str(reaction) == "👍":
await ctx.send("u reacted with 👍 ")
if str(reaction) == "👎":
await ctx.send("u reacted with 👎 ")
god this code is a mess when u put it into discord
!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.10)"). 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.10)") 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.10)") 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**...
When I define channel as nextcord.TextChannel in nextcord slash command, I got this error. Can someone help?
NotImplementedError: Type "class <'nextcord.channel.TextChannel'>" isn't a supported typing for Application Commands
oh damn ur awesomne

@slate swan im reading the doc, if the bot is making the msg, and being the first one to reatct, wont it set itself off?
i might be wring tho
pardon?
the bot sends the message and the bot is the onw that reacts first, so, wouldnt the " await client.wait_for('reaction_add' " get set off by the bot
Umm how can I make a private channel with the bot which is only accessible by staff and certain role?
i acually have this exact code lol, 1 sec
Aye for sure!!
just add the reactions before you wait for a reaction gateway event
@bot.command(name="start")
async def start(ctx):
guild = ctx.guild
admin_role = guild.get_role(make this ur admin id)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
admin_role: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True)
}
ahhhhh gotcha
how to execute a python script automatically after 2 mins in replit

Thanks a lot
like a task?
😅
i gotchu
🤫
yep

it's not commands
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
forgot its tasks


actually it is two files
trade_msg.py
cogs then
i want to run trade_msg.py every 120 seconds
a file?!?!?
function*

lol
same
its not an actual discord bot
it is a discord account but bot too
ye
against ToS lol
mf makin spambots 🗿
no its actually to send trade ads in different server when i am not available
ty for info
bruh, just make a auto type script
thats not agagisnt tos right?
i have auto typer but i need to run my device 24/7
orr u can get banned up to u 🤷♂️
mass dm advertising is against tos aswell iirc
2x tos break! DOUBLE POINTS!
it probably depends on which endpoint and your logs of each request
hey guys how to fix this error
what is client?
should be @bot.command()
you initialized bot
thanks
i use @ bot.event
idk what im doing in my sleep
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
yes.... in my bot it was client... but while going for a rewrite i opted for this
yes thanks........ I just am used to client.... I forgot.......... and you'll helped me thanks
yes it is....... but time saved
send an ss better
error is hard to read with txt
it is not dm advertising so i think it is good
🤔
self bots arent good no matter what they do lol
lol
https://paste.pythondiscord.com/yunumesapo is giving me the error below
https://pastebin.com/xGtkw46X
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
k
and yes thats my name idgaf
ctx is first arg
hey whats sfm?
uhh....... ill google it
ohh nice
infact i do too, pixel art
so message would be behind the ctx?
nice
hello, i asked a question in the d.py server and was wondering if i shoud send it here aswell
what is that argument?
if you want it to be message object
you can only make it like message = ctx.message
yup
fuck hold on
(message, ctx: commands.Context, *, echo: str = "oops! make sure you say something! EX: !order [example]") -> None:
@buoyant quail
no
k'
ctx is a positional argument which its position is always the first
so msg can just go behind "example}"
but if its in a method ofc it will be the second
depends
apparently not: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: order() missing 1 required keyword-only argument: 'message
what wpuld it depend on?
afaik you cant have 2 kwargs in a command
damn i forgor 💀

i get what is shows as 1 in the picture sent in the discord channel
i just cant seem to mash this reactions detection code with this echoing command 😭
you mean it gets saved as the format and not the actual values?
no i want what is saved there to be sent in the discord channel with the {} gone out of the message but i got them in during testing
and the message need to be sent as a f string
im so confused...
have the before text outside of the codeblock
the "Terminal" text
and indents are a bit off
ok, any way i can add qwargs farther on in the string, rather than in the start? idk if im asking this right
have you used pymongo?
Maybe use something like this ”{member.mention} says hi”.format(member=…)
pc/Users/okimii/
>>> hello world
hello world
this looks good to me
well the issue is i don't want it to complex for the user because i send &wenable #channel Welcome {member.mention} to {member.guild} this is a test!
in discord
@slate swan :x: Your eval job has completed with return code 143 (SIGTERM).
001 | lol
002 | lol
003 | lol
004 | lol
005 | lol
006 | lol
007 | lol
008 | lol
009 | lol
010 | lol
011 | lol
... (truncated - too many lines)
Full output: too long to upload
you see the line numbers
mhm
can anyone help?
pardon and its a kwarg
do you understand my issue now
a kwarg means a keyword argument
here let me make it simpler
mb
server = result[query]
channel = self.client.get_channel(server[0])
message = "Welcome {member.mention} to {member.guild} this is a test!"
await channel.send(f"{message}")```
can anyone help? with that?
With?
@bot.command(name = 'order')
async def order(ctx: commands.Context, *, echo: str = "oops! make sure you say something! EX: !order [example]", message) -> None:
msg = await ctx.send(echo)
await msg.add_reaction(":thumbsup:")
await msg.add_reaction(":thumbsdown:")
channel = message.channel
await channel.send('You have 60 seconds to confirm! Press [placheolder thumbsup] to confirm! press [placeholder thumbsdown] to try again!')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == ':thumbsup:'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('Gotcha! order confirmed')
else:
await channel.send(':thumbsup:')```
TypeError: order() missing 1 required keyword-only argument: 'message'
i can't do that because of this reason
and i can't f string that in the database because i don't put quotes to begin with
and if i do put quotes it ends up like the id and slot 0
* consumes all arguments so if you did !order hello cool d.py would think hello cool is the echo parameter
so remove or move it?
move it
before message
so: ctx,*,msg, echo:str?
ahhh
aren't those limited to staff only
Not this one
where did you get it 
U on mobile?
Hmm, then just click on the button. Will just let u use the new Slash Commands UI and Chat Input
Your wish ¯_(ツ)_/¯
?
chat input?
i like new one better
Idk, most probably modals
But then, I have never looked into modals, even never used those
@maiden fable you asian?
is there a such thing as a double f string
anyone know how to make a turn off command where when u run it a certain command will stop working till u turn it back on
yep
Udk?
Well imho its better since now there are boxes around each param
well i have this ```py
@commands.command(name='toggle')
@commands.has_permissions(manage_guild=True)
async def toggle(self, ctx, *, command):
command = self.client.get_command(command)
if command is None:
await ctx.send("I can't find a command with that name")
elif ctx.command == command:
await ctx.send("You can not disable this command.")
else:
command.enabled = not command.enabled
ternany = "enabled" if command.enabled else "disabled"
await ctx.send(f"I have {ternany} {command.qualified_name} for you!")```
Eh, most probably u ain't used to seeing this, so its feeling weird to u
u know
u can also do command: commands.Command in the function
no i did't
and is there a such thing as double f strings?
how
what u wanna do
i have a message from my data base and it has {} in it and it is in a {message} varible but it sends the messages with out defining the stuff in the {}
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
{}
!e py cloud = welcome {member.mention} to {member.guild} this is a test! message = cloud print(f"{message}")
@echo wasp :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | cloud = welcome {member.mention} to {member.guild} this is a test!
003 | ^
004 | SyntaxError: invalid syntax
i know that
bt yes that my prob
how can i fix that
whats udk
You don't know
!d str.format
str.format(*args, **kwargs)```
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces `{}`. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
```py
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
``` See [Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings) for a description of the various formatting options that can be specified in format strings.
example? i hate strings
thats why I asked
!e
a = "Hi! My name is {}"
print(a.format("Hunter"))
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
Hi! My name is Hunter
The embed gave an example already
Ah, well yea I am Indian
!e
message = "Welcome {} to {} this is a test!"
print(message.format(member.mention,member.guild))```
@echo wasp :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'member' is not defined
@maiden fable like that except without the error because it will be defined in the file?
well not everyone wants this format it is per server
that the other road block
use a db then
then store the message in the format Hi! Welcome to the server {}, Hi, {} and stuff like that
Bots tend to use variables, like MEMBER_MENTION and stuff like that for the user to input so that they can also use str.replace
but not everyone is going to want to do that
i got it all set except for the stupid f string
it needs to use f twice onece out of the varible
dang you a comedian
but if i use str.format i'm stuck with doing it a certain way
why when using
@commands.check(MYID)
@commands.has_permissions(manage_messages=True)```
it only checks for permissions and not both?
you can't put an id inside of check

can i do this str.format(f"{message}") and give doc link please
my face rn too
it checks id when i donthave check.permissions
but when I have both it just ignores to check for authors ID
can't you just do ```py
message = 'hi welcome to {}, {}'
message.format(ctx.guild, ctx.author) # output: hi welcome to Python, sift#0410
I really need to start putting comments like that I cant lie
I have 0 comments in my entire bot atm and just have to use search function to find shit
no sadly it would be nicce
nvm
wdym "no"?
I mean it is useful to make a comment like
because when I wanna add some id auth to kick
i have to just search kick and theres like 10 different words with kick in my bot
so what's not possible?
also why is member typehinted as a discord.user? it's supposed to be typehinted as a discord.Member
for the second line it says
Welcome to {member.guild} please look at #925976154890993734 and thanks for joining {member.mention}
if you did the format method it would be backwords
on the second one
@boreal ravine
@bot.command(pass_context=True)
async def random(ctx, *args):
if len(args)==2:
(minInt,maxInt)=args
if len(args)==1:
minInt=1
maxInt=args
else:
await ctx.channel.send("Invalid")
if minInt.isnumeric() and maxInt.isnumeric():
minInt=int(minInt)
maxInt=int(maxInt)
rand=random.randint(minInt,maxInt)
await ctx.channel.send(f"<@{ctx.author.id}>, your random number is {rand}")
else:
await ctx.channel.send("Invalid")
why does this not work
it doesnt give error
On a command my bot displays a button and I just use it to get the user id of the person and send him a dm....the thing is I just wish to suppress the words "Interaction failed"
You just put it?
Oh wait lol
i mean in code
i cnt
?
oh i can
if you mean in discord: " ``` "
sry a tysm!
Why does this not work
because you're checking an object....and not an instance
😔 OOPs Moment
So what do I do?
get an instance of the object
hey, whats that?
Lmao
Also why == instead of is
it works
My brain
👀
no
So what do I do?
Role is an object, not an instance of Role object
make an instance of Role object
how to make a message logs?
?
?
client.event right?
Yes
i meant
@client.event
Yes
ty
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Where’s the code?
wdym?
Why don't you just use the vsc python extension to run the program
if not role 👀
have?
which?
why dont you help when you know the solution :/
Cz I am in a game
Ok you have that installed
Now see on the top right bar do you see a "Run" menu?
not that shit
so i must add python in right?
.
this right?
here?
Yea
lol
use this, and use run without debugging
Just do it again
Heyy
#@commands.has_permissions(manage_messages=True)
@discord.Permissions.moderate_members(True)
async def mute(ctx, member: discord.Member):
mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")
await member.add_roles(mutedRole)
await member.send(f"Shuddup stupid KEKEKEKEK {ctx.guild.name}")
embed = discord.Embed(title="mute", description=f'Idiot {member.mention} has been muted', color=0x1abc9c)
await ctx.send(embed=embed)```
for this mute slash command, i get the error 'flag_value' object is not callable. can someone point me in the right direction on how to properly enable ```Permissions.moderate_members```?
@static lintel as far as I know that isn't a permission
mute command require manage roles, if using muted role to mute someone
I would use ctx.author.guild_permissions.manage_roles
oh it is for discord.py 2.0 for slash commands
timeout command require moderate members
moderate members is for timeout
yeah thats what im trying to do
@hazy oxide
I'm pretty sure you could also use .timeout_members
!d discord.Permissions.moderate_members
Returns True if a user can time out other members.
New in version 2.0.
Lemme see hold up
use humanfriendly to convert the time
@static lintel use @commands.has_permissions(moderate_members = True)
this will work for slash commands too?
Thats what they told me in dpy.
How do I make a command to dm a user?
I'm not very experienced with this new permissions
Send a message to the author
interesting... ill try it out and see if it works
Or to dm someone else?
dm sum else
I don't know why you would wanna do that
my bot uses a whitelist system
and when i input teh users id i want to make it dm them
Then dm them when they join
they are already in the server
There is no point of forcing members to verify when they already joined. Half of the people won't do it because they're annoyed
noooo i mean my bot is a tool thats handy and when sum wants it
i whitelist them w ;wl 023949204
and then i want the bot to dm them
Ah a whitelist
Yeah
dming a member is very easy. You should know how that works tbh
You know how to pass a member in the paragrams?
have u heard of me being lazy
Would this work for user groups aswell let’s say I wana @ all coding members
anyways
Nw then
...
yes
Then do that
And member.send(messagessss)
Dpy isn't a good library to start with without knowledge
lol i've been coding in py for 4 years madam
and i havcent touched dsicord.py in 2 years
what to use instead of discord.py? It's unmaintained, right?
ohh alr
which one? Why? 😄
fetch_user() still works right or is that to outdated now
also, thanks
I'll suggest Disnake if you want to continue using discord.py like Library
Else go for hikari
is fetch_user still working or is that outdated now
i remeber using fetch_user and then in () putting the user id
and it working w send_message
send_message?
did you like not update your discord.py for years?
send_message 👀
only place its getting used atm is dpy 2.0
interaction.response.send_message
*any interaction
including buttons and context menus
Yeah but interactions are only in dpy 2.0 atm (in the discord library)
Yessir
Oh I just noticed I said slash commands
I didn't mean to😅 I meant buttons and all the stuff too
so something like this would work right
def dm_User(ctx.author.id):
member = fetch_user(ctx.author.id)
member.send("Welcome!")
Why a function
You're pretty wrong atm Obama😅
Do you know how to use commands?
Who needs help btw
yes
You don't need it in a function
i like it better in a function
Pass member in paragrams and send to the member in the command
That's just making it hard for yourself
thats personal preference
But like- you can typehint it to a discord.Member object and just send it to that, it takes 1 line
It should be like
@client.event
async def on_member_join(ctx):
await member.send("Hello!")```
**__ ~~I think~~__**
I just did the "welcome" as exampl
xd
yes but my commands are diff some need to send to diff users and some need to send to the user who sent it
I am so happy, I finally hosted my bot on Heroku
it should be await ctx.send since the ctx is passed as member
If u Want to send to the user just use ctx.author.send
Yeah-
Lemme give you an example
It is not...?
@slate swan did u see that?
@bot.command()
async def test(ctx,member:discord.Member):
await member.send('test')
Author.send will be message sending to the author bruv
This is how you send to a tagged member/ id of a member
READ EVERYTHING! except code
@slate swan

sus
oh f sorry
Not my emoji
Ye, the ctx param passed as a discord.Member in the event
Ur sus
I've never seen ctx in an event before
how?
yeah and await ctx.author.send("test") it sends the message to the one who did the command right?
Yeah but they shouldn't use member.send then
Yeah
Well It doesnt matter. does it?
alright thanks for all the help and the loss of braincells i gave to yall
This is out of topic guys! Don't discuss emoji stuff or whatever here
18+
ok?
Nevermind
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
🫂ye
what does this error mean?
TypeError: '_asyncio.Future' object is not subscriptable
Code
ok
Send code-
@bot.command()
async def rank(ctx):
stats = xpCol.find_one({"_id": ctx.author.id})
if stats is None:
pass
else:
xp = stats["XP"]
lvl = stats["Level"]
boxes = int((xp/(200*((1/2) * lvl)))*20)
rank = 0
rankings = xpCol.find().sort("XP", -1)
for x in rankings:
rank += 1
if stats["_id"] == x["_id"]:
break
rankEmbed = discord.Embed(title = "{}'s level stats".format(ctx.author.name))
rankEmbed.add_field(name = "Name", value = ctx.author.mention, inline = False)
rankEmbed.add_field(name = "Level", value = lvl, inline = False)
rankEmbed.add_field(name = "XP", value = f"{xp}/{round(5 * (lvl ** 4/5))}", inline = False)
rankEmbed.add_field(name = "Rank", value = f"{rank}/{ctx.guild.member_count}" , inline = False)
rankEmbed.add_field(name = "Progress Bar", value = boxes * ":blue_square:" + (20-boxes) * ":white_large_square:" , inline = False)
rankEmbed.set_thumbnail(url = ctx.author.avatar_url)
await ctx.send(embed = rankEmbed)
duh
Are you using motor?
yeah
await the find_one
Oh then u should await it
ok just a sec
I thought u weree using pymongo
why are you using pass if it's none?
U mean this?
@bot.command()
async def rank(ctx):
stats = await xpCol.find_one({"_id": ctx.author.id})
if stats is None:
pass
else:
xp = stats["XP"]
lvl = stats["Level"]
boxes = int((xp/(200*((1/2) * lvl)))*20)
rank = 0
rankings = await xpCol.find().sort("XP", -1)
for x in rankings:
rank += 1
if stats["_id"] == x["_id"]:
break
rankEmbed = discord.Embed(title = "{}'s level stats".format(ctx.author.name))
rankEmbed.add_field(name = "Name", value = ctx.author.mention, inline = False)
rankEmbed.add_field(name = "Level", value = lvl, inline = False)
rankEmbed.add_field(name = "XP", value = f"{xp}/{round(5 * (lvl ** 4/5))}", inline = False)
rankEmbed.add_field(name = "Rank", value = f"{rank}/{ctx.guild.member_count}" , inline = False)
rankEmbed.add_field(name = "Progress Bar", value = boxes * ":blue_square:" + (20-boxes) * ":white_large_square:" , inline = False)
rankEmbed.set_thumbnail(url = ctx.author.avatar_url)
await ctx.send(embed = rankEmbed)```
yes
uhm it wont work bc of await xpCol.find! It shouldnt be awaited
ok
it should
i've tried it but it doest work
hm
for x in rankings:
rank += 1
if stats["_id"] == x["_id"]:
break
should be
async for x in rankings:
rank += 1
if stats["_id"] == x["_id"]:
break
``` right?
cuz i'm getting python TypeError: 'AsyncIOMotorCursor' object is not iterable
ig so haha
Ye ik
He's using find not find_one
@slate swan
Oh, another one
use motor.motor_tornado.MotorClient("ur database url") instead?
nvm, it works now
Yea, as the example says
thanks guys
Great!
@slate swan pls help me
how to put more one word in a txt file?
i only can put one then its work
if i put more it wont work
i did but not work
if only one like this then its work but
if like this then wont work
ahh ok ty
still not work @slate swan
i did
wdym?
change name or extension?
i did it
idk why
should i change from "with open" to "a = open(bad_word), data=json.loadslnsadlkjnsajldnsalnaslknsa?
like i just do with file json
open,read() and loads
instead of with open as
use json.load(file) instead of json.loads(file.read())
it not releated to my problem
k
still not work
readlines() is better imo
are you trying to like get all the words in the text file?
He'a tryinf to see if the words in the message content
Is that a private bot?
For ur server only right?
then eh use database instead?

.env file?
Ye, since the bot is public :) so everyone can ban words(wit db ofc)
Oh
Let's start hard coding the token in the code and hope for the best 👀
That's how I have been hosting my API on replit. Everything is public, but no one has ever seen the code 

how do i check if an object exists inside the json file?
example:
{
"Users": [{
"a":{
"a":"item"
},
"b":{
"b":"item"
}
}]
}
I want to check if the user exists, if not, return False
Source code: Lib/json/__init__.py
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript 1 ).
json exposes an API familiar to users of the standard library marshal and pickle modules.
Encoding basic Python object hierarchies:
read that json, and use dict.get
!e ```
json_ = {"exists" : 1}
print( json_.get("exists"), json_.get("doesn't exist"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1 None
If it's there you will get the value, elseNoen
it's just returning none
{
"954331209599709195": {
"user": "arcanjo",
"name": "arcanjo1"
}
}
i need to check if userid is already "registered" in json
if user already exists it returns true, if not false
Code?
the on_message_edit event triggers even if message wasn't edited?
att, I had something wrong here, now it's working, much done thanks
How to make optional command argument?
def func(optional=""):
if optional:
print(optional)
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thank you
unnecessary
why make a separate function when you can do it within that function
indent the send line
So ita like this? ```py
await msg.channel.send(.....)
indent the line
dude, no, the whole line
Ok
also, thats a very bad implementation of blacklisting words
How to do it properly
if any(word in msg for word in swear_words):
await msg.delete()
Gpt it
There's actually another huge disadvantage still; let's say one of your blacklisted word is a part of another word the message will be deleted, which is commonly known as the Penistone problem, see https://www.youtube.com/watch?v=CcZdwX4noCE
In a small town with an unfortunate name, let's talk about filtering and innuendo. And use it as an excuse for as many visual jokes as possible.
I'm at https://www.tomscott.com
on Twitter at http://twitter.com/tomscott
on Facebook at http://facebook.com/tomscott
and on Instagram as @tomscottgo
(Thanks to James Paulsen for prompting me to do th...
yeah that too is an issue
👀 str.split() exists
nice sign board on thumbnail though 
Lmao
Still won't really work, filters need to be immensely complex to even be partially successful
i.e. badword vs b4dw0rd
@slate swan @vocal plover
I spent 8 months writing AI automod as my job so uh, I've experienced most of this pain
press backspace after delete()
there is an invi char
AI for discord bot pfffttt, no life
Hmm, then seems like a work for me
eh, moderation is much easier on large servers with the aid of AI
source: I mod large server and AI helps me
Yeah slate 2 is pretty nice
Yup
can't wait for general availability so we can properly have multiline slash
Wait multiline support is also there in the build override?
understandable, a server with 400k members only has one bot with the commands to kick ban mute 
wait huh, how
no clue, but multiline is dependent on slate 2
I posted the build url in the chat before
so slate 2 needs full release before we get it
orait
Just click on the button
or 4 bots that do that
actually might be 5 lol
yeah done
Including u or.......
zep, dyno, raptor, hep, lester kinda
....
where is vcokltfre?
not a bot smh
I beg to differ
!ot woa....
okay the new slash UI looks dope 😔
In fairness each has their own reasons for being there
Indeed
I was so excited for modals and now that they're out idk what to use them for 
i am on mobile
same
Looks like your discord.py version isn't high enough, you need to install the master/github version
pip install git+https://github.com/Rapptz/discord.py
pip install -U discord.py
Oh
Yes I can see
You'll need git to use the git version: https://git-scm.com/downloads
yup
@vocal plover @slate swan help meeeee
what
...
Would it be better to save a whole VoiceChannel in an object aka keep it in memory, or keep just the VoiceChannel#id and convert it to a VoiceChannel later on (for memory's sake)
Or does it barely make a difference.
(Pycord / discord.py)
press the button that works as a backspace then 
realistically no difference, discord.py takes up far more memory than this will affect anyway, so this would have comparatively very little effect
Probably, what if we're talking a large scale bot though
Like 1000 VoiceChannel's at a time
It might impact CPU more tbf
Here is my keyboard
oof
a thousand voice channels is still essentially nothing in terms of cpu and memory on any modern computer/server
Uhhhhh
the second button on the right
oh god
Alr ty
That, yea
just learn how to use a phone, it'll be better
ok,you mean this?

Weird keyboard layout btw
Does anyone have any experience with Telegram bots?
😔 Yes
Dude
two cap btns 
I do 50 wpm and ur saying this
Some phones have it, but never saw the backspace button at the top
😔 I can do 70 on a laptop. Its difficult to type on a mobile
sad Gboard noises
welp
Ik ik no need to flex
nice
lol
😔 But then I just use 2 fingers
same
Oh well, no need to install then
I think, I uhh will just go away

Lol,its important and easy cuz if ur dependent on ur left hand then use left one but if for right hand then use right one eeee
@slate swan on replit,it doesnt work
just use both of your hands 
what?
I mean i cant click backspace on the place of the error
I use 2 fingers 🤞
Ok lemme try
just do whatever you want
S.M.H.
1 finger from each hand
thats honestly a worse idea
😔 Also no use of fast WPM, everyone still copies code off stack
I haven't been on stackoverflow for 6 days smh

@maiden fable i cant do that the error comes still,can i guve the source code link?
Plot Twist: I haven't coded for a week
Sure, uhhh, ig
Checm ur dms
Done
dms 




