#discord-bots
1 messages · Page 465 of 1
No one even mentioned it
"Dont giveaway code." "it is infact a big deal"
can i use the key half of a dictionary in a simialr manner to a list?
im not, i said what happened lol
He just told you no
i asked if someone has a script for blacklisted words and i got a lecture
If you spoonfeed others they won't learn how to do the thing they got spoonfeeded. That's what we're tryna tell you here
I'll just go back to sleep
because he said "dont give free code" and i asked why and then i got chewed out for no reason
i already know how to do it, i already said im just to lazy
hello
No one chewed you out
Hi
whats happening here
this was my first resource and now im just gonna do it myself its not that big of a deal
please drop it already dude
Point out one message where it did actually happene
!shh
✅ silenced current channel for 4 minute(s).
✅ unsilenced current channel.
thank you
what happened?
preciate it, now if anybody needs help just lmk :)
it dont matter
can a dictionaries keys be used in a similar manner to a list?
whats ur code?
send it
k
spoonfeeding happened
ohh
#Kicks/Bans everybody who has an account less than 1 day old or who has joined within 24 hours.
@client.command()
@commands.has_role('bot')
async def raid(ctx):
memberslist = []
if ctx.channel.name == 'botstuff':
for i in client.guilds:
for member in i.members:
if member.id != 832106800580001813:
joineddate = datetime.now() - member.joined_at
createddate = datetime.now() - member.created_at
if joineddate.days <= 1 or createddate.days <= 1:
mymembers = {
'Member name:': member,
'Member id:': member.id,
'Member roles:': member.roles,
'Created:': member.created_at,
'Joined:': member.joined_at
}
memberslist.append(mymembers)
await member.send('Kicked due to anti-raid procedures. If you believe this is in error, feel free to contact our staff. <List of staff goes here> \n\n as this is just a test, you are not banned. The live version will ban you.')
await member.kick()
await ctx.send('I have compiled a list of members who were kicked. Please note this list is only sent to help verify everybody who should have been kicked. \nI only check for accounts created or joined within the last 24 hours.')
memberslist_string = 'tickticktick\n'
for i in memberslist:
for a,b in i.items():
memberslist_string += (f'{a} : {b} \n')
memberslist_string += ('\n')
memberslist_string += 'tickticktick'
await ctx.send(memberslist_string)
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
maybe on a website bin if its big
for the purpose of tracking a set of channels to process in a special manner, and also check what channel gets procesed how
no spoonfeeding happened but a lot of people were whining about spoonfeeding happening
@crude crater
NOW MOVING ON
yes
this
You know
whats ur error?
No error. just review
I'm honestly surprised that a silence didn't stop you guys
lol
Take a deep breath or smth
im not it was like 4 minutes
oh my lord leave it already dude 🤦♂️
Focus damnit!
@crude crater do you think i've missed anything? Can you spot anyways this could go wrong?
a channel purge and maybe some animal/pet pics would possibly work for a channel topic reset method
im still looking
Ty ty
So when a server gets raided, instead of sshing all channels, just purge everybody with an account <1 day old or joined <1 day ago
oh for anti raid? thats sick!
and the message is in case some innocent pleb gets caught in the kick/ban wave
okay lemme look
I'm happy to take suggestions on how to improve it if you can provide.
At the moment, the code works so far.. 'as intended'
now personally i wouldnt do for people who JOINED in last 24h
but for accounts that were made in 24h
as in the 20 people I tried it on, it worked as intended.
imo
id suggest a link to like a google forms or smthn rather than listing staff as if they hadnt contacted any staff yet it might be difficult
I chose 'joined' because sometimes the accounts are older than 24hrs but have just joined
maybe accounts joined in the last hour get a ban and accounts newer than 24 hours get a temp ban?
Well was going to just output the staffs tags like Gnomeslayer#5551 for example and they can add and speak to them.
which is great until a staff member changes their name or gets nitro
If I stick to kick. I could just also send them a new invite?
exactly
Since most of those 'spam accounts' are just bots and wont have their pms checked anyway
i think a temp ban of some sort would be ideal as it would prevent people from spam joining?
i think its great!
tempban 15s?
i would just get the staff role and search for members with the role and give the person the members
nah like tempban 1 day
i wouldnt do 1 day. I'd do maybe 5 minutes
well if you're trying to prevent spam joining 15s is good i think
yeah 5 minutes is good too
ah true using f"staff members are {rolething.user}"
So changes:
1 - change kick to tempban 5 minutes
2 - Send a new invite link.
yeah
that works
oh even better actually, add an optional specification for how many minutes to tempban for, otherwise default to 5
Now how the bot handle if the output..
memberslist_string = 'tickticktick\n'
for i in memberslist:
for a,b in i.items():
memberslist_string += (f'{a} : {b} \n')
memberslist_string += ('\n')
memberslist_string += 'tickticktick'
await ctx.send(memberslist_string)
Is longer than what discord allows? will it just send a txt file?
how many moderators we talking?
whats the " if ctx.channel.name == 'botstuff':" for?
that's just me limiting the bot to a specific channel in the discord i have it in
Just in general
I'm still testing it. and the output can be quite large
true
That was before I added the exception for the bot.
That output will be longer in a raid tho. So I am concerned that it may not send it if it's above the discord character limit
itll be fine
Will it send it as a txt file? 🤔
you could edit the code to do that
but unless its banning id say like 50+ people itll be fine
fwiw we don't allow paid services of any kind. If you're going to help here, you do it for free
The idea before the message being sent is so you as the admin can be like 'oh damn. I accidentally banned half the new staff members I invited today.'
Cool cool. Thought I'd ask ;D
you can always feel free to DM me if you're up for it too long
because they're pretty strict in this discord a lot of times lol
protip, just use
@client.command()
@commands.is_owner()
and it will only work if you send it
but its for staff
I want to be able to add roles as well. For example, staff members (mods or admins)
and mods not the owner
for testing i men
Owner is just the name of the role I had at the time xD
Oh. thanks then. I will use that.
it to me seems celaner than checking if its in a private testing channel
and is also useful for stuff like emergency reset commands and bot shutoff commands
I wouldn't suppose the invite thing wouldn't be as simple as member.invite would it? xD
Response Recorded as: [<Attachment id=886489123668508722 filename='boombtw.png' url='https://cdn.discordapp.com/attachments/886314980746625085/886489123668508722/boombtw.png'>]
i dont believe so lmfaoo
OH WAIT
step one: get a permanent invite link for your server
step two: use that as plain text in the message
i am getting this response on image.attachments
you could just attach a permanent invite to the message
how do i get the url
I was hoping to do it with plain code XD
because theres no way a raid bot is that advanced to click on a link
i didnt even see this my bad XD
webscraping
await create_invite perhaps?
Looking into that now @glacial echo ty
alright tahts enough helping for now imma work on my thing
cya
but yes i agree with Katte, it might not be that specific line obviously but to create a new invite is a perfect idea
how to get guild id from bot object
because thats not how you do something to send to a channel
its
await ctx.send
you do it in brackets
await ctx.send("@hollow iron Bruh, did " + '<@' + {ctx.author.id} + '>' + " really just try that? Don't worry, he's banned lol!")
'<@' + {ctx.author.id} + '>' -- {ctx.author.mention} is a thing
And it needs to all be one f-string
e.gpy f"@hollow iron did {ctx.author.mention} really just try that?"
i was about to say that too
whats the use of passing bot to callable when making a dynamic command prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.
def what_prefix(bot , message : commands.MessageConverter):
db = get_database()
collection = db["prefixes"]
guild_id = message.guild.id
result = collection.find_one({"_id": guild_id})
if result is None:
return "$"
else:
return result["prefix"]
callable just means a function in this case
is somethig wrong
hhmm.
await message.channel.send(f"@hollow iron Bruh, did <@{message.author.id}> really just try that? Don't worry, he's banned lol!")
try this
what do i do with the first parameter "bot"
- Please don't just dump code
- Especially when it's incorrect
is it incorrect?
message.author.id
It's in a command so ctx.author.id and you shouldn't even be doing that anyway
Just use ctx.author.mention as I said to them above
i dunno man i just took the code they had posted and offered a way to troubleshoot the problem they said?
but my apologies
What happens if I invite people to a channel they dont have permissions to view?
do they just get sent to the nearest public channel?
Why not use fstrings @hollow iron ?
cool
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@client.command(aliases=["SERVERINFO", "Serverinfo", "Serverinformation", "SERVERINFORMATION", "serverinformation"])
async def serverinfo(ctx):
embed = Embed(title="Server information",
colour=ctx.guild.owner.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=ctx.guild.icon_url)
fields = [("ID", ctx.guild.id, True),
("Owner", ctx.guild.owner, True),
("Region", ctx.guild.region, True),
("Created at", ctx.guild.created_at.strftime("%m/%d/%Y %H:%M:%S"), True),
("Members", len(ctx.guild.members), True),
("Humans", len(list(filter(lambda m: not m.bot, ctx.guild.members))), True),
("Bots", len(list(filter(lambda m: m.bot, ctx.guild.members))), True),
("Text channels", len(ctx.guild.text_channels), True),
("Voice channels", len(ctx.guild.voice_channels), True),
("Categories", len(ctx.guild.categories), True),
("Roles", len(ctx.guild.roles), True),
("\u200b", "\u200b", True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed=embed)
the command shows up when i do "!help" but it doesnt do ANYTHING
!fstring
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
like i type the command and then nothing happens
ctx.author
well what are you trying to do?
Yea
yes but on what event?
But that will ban the person who invoked a command
It depends on the platform the user is using but they won't be able to view the private channel
yes exactly
Imagine doing
async def on_message(message):
await message.author.ban()
ctx.author.ban*
I just want to send a generic invite to people who I have kicked using my bot. I can't figure out how to do a 'guild invite' and all i find on google creates a invite to a specific channel or voice.
So I am concerned it won't work or something will go wrong if they dont have permission to view the private channel
.....?
try this in your code, it should help reduce the number of aliases you need to write
client = commands.Bot(command_prefix="!", case_insensitive=True)
It won't go wrong. The invite will still work, even if it's to a private channel
the important bit being the case insensitive thing
THANK YOU!!!! <33333
Who cares. It's optional
.ban(reason="reason")```
whats the thing that lets commands still work even if i have an on_message() event?
await bot.process_commands(message)```in your `on_message`
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
m = str(data['data']['attributes'])
print(m)
else:
print("Not wkrng")
error:```
m = str(data['data']['attributes'])
TypeError: list indices must be integers or slices, not str
data['data'] is probs a list
That or data is a list
Try printing data and see what the output is
@commands.has_role('bot', 'Bot', 'Owner')
This doesn't work. would I instead pass a list?
@commands.has_role(['bot','Bot','Owner'])
or would I just need to write that line multiple times?
it is smt like this
[<Attachment id=886489123668508722 filename='boombtw.png' url='https://cdn.discordapp.com/attachments/886314980746625085/886489123668508722/boombtw.png'>]
how do i seperate url from this
yes
It's a list, so you'd want to loop over it presumably
so how can i fix this? ```error
m = str(data['data']['attributes'])
TypeError: list indices must be integers or slices, not str
yes
for whatever_you_want_to_call_it in data["data"}:
print(whatever_you_want_to_call_it["attributes"])```
How would I update my dpy version?
pip install --upgrade discord.py to get the latest stable release
ah
how to send image in an embed message..
thank you
okh ty
embed.set_image(url = )
newVar = thatTextVariable.split(url=) might work?
resolved my past issue. it's actually "has_any_role" 😮
i wanna send smth thats in directory
umm use the pil lib?
anyone?
pillow lib
except MemberNotFound:
ctx.send("member not found")
gives me SyntaxError: invalid syntax, how come?
python
image manipulation
lib
pil
await ctx.send
message or msg
yeah forgot that, but still gives me SyntaxError: invalid syntax
depends on what you put
full error?
send code and your traceback
except MemberNotFound:
^
SyntaxError: invalid syntax
@bot.command()
async def strike(ctx, member: discord.Member = None, *, reason=None):
except MemberNotFound:
await ctx.send("member not found")
role = discord.utils.get(ctx.guild.roles, name="striker")
if not role in ctx.author.roles:
embed1 = discord.Embed(description='You do not have the role "striker".',
colour=0xff0000)
await ctx.send(embed=embed1)
return
if member is None:
embed1 = discord.Embed(description="The provided member could not be found or you forgot to provide one.",
colour=0xff0000)
await ctx.send(embed=embed1)
return
if reason is None:
embed1 = discord.Embed(description="Please provide a reason for striking this person.",
colour=0xff0000)
await ctx.send(embed=embed1)
return
embed1 = discord.Embed(description=f"{member.mention} has been succesfully striked!",
colour=0x00ff00)
await ctx.send(embed=embed1)``` full code
🤦♂️
:/
embed.add_field(name='', value=discord.File(fp='', filename="")) ```
this kinda works but returns
How can I resolve this issue:
split your message
So basically the string is over 4000 characters. How do I make it send as a txt file?
You can't add files to embeds
idk never messed with it
Simple if
someone?
uh .. how should i do it thn
Or just paginate the embed
:/
You attach files to the message, not the embed
check if the string is over 4000 lines and if it is send it as a file
await ctx.send(embed=embed, file=discord.File(...)```
read above
If you're wanting to add an image you'd generally do embed.set_image
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
but the image is in directory... no url
..
tizzy help me :3
You can do url="file://full/path/to/file.png"
Does it work in 2.0?
Some people say it doesn't work
uh ok i try
@hollow iron
await msg.edit("finito")```
why this code doens't work?
You're doing str(guild) instead of str(guild.id) from the looks of it.
str(guild) gives the name, not the id
try ```py
msg = await ctx.send("Comando in corso...")
await msg.edit(content = "finito")
You have to specify which part of the message you're changing (in this case the content)
So you want this @floral jacinth
editing a mention doesnt work
nvm then lol
thanks now it works
so what to do 
umm
breh several people
Thanks bro
Try attachment:// @frosty prairie
use BytesIO?
As I said, I don't think that works in 2.0, @bitter depot
file = discord.File("output.png")
e = discord.Embed(...)
e.set_image(url="attachment://output.png")
await ctx.send(embed=e, file=file)```I found this online, worth trying ig
when trying that, it gives mysql error -_-
but if i remove that.. mysql error doesnt come up wth 
can i put all my commands in one @client.command() or does each thing need its own?
Since my bot is in multiple discords. How do I limit my commands to only check the current discord the command was run in and not every discord?
which code?
the raid thing?
yeah lol
Each one needs its own
I just realized it was checking the 2 discords it was in coz I removed some of the parameters
@bot.command()
async def ping(...):
...
@bot.command()
async def wave(...):
...
...```
i mean you should only need to cross reference the guild of the message with teh guild of the user right?
Well I want to only run the command in the discord it was run in.
So say my bot is it this discord and say.. fortnite discord.
I dont want to ban everybody in fortnite because I ran the command here.
And vice versa
Just remove the else section? Or give the else section some things to check. Like maybe message age or the last time it sent a "No giveaways going on in this channel"?
okay
if message.author.id in client.players[0]:
TypeError: argument of type 'int' is not iterable
what does iterable mean?
iterable basically means you can loop (iterate) over it
And you can't loop over an integer, which is what client.players[0] is
oh shoot thanks
Presumably you want
if message.author.id in client.players (is a player)
or if message.author.id == client.players[0] (is the first player)
geesh
mhm
hhmm i dont think I've missed anything yet
uk how to embed and image while is in ur directory and is not a url
So you want a discord bot to send images?
inside a embed
what do you mean as embed?
@client.command()
async def joinGame(ctx):
await ctx.message.delete()
if ctx.author.id in client.players:
await ctx.send(f'{ctx.author}, you are already in the game, no need to join twice.')
else:
await ctx.send(f'<@{ctx.author.id}> has joined the round!')
client.players += [ctx.author.id]
print(client.players)
@client.event
async def on_message(message):
if message.content.startswith("b|") == False:
try:
if message.channel.id in list(client.channelGame.keys()):
if message.author.id == client.players[0]:
return
except IndexError:
print("Index out of range, probably empty still")
await client.process_commands(message)
client.run(token)
running this, then typing b|joinGame always prints out the users username, even though no such print statement exists? unless im blind that is
i just cant seem to send a image inside a embed
I found a code online... and got this when I ran it:
Is this not what you want?
its not embedded ..
i want smth like this
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
@frosty prairie
but .. the thing is inside my directory and isnt url
OH he wants it inside the three code ticks
You wanna send images in an embed from your directory?
Whats that
yee
my text
myimage goes here
more text
or maybe however this is sent
# Rewrite
file = discord.File("filename.png") # an image in the same folder as the main bot file
embed = discord.Embed() # any kwargs you want here
embed.set_image(url="attachment://filename.png")
# filename and extension have to match (ex. "thisname.jpg" has to be "attachment://thisname.jpg")
await ctx.send(embed=embed, file=file)
``` this will help ^^
how to change nickname of bot using bot obj
No?
wish it would..
Get the channel ID you wanna send the message in then send it
Put the image in the same folder as your bot's main.py file
file = discord.File("monkey.png")
embed = discord.Embed(title='Monkey')
embed.set_image(url="attachment://monke.png")
await ctx.send(embed=embed, file=file)
``` like this
i cant keep the whole file path and diff directory?
Uh just put the image you wanna send in the folder ur bot file is in
Get the channel ID
Show your full code?
Show me your code
Alright I managed to add the image. now to figure out how to attach text to it xD
Kwargs?
channel = client.get_channel('channelid')
await channel.send('hello')
yes this
um
Also since 1.0 channel IDs are ints :)
idk what u sayin, i just stackoverflow-ed
Don't copy code
..
Most the dpy code on SO won't work
Or at least a lot of it
no images ..
hm just use imgur then ig
no errors either
Show code
imgur?
@client.command()
@commands.is_owner()
async def sendimage(ctx):
# Rewrite
file = discord.File("cow.png") # an image in the same folder as the main bot file
embed = discord.Embed() # any kwargs you want here
embed.add_field(name="text1", value="Hello World", inline="False")
embed.set_image(url="attachment://cow.png")
embed.set_thumbnail(url="attachment://cow.png")
embed.add_field(name="text2", value="Hello World", inline="False")
# filename and extension have to match (ex. "thisname.jpg" has to be "attachment://thisname.jpg")
await ctx.send(embed=embed,file=file)
How do I get the image above the second text field? 🤔
You cant
So images are always at the end?
yes
damn
i think?
@drifting arrow this shows the possible positions for images #discord-bots message
avatar, icon, image and thumbnail can all take an image
i sent code..
maybe try defining file somewhere else in the code?
Read this @drifting arrow
point still stands you cant customize images
I did. Thank you. all images always end up at the end (or in those specific spots). Which is annoying since I was hoping to do like:
[paragraph of text]
<image>
[paragraph of text]
<image>
That's without any kwargs I think?
how do i make hangman
You make it
yeah but how
You learn
now it gives file doesnt exist -_-
yeah but how
..
how learn
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
@dawn gale This is not the discord channel for you. Perhaps ask in #python-discussion
see top left there is the line in the same directory ..
im doing it for a discord.py bot
so i think it is
i said same folder
idk hto im new to server
yea there is 1 file in the same folder.. i used the same file in code
add full path
Sorry I haven't been keeping track of your current issue. What's wrong now? is it just finding the image in your directories?
how do i take input from the discord server in discord.py
Yeah but your folder is like this
Folder:
Folder:
bot.py
Folder:
image.png
he said not to just now :/
where did I say that
Is your code right?
why are so many people called !
.
No?
¯_(ツ)_/¯
Folder:
bot.py
image1.png(being used in the code
Folder:
image.png(not being used in the code)```
its like dis..
Never mind. One way is to put the file path
i wanna send a image which is in the file in an embedded form
if message.channel.id in list(client.channelGame.keys()) and channelGame.get(message.channel.id) == 1:
i ahve the following statement, but im getting a red line under the second portion of the statement, but somethign is bugging out and i cant properly hover over any of the text in that portion to see any error messages
what might be wrong with it
There's nothing blaringly wrong with that if statement
Although you don't need to convert the .keys() into a list just for an in check
ah
ohhh its me once again being stupid and forgetting that my variables are all client.variable
cause i was having weird problem where i couldnt write to a variable and use it elsewhere in teh code
that's how scope works
variables defined inside a function don't exist outside of them
So yeah, you have to use a bot-attr
!tag bot
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
There we go lol
Also please change your definition to bot = commands.Bot and not client = commands.Bot
The latter is such bad practice
So, has there been any new maintained library with slash commands yet?
client = commands.Bot is like doing my_integer = "some string", it's just completely misleading @glacial echo
If you're using a decent IDE it should have a refactor option that allows you to change all instances of the variable at once
Rofl
Don't use repl.it for discord bots
You're just going to get random ratelimits
Everyone who hosts bots on repl.it basically shares the same IP, and so not only do you get ratelimits from your code, but also from everyone else who's hosting a bot at that time @glacial echo
oh fr?
yeah lol
i did not know that at all
I mean it's not quite everyone on the same IP but the IPs are shared between multiple people
i havent had any issues with it but ill switch over i guess
You reall should switch to a proper IDE
i was honeslty just using it cause i found it easy to share projects and stuff
when i was working with a few other people
and now its just a bad habit
@client.command()
@commands.is_owner()
async def sendimage(ctx):
# Rewrite
file = discord.File("C:/Users/[myname]/Desktop/discordbot/Discordbot/Discordbot/cow.png", filename="fish.png") # an image in the same folder as the main bot file
embed = discord.Embed() # any kwargs you want here
embed.add_field(name="text1", value="Hello World", inline="False")
embed.set_image(url="attachment://fish.png")
embed.set_thumbnail(url="attachment://fish.png")
embed.add_field(name="text2", value="Hello World", inline="False")
# filename and extension have to match (ex. "thisname.jpg" has to be "attachment://thisname.jpg")
await ctx.send(embed=embed,file=file)
Change the location of the image to wherever it is your image is. the filename is the reference to the sed_image and set_thumbnail, it can honestly be whatever you want.
If you want to share it easily I guess you can always zip the code
by share i mean it was more simple than constant pull requests and merging and branches on a github repo
fwiw with a decent IDE like PyCharm that's super easy
@hollow iron is there a specific condition?
ah yes pycharm, the thing smart python devs use
Like I've been contributing to @unkempt canyon quite a bit recently, and PyCharm just makes it so easy with its built-in git features
i use Intellij with a python plugin
As in. What needs to happen for the bot to send a message to the channel?
for reasons
Switch to PyCharm smh xD
Trust me PyCharm is 1000% worth it
As long as you have enough RAM (8gb min, ideally 16gb)
oh im not arguing that, i know its worth it i used to use it at school
how can i get the cog's subcommands in help?
oh god i dont like having my token as plaintext
how to react to a message..
message.add_reaction
how do i remove the command from the content of command
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
what?
like when i use a command
do you want to delete the cmd after its used?
the content of the message is the entire command with prefix and command name
i dont want that in the message content
code?
fetch the channel using its id
Pov : you are using discord.Client
@client.command()
@commands.is_owner()
async def msgchan(ctx):
channel = client.get_channel(794837147068792865)
await channel.send('Hello')
@hollow iron enable developer mode on discord, right click channel and copy id
cog.get_commands()
that gives the commands, not subcommands
@hollow iron
@client.command()
@commands.is_owner()
async def msgchan(ctx, chanid):
channel = client.get_channel(int(chanid))
await channel.send('Hello')
if you want to be able to specify the channel id with the command
also @hollow iron 'client' could also be bot. it's whatever you specify here:
client = commands.Bot(intents=intents,command_prefix = '$')
Guys, I am making a command for DM with my bot, and when the user writes a message, the message is sent in a server channel anonymously, can i add a button that can direct the user to that specific channel?
whats message
wot
Does the bot have permissions to view and send messages to that channel?
oh
you're passing the id as a string.
pass it as an int
also dont indent
try this
vrbl = Bot.get_channel(886511773753147412)
await vrbl.send('yo')
why is pep 8 so strict???
change vrbl to channel
Who uses pycord?-
@hollow iron i honestly have no idea at this point. I've sent you everything that works and somehow it's not working for you.
@client.command()
@commands.is_owner()
async def msgchan(ctx):
channel = Bot.get_channel(886511773753147412)
await channel.send('Hello')
This should work, but I just don't know anymore. if it doesn't work for you then you've gone wrong somewhere.
It's just a style guide which tells how to make yr code more readable
ctx.bot.get_channel() or client.get_channel() and it will work
it throws a fit when i have a space to seperate my dict entries from teh :
pep 8 is like an overbearing parent
Haha
shouldn't need that tho. Mine works without it.
.....?
@client.event
async def on_message(message):
if message.content.startswith("b|") == False:
try:
if message.channel.id in client.channelGame.keys() and client.channelGame.get(message.channel.id) == 1:
if message.author != client.user and message.author.id in client.players:
if message.author.id == client.players[0]:
if len(message.content) <= 45 and " " not in message.content:
client.remainingCharacters = len(message.content)
while client.remainingCharacters > 0:
for i in message.content:
for key in pointDict:
if i == key:
client.points += pointDict[key]
client.remainingCharacters -= 1
await message.send(client.points)
client.points = 0
client.players.insert(0, client.players.pop())
await message.send(client.players)
except IndexError:
print("Index out of range, probably empty still")
await client.process_commands(message)
is there a contradiction in here somewhere?
it registers teh person joining the game, it registers the game channel, but it wont send any messages about points
Try adding print statements and see which ones are triggered
hmmm literally none of them
?
nothing triggered at any point
i think its my dictionary key search
does message not have a .channel.id?
like if i print ctx.channel.id off the join command it works
but not if i put message.channel.id
The TextChannel that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
The channel ID.
I am currently making an advertisement command, and a question is how many members It has.
I want It to detect the message.content but how can I do that?
I currently have:
if message.content.lower() <150:
return await ctx.send("We dont accept servers under the needed 150 members.")
But It doesnt detect the number or atleast, theres no error or output
whats your code?
oh oh oh
try:
if int(message.content) < 150:
do stuff
except:
something do on broken
To what are you adding reactions?
should convert your message to a int which can be compared to another int
Help!!!
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
File "/home/container/bot.py", line 771
@bot.command()
IndentationError: unexpected unindent
why>
you indented by accident on or around line 771
you as in server owner?
or you as in, just always youj regardless of role?
@client.command()
async def spamvaprant(ctx):
vaprants_id = 672580539513045013
await client.send_message(vaprants_id, 'Spam spam spam')
You don't need 'vaprants_id' However it's there so u understand
!codeblock
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@bot.command()
@commands.dm_only()
async def partner(ctx, leden=None):
await ctx.send("Bedankt voor het aanvragen van een partnership! Hoeveel leden heeft u?")
try:
message = await bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=45.0)
except asyncio.TimeoutError:
await ctx.send("Helaas reageerde je niet binnen 45 seconde! En de prompt is beeindigd.")
else:
try:
if int(message.content) < 150:
return await ctx.send("We accepteren helaas geen partners onder de 150 leden.")
if int(message.content) > 150:
await ctx.send("Top! Hier komt dan de rest van de cmd")
return
else:
await ctx.send("Error, geen geldig nummer gevonden.")```
File "/home/container/bot.py", line 768
else:
^
SyntaxError: invalid syntax
Actually doesn't work. apparently not /shrug
anyone?
No. it's meant to be 'except'
Technically the truth.
The best kind of truth
${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/${BOT_PY_FILE}
File "/home/container/bot.py", line 763
int(message.content) < 150:
^
SyntaxError: invalid syntax
idk, go to #python-discussion at this one
Yeah I know. I said that a while ago.
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=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/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
you're trying to convert message (string) to an int.
whaii
it's still just going to do that unless someone takes over the project
Well. discordpy will continue to work until discord itself updates the api
or until python updates and python commands are deprecated.
Whichever happens first
So we still have time
There are a lot of good discord.py forks
I prefer spoons but okay.
lol
Hello,
I have a bot and I would like it to leave all servers that dont have their ID's inside a certain file. How do I get the ID's of the servers my bot is in and how to make it leave them?
The guild’s ID.
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.delete "discord.Guild.delete").
get_guild(id)```
Returns a guild with the given ID.
would this world?
for i in guild.id:
if i != 1234:
guild.leave()
NEED HELP
This is my code.
import os
import discord
from discord.ext import commands
import music
Client = commands.Bot(command_prefix = '§', intents = discord.Intents.all())
cogs = [music]
for i in range(len(cogs)):
cogs[i].setup(client)
@client.event
async def on_ready():
print(f"{client.user} logged just in!")
my_secret = os.environ['TOKEN']
client.run(my_secret)
!d discord.ext.commands.Bot.guilds
guilds```
The guilds that the connected client is a member of.
about yes
got like 3 erros
bot.guilds
it returns a list right?
Whats the issue
no, integers are not iterable
a list of guild objects, yeah
i can just do a while loops dw
no
okayyy i see
for i in range(len(cogs)):
cogs[i].setup(client)
Oh I thought guild.id was a list
thanks alot guys
bot.guilds returns a list of discord.Guild objects
@client.command()
@commands.is_owner()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
@commands.is_owner()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
!d discord.Client.guilds
guilds```
The guilds that the connected client is a member of.
is this the right code?
then i can just make a while loop via how many keys there are right?
With the amount of people saying 'bot', should I just change my code from client to bot? ;-;
Yes. I should know coz I copied it from a youtube.
and ran it. and it worked.

If it works it works
you can use a for loop
i get a malformed disk image for my database when replit tab closes or crashes. if i close the database, would the database be fine even after replit crashing/closing?
nah i got like 5 errors more
with ur code
did you remember to change 'client' to whatever you specified at the start? client = commands.Bot(intents=intents,command_prefix = '$')
yours might be bot or BOT or Bot or BOt or bOT or boT
you can call it whatever you want, it doesnt matter
@lament mesa problem is tho. people keep using Bot or bot and im here using client and they get confused ;-;
how to bot join welcome messageeeeeeeeeee
name it bot then
yeah I change it in my main.py
D:
@bot.listen('on_message')
async def whatever_you_want_to_call_it(message):
# do stuff here
# do not process commands here
here waht does 'do not process commands here' mean?
use @bot.command()
where is that
instead of using if statements there
No matter what you name it, it is an instance of commands.Bot
it just leads me to this channel
yeah read what the bot said bru
I know that. but like, is it just standard to call it bot? is there a discord bot makers industry standard name?
So there is a standard
Lets say you have a class named Foo you won't name the instance bar right?
bet
idk, im weird. but probably not
It will be good and less confusing if you name the instance foo
The same applies to commands.Bot
How did you get that darkened background on that text?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
whenever i do that I cant do it inline.
Is there any event that has anti nuke like on_guild_channel_create i dont know how to use it
whats the problem
do you have bot = commands.Bot ?
Guys, i changed the name and the pfp of my bot, does it take time to get changed on the server?
guys how to make bot send message when it joins a server
it says that there is no client, how the hell did you guessed he has client ????
on_guild_join
you need to define client as a bot instance or a client instance
its suggested to use a bot instance AND name it as a bot instance
suggested: py from discord.ext import commands bot = commands.Bot()Or you can use a client instance client = discord.Client()
yes
Guys
https://discordpy.readthedocs.io/en/latest/api.html#discord.on_guild_join
you need guild intents
How to kick a user that makes to many channels using the on_guild_channel_create
ummm i didnt understand....
well,look
on_guild_channel_create is a event for the bot that can count how many channels are being made but idk how to usw it
bot = commands.Bot(command_prefix="Your prefix here", intents=discord.Intents.all())
should that be in line 4?
yeah
and use your prefix instead of your prefix here
imagine spoonfeeding
sorry, i cant help with that
I cant do anything, he's gonna come back here...
lmao
on_guild_channel_create is an event which is triggered when a guild channel is created
what should i define this with
it doesnt mention channel
how to mention it then
Ye ik but how do i kick a user that makes to many
should it be @bot.client
@slate swan we wont spoonfeed more
Afk command who knoww
learn basic python before trying to use discord.py
dpy is not at all a beginner friendly library
u are making client.command() bro
pls typee
help
you need to check if the channel created is by the same member in a short duration of time and if yes, then kick the member
bro im reading this but i get issues, https://vcokltfre.dev/tutorial/04-pong/
So far we've made a pretty simple bot - it only responds to !hello with a static response. Not particularly interesting, is it? Let's fix that! In this part we'll be creating a ping command that shows the bot's gateway websocket latency when you call it.
are you sure your using the correct ids 
But look idk how to do that lol that event doesnt let u add more arguments then just the channel argument so how would i kick a user without the discord.Member argument can u try it out and tell me
also it doesnt meantion in title i believe
i use role.mention
🥲
try to put it in description
ok
@tawdry perch look there is a even called on_guild_channel_create that checks if any channel has been made how do i kick a user that makes to many
Like if channel.guild > 7:
Ban
Somethi like that
Can u paste the source here
Like for this event
Ok
Alright ill look at it brb
MAKING A DISCORD BOT FOR Digimon or Pokemon
Hi I wanted to ask you if you wanted to help making this bot
I have made a discord bot in the past but this time I want someone that could help me
Kinda... I need someone that could be my second hand and contribute in making the bot
The bot is gonna be written in Python
If you are intrested come to my DM.
Well not really can u give me a sample
Guys
@bot.command(aliases=["checkcogs", "check"])
async def checkcog(ctx):
author = ""
if ctx.author.id == 815555652780294175 or ctx.author.id == 723032217504186389:
if ctx.author.id == 815555652780294175:
author = "Mr One"
elif ctx.author.id == 723032217504186389:
author = "Mr Zero"
for filename in os.listdir('./cogs'):
all_cogs=[]
loaded_cogs=[]
if filename.endswith('.py'):
print(filename[:-3])
all_cogs.append(filename[:-3])
print(all_cogs)
await ctx.send(f"Hey {author} All cogs are [{''.join(all_cogs)}]")
for i in all_cogs:
try:
bot.load_extension(f"cogs.{i}")
await ctx.send(f"{i} wasn't loaded")
await asyncio.sleep(1)
bot.unload_extension(f"cogs.{i}")
except commands.ExtensionAlreadyLoaded:
loaded_cogs.append(i)
await ctx.send(f"Hey {author} All loaded cogs are [{''.join(loaded_cogs)}]")
Why is this giving me an error?
Its returning
Off that command
Look when the user makes more channels then the limit it should kick him can u do that?
Yes like just the on_channel_create part
Thats all
Na
@gloomy coral imagine using bot
Titles only support markdown chars
I FIXED IT WITH des
@slate swan rtfm for the events member join/removed
That makes more then the limit
if so, you'll need to check the audit logs
wdym
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print('{0.user} did {0.action} to {0.target}'.format(entry))
```...
can sm1 help me pls
@gloomy coral the thingy u defined commands.Bot for :)
.
And how would i kick the user can u do a sample
..
oh idc
same <3
the iterator returns a AuditLogEntry you can get the user using AuditLogEntry.user, and then passing it in Guild.kick
So like this
user = AuditLogEntry.user
Guild.kick(user)?
you can filter the audit logs using action=AuditLogAction.channel_create
no
i said the iterator returns it
Can u just make a the whole code that would be easier to understand
@hasty iron cld u help me?
cant find the error
where is the error??
what error do you get
ok
i got it bro thnx found it already
fix?
sorry to disappoint you, but i don't have clairvoyance
i don't know what you expect or what you need
and i am supposed to "fix"
sure man
How to react on messages..... lile of they type: a/invite, bot should react with a ✅ help in dm plss
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
thanks
how dont work
how about
you send the code
and the error you get
and then we'll see "how dont work"
should be a string
I will ask you one thing. How is it supposed to know what to add a reaction to?
This too.
pls u help me @hasty iron
read what the two people above said
Hmm so how can i make custom commands what's the ideology behind ... its like a user creates a command with some text and invokes it normally eg: !cc create test hello there and then the user will do !test and thr bot eill respond hello there... im ready to make it but i need the logic behind that how can i invoke it as a normal cmd
how i can solve this problem
What are you adding a reaction to?
Not what reaction, what are you reacting to?
dm
Do
msg = await ctx.author.send("ur stuff")
await msg.add_reaction("emoji")
He wants to react to the ctx.message.
thanks
No*
That will react to the message that the bot sent not you.
he said dm msg
Show your code.
im doing erro handling in a cog
With my say command how do i make what i said get deleted but the bot still says it?
in the third line, i.e. the line after async def invite()
put msg = await ctx.auth...
ok, so when making slash commands with discord-slash(whatever), how long does it take for. the / commands to register?
@commands.command(name="Say")
async def say(self, ctx,*, message=None):
await ctx.send(message)
auuuuu
delete the original message with ctx.message.delete and then send the required
so under await.ctx.send put
ctx.message.delete
?
above or below your chocie
it will be executed in the order you put it
how i can fix this problem
You need to have the role "Giveaway Handler" so that the command would work.
the error handling code is within the cog
i want if a user don't have that role bot should tell him that you must have a role with that name
Error handlers
is that a problem
Why did you show me your whole file? I only asked for the part where you have the error.
!d discord.ext.commands.MissingRole
exception discord.ext.commands.MissingRole(missing_role)```
Exception raised when the command invoker lacks a role to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
New in version 1.1.
Before the await ctx.author .send add msg =
So it becomes msg = await ctx.author.send("stuff")
The command won't work at all if the checks weren't passed.
Define the message you sent to msg
pls dm
How Do i add a reaction to my embed?

yh thats why i used hastepaste
how i can pass checks
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send(f"You need `{error.missing_role}` role to use this command")
yes
By passing them.
It checks if you meet the requirements to use the command and if you don't the checks aren't passed.
this is a global error right? For all commands?
oo
You can't get into a party without a ticket, you can't ban a member without ban_members permissions.
Yes.
it should be in the starting ?
oo👍
It should be where it should be.
If you don't know such very basic things I highly suggest you learn Python before jumping into an advanced library like discord.py.
@client.event
async def on_guild_channel_create(channel):
try:
guild = channel.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_create).flatten()
logs = logs[0]
reason = "Created More Channels Then The Limit"
await logs.user.kick(reason=f"{reason}")
await channel.delete()
except Exception as e:
print(e)``` guys how do i fix this error
'User' object has no attribute 'kick'
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@client.event
async def on_guild_channel_create(channel):
try:
guild = channel.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_create).flatten()
logs = logs[0]
reason = "Created More Channels Then The Limit"
await logs.user.kick(reason=f"{reason}")
await channel.delete()
except Exception as e:
print(e)```
'User' object has no attribute 'kick'```
is user defined
Get the user from the guild's members. You can do
member = guild.get_member(logs.user.id)
await member.kick()
Did yiu even read the error?
'NoneType' object has no attribute 'kick'```
Try to print member.
it says None
Try to print logs.user.id.
yes it does print my id
All I can assume is that the user is not in the guild's members, or you don't have member intents enabled.
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Then do it and it should work.
it works thank you
!discord coinflip
!discord.coinflip
khm
helppppp
!coin
!coinflip
How to make coin flip command
@zenith zinc No spamming pls
Make a random number generator
ok sory
Just make make a variable with heads or tails and random.choice(coin_flip)
so Im trying to make my clear command clear users for specific users, like -clear user amount
!userinfo
#bot-commands
so I'm trying to make my discord bot clear messages for specific users, like -clear user amount
ok
but I don't know how to make it clear for the user
await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
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/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
What do you check for?
how would i got about counting the messages a discord user has sent and making my bot display them
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
``` here is an example from the doc page, just replace `client.user` with your Member or User object
member == member? @hasty iron
o thx
Theoritically speaking, this code should work right?
@client.event
async def on_ready():
print('bot initialized!')
pre_serversallowed = varsfile.serversload()
serversjoined = client.guilds
serversallowed = []
index_ = pre_serversallowed.keys()
for I_ in index_:
serversallowed.append(client.get_guild(pre_serversallowed[I_]))
index_ = serversjoined.keys()
for I_ in index_:
if serversjoined[I_] in serversallowed:
pass
else:
client.serversjoined[I_].leave()```
The goal is to leave servers that dont have their ID's in the file
that is imported
in varsfile.serversload()
did any one knows how to host discord.py bot host on HEROKU
any good youtube videos

No idea sry mate
dont do it
heroku is not for discord bots
what
😂
heya, how can I make my discord bot delete peoples messages after they leave?
hi I need help. How to add timestamp if I have the unix time
but then my ban command will be useless
could you elaborate?
you mean completely wipe all messages when the user leaves on their own?
help pls
when they leave just purge their messages ig
you either need to ban them with deleted days set to max, but this is limited in days
or you need to iterate over EVERY channel in the discord and EVERY message, which is a TON of API calls and can last months to finish if you have quite a lot of messages (a long time user for instance) and check who the author is
wait I think I know how to solve this
you need a datetime object
why is my snipe command not working all its saying is There is nothing to snipe
@commands.command(name="Snipe")
async def snipe(self, ctx: commands.Context):
if not self.last_msg:
await ctx.send("There is no message to Snipe!")
return
author = self.last_msg.author
content = self.last_msg.content
embed = discord.Embed(title=f"Message from {author}", description=content)
await ctx.send(embed=embed)
```y
!d datetime
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
def to_timestamp(timestamp: int, typ: str = None):
if not isinstance(timestamp, int):
try:
timestamp = int(timestamp)
except ValueError:
print("Invalid Timestamp Given: {}".format(timestamp))
if not typ:
return f"<t:{timestamp}>"
if typ not in ["f", "F", "d", "D", "t", "T", "R"]:
print("Invalid Type Given: {}".format(typ))
return f"<t:{timestamp}:{typ}>"
``` Got this from R. Danny ^^
tysm
you may only use danny's code if your bot is open source too @grand anvil
wait I meant like embed timestamp
if you have rdanny code, you need to make your bot open source and add the license
read the license
fr? I never knew that :)
read the license
but it doesn't help me
on the github?
I need like the one it shows in embed on bottom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.


