#discord-bots
1 messages · Page 941 of 1
tbh a really nice and simple explanation
Wow
Repl is actually being blocked by uptime robot
For a website you'll have to bind a port so a docker port is re-routed to your host port
To be fair tough docker is overcomplicated. Could have been made a lot easier.
With overcomplication comes extensive customizability which is suited in a professional environment
Yep, if I were to do it for a discord bot , will it properly hold a SQLite file?
Very much so.
Thus, not recommended for beginners.
Sure
But I'm not privy to using a database within a docker container
I'm just running a postgresql database on my host machine
Oh you can just link them up like that with postgre?
Don't know if a docker container can access an external postgres, since it's meant to be isolated
Why couldn't it?
Docker actually has a postgres image
Huh
So maybe I'm mistaken
The PostgreSQL object-relational database system provides reliability and data integrity.
Cool, nice talking to you 👋

Better if i go sleep as well 
Night
👋
Why is this pinned?
#help-bagel message @undone halo i used this code and i did this. is there a way to get it so that the embed updates with how much time is left?
yes, just use timestamps
I think you meant to ask someone else, I barely know my way around bots
oh how do i use timestamps?
<t:unix timestamp> <t:999999>
when i go 2 load my cog it says "Enable tracemalloc 2 get the object allocation trace back"
anyone know why
That happens when you don't await something
im trying to see how many servers my bot is in by going
,servers
and i dont know where to start
{len(bot.guilds)}
Hint: bot.guilds returns a list of guilds your bot is in
but where would i put that
wherever you want
Depends where you want to display it
robin a pro i'll let him do the talking
i want it to say how many it is in when i run the command
For example:
@bot.command()
async def my_command(...):
print(f"Bot is in {len(bot.guilds)} servers!")
I'll let you use that as an example to adapt it to your needs because printing to console isn't very helpful
so if i replace my command with servers and ... with ctx and ctx instead of print would it do that
I'm not quite following
let me get an example
await ctx.send(f"{len(bot.guilds)}
That would be great
the f string is very ugly
Missing a few things but I would suggest not spoonfeeding
missing?
@bot.command()
async def servers(ctx):
await ctx.send(f"Bot is in {len(bot.guilds)} servers!")
that would work
yeah
missing a " and misplaced the ending parenthesis
oh yea 😭😭
but can anyone help me
how am i supposed 2 await bot.load_extension if it's not in a function?
do i HAVE 2 put it in one
why what's your code
There are better places to load your extensions than your top-level
if filename.endswith(".py") and not filename.startswith("_"):
bot.load_extension("cogs.{filename[:-3]")
there's an f string in the bot.load
I'm going to assume you're on d.py 2.0 because you mentioned load_extension needing to be awaited. In 2.0, you have a setup_hook you can run it in
ye i'm on 2.0
explain?
You can overwrite the default setup hook
async def MyBot(commands.Bot):
def __init__(self, ...):
# This is where we used to load_extension
async def setup_hook(self):
# This is where we want to load_extensions now. Keep in mind you can await it
await do_something()
bot = MyBot(...)
also another alternative is loading extensions in a main, async function and starting your bot from there
That gives you more fine-grained control, and is how we did it pre-setup hook, yes
Both are viable options, you pick which you feel to be easier
if message.author == client.user:
return
if str(message.channel.type) == "private":
await add.reaction("✅")
``` Tried this as `message.add.reaction` and `client.add.reaction` with both had no "add" attributes, and as it is it says that "add is not defined"
I prefer the main async function method becuase for the aforementioned fine-grained control, and also I like having a defined entry point into all my asynchronous programs
my main.py looks nothing like this, is that an issue?
Why this is not working there is no errors
isn't it add_reaction
You probably meant message.add_reaction()
No shot I'veb [onqjwdiu[danwjk
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds 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.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
God.
Not an issue. I'm guessing this is how you do it:
bot = commands.Bot(...)
Most people do it that way, it's simpler. It also provides you with less control over your bot. Transitioning to a bot subclass isn't very difficult, in fact @spring flax (sorry for ping) is writing a guide on that to put up on the pydis site :)
I need sleep, thank you
shutting down
py
@client.command()
async def syncofficials(ctx):
if ctx.author.id == 771252695667310623:
await ctx.send("Sorry")
else:
return
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if "™️" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)
No erros but not working
Define "not working"
Actually I want to replace author with role id
Also, this may be a good time to ask about this, but is there a way to sort of "slice out" a mention from a string of message.content?
Just, remove it?
One moment
who is helping me
Aha, I love it when this happens. You're looking for exactly discord.utils.escape_mentions(text)
No way
Help me anyone
We can't help unless we know what "not working" means in your case
yeah still waiting for your answer
Again, what does "not working" mean
It's not sending sorry
Yes
Whose using the command? You?
My alt
But even if I send
It's not sending sorry messagr
Then there's a problem somewhere else
Try printing to see if the command gets picked up
Can you pls help
@client.command()
async def syncofficials(ctx):
print("command was called")
...
It's printing
Okay, now try printing this:
print(ctx.author.id == 771252695667310623)
Works
It prints "true"?
Yes
Can you show how your code looks like right now?
@client.command()
async def syncofficials(ctx):
print("Command Was Called")
print(ctx.author.id == 771252695667310623)
if ctx.author.id == 958421003921403995:
await ctx.send("Sorry")
else:
return
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if "™" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)```
Can you also add
await ctx.send("Command was called")
at the top?
It might be an issue where the bot's not able to send messages
ok
I have a feeling that I'm going about this the wrong way, so is there a good way to get a user object from a user ID in a message?
Hmm something's not right
Is it a command?
Not quite, just starts with $
If so, you can typehint it and discord.py will provide you with the appropriate object
@bot.command()
async def my_command(ctx, member: discord.Member):
# member is a member object
print(member.name)
Oh wow, I was doing that in a very roundabout way
bruh
Take a look at this: https://discordpy.readthedocs.io/en/master/ext/commands/commands.html#converters
There we go
this is what happned
it said sorry but also performed the action
Well yes
actually it should not sync
That's what your code is telling it to do
If you want that, your code should look like this:
but i don't want it to be like this
if ctx.author.id = someid:
# say sorry
return
??
What?
Don't use an else: return
then what
Send the sorry message, then return immediately after
if ctx.author.id == 123:
# say sorry
return
# other stuff
Is it possible to do this with ```py
elif str(message.channel) == "channelname" and message.content.startswith("$ "):
Fixed
So you want to check if a message starts with "$" and is in a certain channel?
Thanks
*under an on_message event
Well you can leave out if it starts with "$" becuase command handlers won't be called anyway
And it's best to compare IDs rather than names
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\impre\OneDrive\Desktop\Vouch\main.py", line 85, in on_message
await userCommands.vouch(message.author,
File "C:\Users\impre\OneDrive\Desktop\Vouch\userCommands.py", line 24, in vouch
vouchNum: int = d['VouchCount'] + 1
TypeError: can only concatenate list (not "int") to list```
d['VouchCount'] is a list
Mm, the last thing I tried was a \d{17,19} regex, and then used get_user on it, but that didn't seem to work 
You're overcomplicating it
What do you want your bot to do if a message was sent in a certain channel?
@sick birch how do i fix it
I'm gonna need a lot more information on that
Here, I'll send the full code
For example, what is d, where does it come from, what's it's defined structure, if any, etc
I was talking to Austin, sorry
yours is a relatively simple problem
Gotchu
But I need to know what you're doing if the message is sent in a certain channel
elif str(message.channel) == "channelname":
# what here?
d = data.loadJSON(data.DATABASE_FILENAME)
vouchNum: int = d['VouchCount'] + 1
vouch = {
'ID': vouchNum,
'Giver': user.id,
'Receiver': targetUser.id,
'IsPositive': isPositive,
'Message': message,
}
pendingVouches: list = d['PendingVouches']
pendingVouches.append(vouch)
data.updateJson(data.DATABASE_FILENAME, {
'PendingVouches': pendingVouches,
'VouchCount': vouchNum,
})```
@sick birch ^
elif str(message.channel) == "💌┃modmail" and message.content.startswith(
"$ "):
await message.add_reaction("✅")
userids = re.findall("\d{17,19}", message.content())
finaluserid = client.get_user(userids)
member_object = message.mentions[0] or finaluserid
``` What I currently have
The upper part is the on_message handler for DMs
So basically any message in a modmail channel?
Well, messages starting with $ yes
Starting with $ of course
so what do i change to fix it
And what do you expect it to contain?
Make sure VouchCount is not a list
Why not use a command for that instead and save yourself some time
And get rid of that entire on_message
remove int?
@bot.command()
async def modmail(ctx, member: discord.Member):
# stuff
Only you know. It depends on every other place where you update your database
And you need to make sure you're not dumping a list into it
what i did ?
Code?
@client.command()
async def syncofficials(ctx):
await ctx.send("Command was called")
print("Command Was Called")
print(ctx.author.id == 771252695667310623)
if ctx.role.id == 958572191681744898:
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if "™" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)
return
await ctx.send("Sorry, This Command Is Only For Server Mods")```
rip im just gonna delete this bot idea/project :(
if the role id =
Which role?
So you want to check if a role is equal to itself?
no
So on a command, if I put startswith (" ") will it require $ regardless?
Commands will only be invoked if they start with your command prefix, yes
i wannna check the user roles if he have role of the id i have wirtten then perfrom sync otherwise if he does not have the role then send sorry
You don't have to check it yourself
role = ctx.guild.get_role(...)
if role in ctx.author.roles:
# user has role
else:
# user does not have role
@sick birch my brother said to change int into list?
if role in ctx.author.roles: == 958572191681744898:
does bot.users bring up a list of all the users inside the servers the bot is in?
like this
Yes, every user the bot can "see"
okay thank you
No, that's incorrect syntax
You need to check if a discord.Role object is in ctx.author.roles
bruh
?
wait listen carefully
I know what you want to do, I've provided a solution
if role in ctx.author.roles: ??
i want that the cmd only can be executed by the server mod role and if the user is not having the mod role simply send sorry if it has the mod role then sync the officials
So just use the has_role check?
yaaa
ok
@unkempt canyon
@commands.has_any_role('Library Devs', 'Moderators', 492212595072434186)
this will work for me?
commands.has
the id
Assuming your server has all of those roles yes
what the
syntax error
help
@client.command()
@commands.has_role(...)
is how it should be formatted if i'm not wrong
print("...")
ys like
@client.command()
@commands.has_role("CoolBoy")
must type name not id
how can i check if a message is nsfw?
it should send sorry
when i don't have mods role
@client.command()
@commands.has_any_role(958572191681744898)
async def syncofficials(ctx):
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if "™" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)
return
await ctx.send("Sorry, This Command Is Only For Server Mods")```
@client.command()
@commands.has_any_role(958572191681744898)
async def syncofficials(ctx):
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if "™" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)
else:
await ctx.send("Sorry, This Command Is Only For Server Mods")```
that is probably indented very wrong
try
@commands.has_role("role name here")
ok
not id
dont put id there
still the same error
this one
send the error
change to name of the role where its id of role
its thinking that role id is role name
if i have mod role
dont put id man
hmm
when i have mod role this happens
ok try
@commands.has_permissions(kick_members=True)
@proven birch try this
but mod role are not having kick permission and i dont want to give them any perms
i only want by the role or id
its not checking for role
raise and error when the user doesnt have role
but it in the code i have said await ctx.send("Sorry, This Command Is Only For Server Mods")
it should send this
ye before that in the if statement
if user is not having the mod role
Whats the command to message a user
then you should check for user roles
it may work
yaa i want to do that
bruh
now i again need to go up and check for that code
.
here you can try
for user in ctx.guild.members:
if "role name" in user.role:
in dms?
Yeah
!d discord.User.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
ok then
@client.command()
async def dm(ctx, user:discord.Member, *, msg):
await user.send(msg)
How do i use
@client.command()
async def syncofficials(ctx):
for user in ctx.guild.members:
if "mod" in user.role:
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if ":tm:" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)
else:
await ctx.send("Sorry, This Command Is Only For Server Mods")```
client?
new to discord.py?
Yea
Me also
Member' object has no attribute 'role'
man
hi
roles
ys typing error 
And you would need a role object not a string
cuz checking role in user roles
Or you could do [role.name for role in user.roles]
Nice
works
Yes
!d discord.Member.timeout
await timeout(when, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
ys
only on master branch
wdym by master branch
https://github.com/Rapptz/discord.py is the master branch
replit installs d.py 1.7.3 by default which is the stable branch
so what should i do then
install master branch inside the shell
pip install -U git+https://github.com/Rapptz/discord.py/
Is it possible to build a bot that can fetch answer to questions from the Web, e.g Website like, Stackoverflow e.t.c?
async def timeout_user(*, user_id: int, guild_id: int, until):
headers = {"Authorization": f"Bot {bot.http.token}"}
url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
json = {'communication_disabled_until': timeout}
async with bot.session.patch(url, json=json, headers=headers) as session:
if session.status in range(200, 299):
return True
return False
@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
if handshake:
return await ctx.send(f"Successfully timed out user for {until} minutes.")
await ctx.send("Something went wrong")```
use v10 api
it there v10 api in discord
yea
# unban logs
@client.event()
async def on_member_unban(guild, user):
username = (str member.string)
userid = (str member.id)
unbanreason = (str reason)
unbanembed = discord.Embed(title=(str "User " + memberid + "unbanned"))
modlog = client.get_channel()
await modlog.send()
```Not sure what I'm doing wrong, but I definitely know that I'm doing it wrong. (guild is predefined)
- you aren't supposed to call
event get_channeltakes an id as an argumentsendtakes an arg/kwarg
So str should be in front of ( and reason is not defined and ur not sending anything
Is dis for me?
And member.string isn’t a thing
hello, need help with integrating spotify with my discord bot yo
use stackoverflow's api
?
Removed ID from get_channel by mistake
Oh Thanks
this is what i got from stackoverflow
Ur not closing the (
What would you use to define reason for it?
me?
You would have to check the audit logs
Yes
where
Oh I’m blind
And then for modlog = client.get_channel(881835799547609109) I'm getting invalid syntax
what
Nvm I saw ur code wrong
No no sorry I looked at it wrong
someone tell me what to do then
What’s the problem
Show the import
When u run it does it work
That’s not related to the code you sent
for some reason my python discord bot can't send an emoji
I've trying to get it to send
but it just won't no matter how I format it
can anyone help me?
but i unable to import discord
after install git dpy 2.0.0
# ban and unban logs
@client.event()
async def on_member_unban(guild, user):
username = str(user.username + "#" user.discriminator)
userid = str(user.id)
thereason = str(reason)
unbanembed = discord.Embed(title=(str( "User " + userid + "unbanned"))
modlog = client.get_channel(881835799547609109)
await modlog.send(embed = unbanembed)``` Alright so, I couldn't find anything in the docs for unban entries, so I assume there is a different way to add that, and I also am unsure as to what I'm doing wrong with user.discriminator (invalid syntax)
I’m not sure why. Maybe it’s a replit problem
You can do str(user) for username#1111
Thanks!
Oof, now invalid sentax on modlog =...
I searched back through this channel for get channel, and it looks like I've got it right
Prolly a missing closing bracket in the former lines
I have to be blind because I do not see anything like that
On the unbanembed you're missing a closing parenthesis
There's 3 parenthesis on the left side while theres only 2 on the right
Btw f strings exist why use concatenation in such cases
And why are you literally str'ing everything
unbanembed = discord.Embed(title=f"User {user} ({user.id}) unbanned")```
Easier and more clear
Fixed
And uh you never used username and reason
Mhm, haven't made the embed yet
Not sure how to define reason / get one from the unban
Audit logs is the only possible way ig
I saw that in the docs for ban events, but not unban events
Do unbans even support reasons
They do not, though I have seen bots that do take it from the command / application and use that
Nvm seems like they do
Interesting, so how would you define reason with that?
You can get it from iterating through audit logs and fetching the correct unban entry
The event does not send reason
Gotcha, odd
?
help me
Can you get reason from on_member_ban or is there a different way you need to do it
you technically can
fetch the ban -> use the reason property on the BanEntry object you get
I recently got a discord bot which is going to be closed soon by the developer and he gave me his github repo of source code of that bot. So now I want to use that source code in a bot made by me
So bot we can create via discord developer option. But how to add that code file with that bot ??
You need to run the bot files yourself, setup to log in using the bot token on Discord.
I have that cloned in my kali
install/clone the code -> run the bot using the bots token
but files adding for that bot how will it done??
I want it to be a bot which works itself by commanding as other bots do
like probot and all
oh
so I need to run that file myself with discord token
in my terminal
everytime I use it
Tried this and on reason.reason I'm getting invalid syntax
# ban and unban logs
@client.event
async def on_member_ban(guild, user):
username = str(user)
userid = str(user.id)
reason = guild.fetch.ban(user)
banembed = discord.Embed(title=str(username + " banned"), description=str("🔨 **User ID:** " + userid + "\n📄 **Reason:** " reason.reason))
modlog = client.get_channel(904806027025854544)
await modlog.send(embed = banembed)
Yes
Yeah look after "Reason: "`
Oh God this is going to be one of those things where I see it and feel really stupid for missing it isn't it
😅
hello guys I want to write a commands about when you type a date and then the bot ctx that date event
how can I write this
what does ctx mean?
ctx = when you type a command and the bot send some words to u in the channel
yes?! I am not sure
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
what
what do you mean "ctx" that date?
so you want to reply like that if there's a birthday at that time?
yes!
only birthdays?
Em I guess I will add some important day
Is this things hard? i guess yes
Well no
its just a nickname u can change it to cat or anything
and u can do like
await cat.send(oof)
I'm asking what he means by that cause that doesn't make sense
HAVE some Material?
you can use the datetime module to convert it into a date
!e ```py
from datetime import datetime
quack = datetime.strptime("30/8/2022", "%d/%m/%Y")
print(quack)
@supple thorn :white_check_mark: Your eval job has completed with return code 0.
2022-08-30 00:00:00
ok
@start.error
async def on_start_error(ctx, error):
embed = discord.Embed(
title="Timed Out!",
description="You Have Taken Too Long To Reply. Closing This Session.",
color=0xFF5733,
)
if isinstance(error, asyncio.TimeoutError):
await ctx.channel.send(embed=embed)
this embed wont send even when the error occurs
i bascially have a command called start which waits for a reaction on a message
you have 60 seconds to react or it returns an asyncio.TimeoutError
but
the message doesnt send
First of all the context is an object which refers to a message (or an interaction in case of slash commands) so the context has a send and reply object builtin, there is no need to use ctx.channel to send a message. Now let's come to your issue. wait for raises TimeoutError, but TimeoutError is not an object of discord.py so most you are trying to call a command error but it is raised by something else. So you should check the timeout error directly in your code and not in an error handler:
num = input("add a number")
try:
result = int(num)**2
except TypeError as e:
print(e)
hi
Okay
?
??
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello there!')
client.run(os.getenv("token"))****
can someone tell whats wrong with this code? its not running
they're talking about ctx.send
Not running?
At all?
like i'm getting errors(a lot)
Yeah i know but they shouldn't say "ctx" when referring to that
how would we know what's wrong without the errors..??
we can send ss in this channel?
Yes
yeah exactly 💀
There's no token
getenv is returning none
just read the error
it shows that token.strip doesn't work because it's None, and look where you're passing in the token
Must mean that whatever ur passing in is none
Also u can use actual commands instead of checking every message like that
Comes with arg parsing and a lot more
If you need commands, use the commands extension.
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
Why should I use the commands extension?
- Prevents spaghetti code
- Better performance
- Easy handling and processing of command arguments
- Argument type converters
- Easy sub commands
- Command cooldowns
- Built-in help function
- Easy prefix management
- Command checks, for controlling when they're to be invoked
- Ability to add command modules via extensions/cogs
- Still able to do everything you can do with Client
taken from discord.py server
okayyyy ty
class gif_cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.every_10_min.start()
why does the self.every_10_min.start() have to be awaited?
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
In the documentation it should work like that:
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.data = []
self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
self.batch_update.start()
def cog_unload(self):
self.batch_update.cancel()
@tasks.loop(minutes=5.0)
async def batch_update(self):
async with self.bot.pool.acquire() as con:
Uh
You need to add
@batch_update.befote_loop
async def loop_waiter_or_something(self):
await self.bot.wait_until_ready()```
Loop can't be executed until bot is ready
I mean it can be but shouldn't
Imagine coding discord bots
But that shouldn't really error out, since the cogs are loaded only when the bot is starting and there is a loop
nah that wasnt the problem
but it doesnt matter now tbh i removed it since i dont actually needed that loop
@bot.event
async def on_message_edit(before , after , message):
if message.author == bot.user:
return
else:
em = discord.Embed(title = f"{before.author} edited a message", color = discord.Color.random())
em.add_field(name = "Before",value = before.content )
em.add_field(name = "After",value = after.content, )
await after.channel.send(embed=em)```
why this not work
Traceback (most recent call last):
File "C:\Users\JOYED\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_message_edit() missing 1 required positional argument: 'message'
``` the error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
dms closed
How do I skip this error?
You're missing a argument
How do I skip the error if DM is closed?
which
wait i have the code for it a sec
Is there a way for me to accept command like .com p1 p1 p1 something else p2 p2 p2 (spaces between p2 should connect it into one variable same goes for p1)
apart from accepting entire command as one string
@bot.event
async def on_member_remove(member,after):
leave_channel = bot.get_channel(954347624612393001)
modchannel = bot.get_channel(933966074955833445)
em = discord.Embed(title = f"Goodbye Message" , color = discord.Color.gold())
em.add_field(name = "Bye", value = "{member.mention} has left the server :sob:", inline=False)
await after.channel.send(embed=em)
try:
await member.send(f"Hey {member.display_name}! goodbye")
except:
await modchannel.send(f"{member.mention} I can't dm you, but goodbye")``` @slate swan
try except
thank you very much
!d discord.on_message_edit
discord.on_message_edit(before, after)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") receives an update event. If the message is not found in the internal message cache, then these events 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_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_edit "discord.on_raw_message_edit") event instead.
The following non-exhaustive cases trigger this event...
thanks bro
np
Mans got spoonfed
nope
its a different cmd
i dont think he'll need that command
You still literally gave him the code
.
.
error
Jorden do you know bot call for command formating
There's is no message argument for on_message_edit
It's only before and after
What
HI
@bot.event
async def on_message_edit(before , after , self):
if before.author == self:
return
else:
em = discord.Embed(title = f"{before.author} edited a message", color = discord.Color.random())
em.add_field(name = "Before",value = before.content )
em.add_field(name = "After",value = after.content, )
await after.channel.send(embed=em) ``` @supple thorn this?

No
damn
I wonder what you learned the past 2 years
😑
I want to get 2 parameters from command with multiple spaces ie. .pizza spicy and crusty (and then another) ingredient1 ingredient2
Since it doesn't look like you use cogs you don't need self
It's only just before and after
and well some params in between
leave it ill check my old codes
does " " format command as single parameter
???
is this the thing i need to do
So?
should i open my vsc now?
Yes
Why are you asking us if you should open vsc?
then sleeeeeep
Do you mean
.pizza "pepperoni" "pineapple" "cheese"
Like that?
when you read comamnd in bot it's like ctx param1 param2 param3 right, I want that param1 and param2 accept multiple words
pineapple in pizza?
Yeah you can just add quotes to it
in my bot he'd be blacklisted 😄
🍍 + 🍕 = 💥
Sadge
Ah great, thanks 🙂
well i couldn't blacklist you since you helped me
.pizza cokecane
Would just be .pizza "alot of pineapple" "sauce and cheese"
sparky have u ever tried it?
so happy discord devs thought about this couse i hate formating 😄
pineapple on pizza
never
I haven't
do u ever eat coal?
is it edible
I can eat it without puking but i won't enjoy it
how u tried ice cream soup?
Yes
cringe
I have eaten melted ice cream
not bad tho x)
i mean 🍨 + 🍵
I still prefer the cold version
how do I delete all discord messages sent by bot
so like the idea is the bot deletes every messages it ever sent in DMs or servers
!d discord.ctx.send()
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
how can i send this to a specific channel using the channel = bot.get_channel() ? I'm using the modal feature
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(color=discord.Color.blurple(), description=self.children[0].value)
await interaction.response.send_message(embeds=[embed])
by bot*
There's a check kwarg
Yeah
he mean delete_after ?
Do you want to delete every message by the bot all at the same time?
Or when it sends a message it deletes it after
ok im opening vsc now
If it's this
all at the same time
some sort of self destruction
Use this then
.
With the check kwarg
You can only delete 100 at a time though
that's good enough for now
@bot.listen("on_message")
async def on_message(message):
embeds = message.embeds
if len(embeds) != 1:
return
embed = embeds[0]
emb_dict = embed.to_dict()
if message.author.bot:
if emb_dict["title"] == "No new tasks.":
Success = False
elif emb_dict["title"] == "Task detected!":
Success = True
else:
return
channel = bot.get_channel(937661345531330590)
if Success is False:
delay = emb_dict["fields"][1]["value"]
type = emb_dict["fields"][0]["value"]
await channel.send(f"Got a task in {delay}, task is {type}")
elif Success is True:
delay = emb_dict["fields"][1]["value"]
type = emb_dict["fields"][0]["value"]
if type == "Shopping" or type == "Brushing teeth":
await channel.send(f" Got a shopping or toothbrushing task!")
elif type == "Showering" or type == "Carwashing!":
await channel.send(f"Got a carwashing or showering task!")
aboutuschnl = bot.get_channel(937742734339485766)
mesg = await aboutuschnl.fetch_message(956227850191659018)
claims = mesg.content.split("`")[1]
aboutmemsg = f"**We've got a total of `{int(claims) + 1}` Tasks, have fun in the server!"
await mesg.edit(content=aboutmemsg)```
When success is True, it doesn't send a message to the channel and gives me this error.
local variable 'msg' referenced before assignment
msg?
Closest variable i can find is mesg
You are right that code is not the code I had when I had that error
I tried fixing it somehow but it still didn't work
What was the old code?
Also did you save the new changes before running it?
Yes I did that yesterday and lost access to old code
but there's no error now which I find weird as it doesn't send a message
I am currently trying to send a webhook which should give me some error
What are you trying to trigger?
It'll only send a message to the channel if it triggers one of the if statements
elif Success is True:
delay = emb_dict["fields"][1]["value"]
type = emb_dict["fields"][0]["value"]
if type == "Shopping" or type == "Brushing teeth":
await channel.send(f" Got a shopping or toothbrushing task!")
elif type == "Showering" or type == "Carwashing!":
await channel.send(f"Got a carwashing or showering task!")
aboutuschnl = bot.get_channel(937742734339485766)
mesg = await aboutuschnl.fetch_message(956227850191659018)
claims = mesg.content.split("`")[1]
aboutmemsg = f"**We've got a total of `{int(claims) + 1}` Tasks, have fun in the server!"
await mesg.edit(content=aboutmemsg)```
this code
Yeah but are you trying to trigger one of the if statements within that code?
Because if you aren't it won't send a message
It'll only edit a message
Uh yeah so basically a webhook is sent with as title
Task detected!
and when that happens it should send a message to the channel
yes that is the problem
So you are trying to trigger one of the if statements?
what do you mean with type
And tell me what it says
Your type variable
Success.type() ?
It's different from what you thought it was
The type variable was not
Brushing teeth
but it was
Brushing teeth
Something I should've thought of from the beginning 😢
Thanks a lot!
is there a way to change items in a view?
self.bot.add_view(view=RowButtons(self.bot))
this not working
i restart the bot
but button not working
!d discord.ext.commands.Bot.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
@slate swan are you familiar with the tictactoe from discord py git
see the arguments
Is it at all possible to use the API to search how many times a specific word has been said? I.e. $search (word) - Word has been said 17 times
Going all the way back to the beginning of the server*
idts but i could try, whats the issue?
basically im trying to implement a way of playing against a bot
just simple random thinking no logic
the only thing i have a problem with is accessing the buttons through the view
just simply changing some button things as style, name etc...
welp no idea
ok
I'm too bad with views smh
i have added view but
You do know python though right?

ofc no
I mean know python as in being a pro in python
doubtful
xD
ok can anyone help
:<
you didnt even ask the question
you need to edit/send the view
hm?
and is self.bot even valid
plus you are not mentioning a message id
class RowButtons(disnake.ui.View):
def __init__(self , bot: commands.Bot):
self.bot = bot
super().__init__(timeout=None)
@disnake.ui.button(label="Create ticket", style=ButtonStyle.blurple)
async def first_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
ah i see
what is that
^
idk why you made it that complicated
Yeah but if hes complaining of not seeing them then thats the issue
edit the view after adding new components
see up
ctx.send(view=RowButtons)
oh idk that
no guys
adding the view is supposed to make it persistent
so it works after restarting
so youve sent the view and stuff works, and then restart and nothing works
yup
Ah ok now i get it
tell?
relax i meant i get what the problem is
ok whats the problem?
no i get what your problem is
bruh
do you get an error?
no
im not great at 2.0 stuff but heres dannys example for persistence https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
im using disnake
ive never even heard of that
already seen
ur probably better off asking in their server
bruh
its official?
when you realise pycord is not the only fork
😑
nextcord and pycord are the only ones ive seen
only
only
There are far better forks existing
anyways its on their github
ok im shifting to discord 2.0
enhanced dpy & Disnake as an instance
lemee change my code
pls give discord2.0.py github?
https://discord.gg/gJDbCw8aQy link from their github
and then ill ask
like this
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py
you need this for 2.0, otherwise pip will install 1.7.3 from
yeah if you use 2.0
oop-
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
i tested it today and it didnt work
got it
lol
i forgot to remove it
i added that it in main file
and today i open and i continue with that i didnt see the main
nvmd
name changed hmm
i have done
that u said
first py
discordpy is quite advanced so make sure you you're comfortable with py first
It's always a bad idea to jump into a library without knowing the language from personal experience it has never went well
Completed my bot 👌 thanks for all the help y'all gave 👌💀
I totally didn't do that
💀
f string
add an f before the string
Not supported the last time I checked iirc
Danny said he would add that but who knows when
Yea
You can make application commands in cogs
anyone familiar with slash commands?
You use the app_commands.command decorator within the cog and it will automatically get added to the bot's tree once you add the cog
You have to import it
what?
Seems like you are trying to access a ui attribute on discord. Can I see your imports? It should work if discord is imported
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT PRIMARY KEY NOT NULL, warns INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
print(name)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ?", (member.id,)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if reason is None:
try:
cursor.execute('INSERT INTO warning(guild_id, user_id, warns, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
except Exception as e:
print(repr(e))
print(2222)
cursor.execute(f'UPDATE warning SET warns = {warnings[2] + 1} WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение # {member} (случай # )")
else:
cursor.execute('INSERT INTO warning (guild_id, user_id, warns, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1, ctx.author.id, reason))
base.commit()
cursor.execute(f'UPDATE warning SET warns = {warnings[2] + 1} WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение # {member}, причина {reason}. (случай # )")
error: OperationalError: no such column: user_id
error is clear
There's no column user_id
i have a note main command where the user where the slash command is note create [name] [content].
Once it's made it is put into a database, and a user can only make notes for himself.
I want a show subcommand where the user can view one of his notes. The arguments would be /note show [note name] and I want to know whether its possible to make it so that when the user just types /note show and is on the argument of note name all his available notes appear in the list
it is clear that it is clear, but how to fix it?
you realize that execute can be replaced with fetchone afaik
what’s this reaction menu thing
buttons
discord.ui.Button should be working
pip install discord.ui.Button
no. It’s included with dpy iirc
@slim ibexcan u come vc?
no unfortunately
@slim ibex familiar with slash commands?
In disnake a little bit
what's Tools
that's not a little bit of help
can you help with this?
what is Tools
You can fetch all notes of a user where the ID corresponds in the db corresponds to their discord id
It also seems like you might want a slash command group
ah yeah you said you want a sub command 👍
but how do I get the user ID though is the question
I am trying to make a code to change a float into an integer but when i typed !number 9.2 it didn't say anything.
@client.command()
async def number(ctx, amount: int):
await ctx.send((int(amount)))```This is my code
don't typehint to int if you're putting a float.
then it'll only accept int as the amount
just do ```py
@client.command()
async def number(ctx, amount: float):
await ctx.send(int(amount))
SQL looks so messy
fr
SELECT notes_col FROM table_name WHERE id_col = ? and where the placeholder is member.id or whatever
you might have to do separate queries to get specific parts of the note, if you have that
no i mean how do i get access to the user id before he sends the interaction
is it even possible? I'm not sure
you should use the thing come with discord.py instead of a 3rd lib
idk tbh
wdym?
there is already button implement in dpy, why are you using a 3rd party lib
but what can i do
install it
what?
install discord.ext.buttons
cmd
idk
brah
everything i can say is install discord.ext.buttons
umm okay
Like autocomplete?
yes
you need master
yes
dpy 2.0
master lol
join discord.gg/dpy and view #guild-news to see how to install 2.0
2.0 is still in beta
git clone
^
basically dpy 2.0 is installed using git
It's been in beta over 8 months now
how to do gitclone?
More ducks are appearing
A discord.py extension for sending, receiving and handling ui interactions in discord - GitHub - discord-py-ui/discord-ui: A discord.py extension for sending, receiving and handling ui interactions...
by this iirc
pip install git+https://github.com/Rapptz/discord.py
i just use disnake i mostly like its impl better than dpys
@jade garden
install git
just google "how to install git on windows"
also are you new to coding?
id recommend learning some basic python before coding a discord bot
Well, if you're using SQL get all of the columns that match the users ID, and then add autocomplete to the slash command I guess
moai I got a warning for this
Wat
yes
and not very python related either
rip
don't take it word to word...
it was autocorrect
why don't you capitalize Kayle's name

cause isnt honorable 
mina 👀
!mute 920688804082352198 to follow up your warning and the clarification we gave in modmail by bringing attention again to your very inappropriate message is not the behavior we expect on this server
:incoming_envelope: :ok_hand: applied mute to @cold sonnet until <t:1648647004:f> (59 minutes and 59 seconds).
o
.topic
Suggest more topics here!
Sorry 🙏
@cold sonnet mute was intended to be 6 hours, and has been extended.
make it easy to get both global and server pfp urls >:
I still didn't try whatever resource you guys pointed me to the other day
you referring to Member.display_avatar ?
That can return an asset for either or.
!d discord.Member.display_avatar
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
yeah, if a user has a different global and server pfp, i'd like a way to get both
property guild_avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the guild avatar the member has. If unavailable, `None` is returned.
New in version 2.0.
Voice receiving
And you can just use Member.avatar for global
Bork’s fork has an experimental implementation of that.
imayhaveborkedit?
Hi
Yea
I see
Hello
👋
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
ah discord.Member.bot == True
Yes, or what tyler said



