#discord-bots
1 messages · Page 570 of 1
so remove break
So, it seems like BOT_TOKEN is not in the current program. Do you have it defined somewhere, do you pull it from anywhere (.env)?
Yes, and move the code up there so you keep printing for each guild
once i removed it it hates the print part
You indented twice, you want to only indent once to keep consistency and you also want to put the print code inside the for loop and also remove the if guild.name == GUILD
I mean I added BOT_TOKEN to the file
that's not what happened
Like this:
for guild in client.guilds:
print(guild.name)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
he simply has to put the print in the if statement
I removed the guild.name=GUILD
and got it fixed
and
Though, you also need to define BOT_TOKEN somewhere
Hm, did you pull it from the env?
How did you get the bot token
@av.error
async def avatar(ctx, error,member : discord.Member = None):
if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
msg = await ctx.send(embed = discord.Embed(title = 'Invalid Response',description = f"Error: There is no such user, {ctx.message.author.mention} please try again.", color = 0x5865f2))
embed.set_footer(text="Thank you for using Cursex")
ctx.embed.timestamp = datetime.utcnow()
await asyncio.sleep(7)
await msg.delete()
await ctx.message.delete()
I have a token from discord dev and added it to herok
the footer won't load
Yep, though you still have to bring the env variable into the program
Usually with os.environ and python-dotenv
This should help:
https://vcokltfre.dev/tips/tokens/
Storing your tokens and application secrets securely is very important. In this bonus tip I'll show the most common ways to do so in Python.
and add to my main.py
didn't fix it still the same here is all the code: https://paste.pythondiscord.com/qajaqifibi.py
If you want to print each guild separately, you have to put the code that prints each guild into the for loop.
how?
how can i make first message command?
Something like this:
#discord-bots message
You seem a bit confused about for loops in general though, do you have any questions about them?
yes how to use them really basic discord.py and python
So, for loops in Python are like getting each "element" in a "container", usually
say if in real life, I had a bucket of fruits, and I want to go through each fruit separately, that would be how a "for loop" works, somewhat.
So, say I have a list with the words "apples", "oranges", and "bananas"
!e
my_list = ["apples", "oranges", "bananas"]
for fruit in my_list:
print(fruit)
@brave vessel :white_check_mark: Your eval job has completed with return code 0.
001 | apples
002 | oranges
003 | bananas
The fruit part of this is the variable that Python will bind each element to
@av.error
async def av(ctx, error,member : discord.Member = None):
if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
msg = (await ctx.send(embed = discord.Embed(title = '',description = f"`Error: There is no such user,` {ctx.message.author.mention} `please try again.`", color = 0x2f3136)
embed.set_footer(text="error your mom")))
await asyncio.sleep(1)
await msg.delete()
await ctx.message.delete()
error:
File "C:\Users\User\Desktop\bot discord server console — копия\bot.py", line 159
embed.set_footer(text="error your mom")))
^
SyntaxError: invalid syntax
Press any key to continue . . .
opened 1 bracket, closed 3
don't work why not
you to me ?
yes
msg = await ctx.send(embed = discord.Embed(title = '',description = f"Error: There is no such user, {ctx.message.author.mention} please try again.", color = 0x2f3136))
this would work
and remove two ) of the set_footer
...
On mobile it's formatted so poorly that I didn't see the first bit
main point is, don't put the set_footer in the constructor
then how do I do this so that the bot deletes both Footer and embed.discord?
it is not deleted at all
why are you covering it with brackets
does not even need it
that worked thanks
No problem!
and that loop thing makes sense
error:
File "C:\Users\User\Desktop\bot discord server console — копия\bot.py", line 159
embed.set_footer(text="error your mom"))
^
SyntaxError: invalid syntax
Press any key to continue . . .
code:
@av.error
async def av(ctx, error,member : discord.Member = None):
if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
msg = await ctx.send(embed = discord.Embed(title = '',description = f"`Error: There is no such user,` {ctx.message.author.mention} `please try again.`", color = 0x2f3136)
embed.set_footer(text="error your mom"))
await asyncio.sleep(1)
await msg.delete()
await ctx.message.delete()
bruh? why do you have 2 brackets at the end of set_footer?
how can I use converters if i don't have a context?
?
it's all in "msg"
im loosing brain cells rn
lol
its not lmao
-_-
and you dont even need to put it in "msg"
someone?
yes? then how can I force the bot to delete his message without "msg"
?
. . .
!d discord.ext.commands.Context.send
do you know how attributes work?
sure
doesn't look like it
!d discord.ext.commands.Context.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
delete_after deletes the message after n seconds
there is a way to use converters without passing a context?
make the embed first and then send
or call the function directly
discord.Embed().set_footer()
thank you
How to set bot sending photos from my computer using this
@bot.event
async def on_message(message):
if message.content == "Ping":
await message.channel.send('Pong')
is that possible ?
i know @bot.command can perform send photos but how about this one ?
why do you want to do that with this when you can do it with @bot.command?
i just ask is that possible ?
yes it is
msg = await ctx.channel.send(f"`Now playing: {var3}` \n{url}")
await msg.add_reaction(u"\u23F8")
await msg.add_reaction(u"\u25B6")
try:
reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: reaction.emoji in [u"\u23F8", u"\u25B6"], timeout=90.0)
except asyncio.TimeoutError:
return await msg.clear_reactions()
else:
if reaction.emoji == u"\u23F8":
await msg.remove_reaction(reaction.emoji, ctx.author)
await ctx.voice_client.pause()
elif reaction.emoji == u"\u25B6":
await msg.remove_reaction(reaction.emoji, ctx.author)
await ctx.voice_client.resume()
This code is supposed send a message showing what is playing, and bring up pause and play reactions which will pause and play the audio when reacted to by a user. Right now it only works the first time the command is called, after that any new times the command is called the reactions do not do anything, additionally, it only responds to a reaction once, for example if someone hits the pause emoji then the audio will be paused, however if the play emoji is hit after that then nothing will happen.
If your trying to send a picture from your computer use import os to open a file and put it in a embed and thats all
Yes but bad practice
wait_for only waits for 1 time, use for loop to keep listening, to stop you can add a stop reaction where it can stop waiting for the reactions.
but how much would i loop the for loop?
what
put it right above the wait_for
so after its finised it will go straight back to the wait_for
wait
Yes I understand, but wouldn't it be better to use a while loop because it would be an undefined amount of times that it would have to repeat
Ok but what would I put as the condition?
while True:
#wait_for stuff
Seemed to have no effect
@client.command()
async def beg(ctx):
people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
amount = random.randit(1, 1000)
title = random.random(people)
``` if im correct this should have no errors right?
why doesn't this work I have checked around and it should work fine```py
@client.event
async def on_member_remove(member):
channel = client.get_channel(904073508269731860)
embed=discord.Embed(title=f"{member.name} Left", description=f" {member.name}has left{member.guild.name} sad to see you go :( ")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)``` this works fine for the join message
@client.event
async def on_member_join(member):
channel = client.get_channel(904073508269731860)
embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)```
define "it doesn't work"
and i'm pretty sure it's on_member_remove, not on_member_leave
@client.command()
async def beg(ctx):
people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
amount = random.randint(1, 1000)
title = random.random(people)
embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
await ctx.reply(embed=embed)
db2.update_one({"user": ctx.author.id},
{"$push": {"bal": amount}})
wtf is wrongf
nvm
nvm i found what was wrong, the db wont update
how can I do this?
embed.footer
!d discord.Embed.footer
property footer: _EmbedFooterProxy```
Returns an `EmbedProxy` denoting the footer contents.
See [`set_footer()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.set_footer "discord.Embed.set_footer") for possible values you can access.
If the attribute has no value then [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") is returned.
k thanks
thank you
@client.command()
async def beg(ctx):
people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
amount = random.randint(1, 1000)
title = random.choice(people)
embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
await ctx.reply(embed=embed)
db2.update_one({"user": ctx.author.id},
{"$set": {"bal": amount}})
``` how can i add there before value to there after value
@client.command()
async def beg(ctx):
people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
amount = random.randint(1, 1000)
title = random.choice(people)
embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
a = db.find_one({"user": ctx.author.id})["bal"]
new_value = f"{a}+{amount}"
r = eval(new_value)
await ctx.reply(embed=embed)
db2.update_one({"user": ctx.author.id},
{"$set": {"bal": r}})
``` new stuff
what do yu mean
right now it is only doing 1 server how do i get it to do multiple servers
set a channel for each server
how do i add it in
i am basic in python and discord.py i am learning along the way
so i just want it to do 2-3 servers but idk how to add them in
They already answered you
@kindred epoch ur smart can u help me
@client.command()
async def beg(ctx):
people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
amount = random.randint(1, 1000)
title = random.choice(people)
embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
a = db.find_one({"user": ctx.author.id})["bal"]
new_value = f"{a}+{amount}"
r = eval(new_value)
await ctx.reply(embed=embed)
db2.update_one({"user": ctx.author.id},
{"$set": {"bal": r}})
``` new stuff
What do you need help with
Create variable doesn't return url what to do to get url
Huh?
how do i check if a member has nitro?
but for that it was adding the values
Discord doesn't give any reliable way to check if a user has nitro
what things should my bot do? so far it does 3 commands 2 text back 1 does something
it depends on what your bot is (music/moderation/all-in-one etc)
Commands everyone can use:
%ping
%purge
%Help
Commands dev only:
%Moveit
Hello! To handle invalid token errors, I use this:
bot = Roover()
token = os.getenv('TOKEN')
try:
bot.run(token, reconnect=True)
except Exception as a:
handler(a).efilter()```
However still get this error:
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
again it depends on what ur bot is meant for
all in one
youll need moderation tools, music and basically everything u can think of
basic bot builder barly know python and discord.py
then i suggest learning python before discord.py
otherwise youre going to have a really hard time
I learn on the way
it's not a beginner friendly library, you'll be fustrated at many errors
@client.command()
async def serverinfo(ctx):
server_created = ctx.server.created_at.strftime("%d %b %Y %H:%M")
embed = discord.Embed(description=f"Server | {ctx.guild.name}\nID | {ctx.guild.id}\nCreated At | {server_created}\nOwner | {ctx.guild.owner}\nMembers | {ctx.guild.member_count}\nRoles | {len(ctx.guild.roles)}\nChannels | {len(ctx.guild.channels)}\nText Channels | {len(ctx.guild.text_channels)})\nVoice Channels | {len(ctx.guild.voice_channels)}\nBoosts | {ctx.guild.premium_subscription_count}")
embed.set_footer(text=f"Invoked By: {ctx.author}",icon_url=ctx.author.avatar_url)
embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.reply(embed=embed)
``` i dontt even know what the error is
its not returnign anything in terrminal
can you debug it with jishaku
Does it send? If not then do you have an on_message event by any chance?
are any other functions working
dont send and no
Did you save and restart
mhm
ill restart one more time
You could try adding prints everywhere and see where it stops printing
never heard of this?
@slate swan this is a useful debugging tool, simply do pip install jishaku and add this to ur main.py then do !jsk dbg (your_command)
client.load_extension("jishaku")
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
it comes in handy when there are no terminal errors
should i run this in a public channel?
it did nothing
did it react on ur command?
yes 😭
omg you said "!" so i thought to use that
replace ! with ur own prefix
LOL
i thought it was understood but nvm, do it again
react on the trashbin while ure at it
omg i put server instead of guild
there we goo
dumbest error, but thank you that is actually so useful
and i had no clue that even existed
it is
now you do :)
yup that is what the https://google.com is for
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
not all errors you can google and fix
well most are on stack overflow
note your use of language, most
Keyword: Most
most of the code on google/stack is outdated and is making simple things complicated
from my experience only the simple things you can find on stack overflow, when you encounter bugs in classes etc you likely wont find a solution
like clorox wipes 99.9% is found
So your just gonna skid code..
I mean lets be honest if the solutions can be found on stack overflow whats the need of all these channels here...
fr, or if you could just look anything up and it will work
For more complicated code you'll need others' assistance and quite a fair bit of Py knowledge
why dont they make server an alias of guild
ask Danny
oh i forgot they discontinuted
he quit
he's still around in discord.gg/dpy
because the official discord docs define it as guild
people are used to calling it servers though
yeah
getting used to guild is kinda aids
the word server would mean many other things in coding tho
^
hmm good point
It used to be server but later changed to guild
I'd assume because that's the correct discord terminology
@commands.command(name="serverinfo")
async def serverinfo(self, context):
"""
Get some useful (or not) information about the server.
"""
server = context.message.guild
roles = [x.name for x in server.roles]
role_length = len(roles)
if role_length > 50:
roles = roles[:50]
roles.append(f">>>> Displaying[50/{len(roles)}] Roles")
roles = ", ".join(roles)
channels = len(server.channels)
time = str(server.created_at)
time = time.split(" ")
time = time[0]
embed = discord.Embed(
title="**Server Name:**",
description=f"{server}",
color=0x42F56C
)
embed.set_thumbnail(
url=server.icon_url
)
embed.add_field(
name="Owner",
value=f"{server.owner}\n{server.owner_id}"
)
embed.add_field(
name="Server ID",
value=server.id
)
embed.add_field(
name="Member Count",
value=server.member_count
)
embed.add_field(
name="Text/Voice Channels",
value=f"{channels}"
)
embed.add_field(
name=f"Roles ({role_length})",
value=roles
)
embed.set_footer(
text=f"Created at: {time}"
)
await context.send(embed=embed)```
error
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
ping me when answer
you're likely missing intents. guild intents to be exact, you'll enable this through firstly the dev portal and in your code, have u done this?
slap the ticks
since ure bot is verified u'll need to request for it
Nah
Nope.
you don't need context.message.guild you only need context.guild
if message.author.permissions.manage_messages:
return
is this proper?
!d discord.Member.guild_permissions
property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
@slate swan right way
@client.command()
async def welcome(ctx, user:discord.Member=None):
if ctx.author.guild_permissions.manage_messages:
if user is None:
await ctx.reply("Woah, how can you think of welcoming no one?")
elif user.bot:
await ctx.reply("Sorry but bots don't care even if you welcome them...")
elif user==ctx.author:
await ctx.reply("You cannot welcome yourself!")
elif user.top_role >= ctx.author.top_role:
await ctx.reply("Bruh, you cannot welcome someone who is already in such a high rank!")
else:
visitor_role=ctx.guild.get_role(698500675306258452)
if visitor_role in user.roles:
try:
await user.remove_roles(visitor_role)
initiate_role=ctx.guild.get_role(698500328169013258)
await user.add_roles(initiate_role)
try:
await user.send_message(f'You are not a member of {ctx.guild.name}!')
except Exception:
pass
await ctx.message.delete()
await ctx.channel.send(welcomemsg.replace("(userhere)", f"{user.mention}"))
except Exception:
await ctx.reply("Missing permissions for that user")
else:
await ctx.reply("User doesn't have visitor role")```
IDK why but it show indentation error in await `ctx.message.delete()`
what does dik mean
?
@client.command() async def welcome(ctx, user:discord.Member=None): if ctx.author.guild_permissions.manage_messages: if user is None: await ctx.reply("Woah, how can you think of welcoming no one?") elif user.bot: await ctx.reply("Sorry but bots don't care even if you welcome them...") elif user==ctx.author: await ctx.reply("You cannot welcome yourself!") elif user.top_role >= ctx.author.top_role: await ctx.reply("Bruh, you cannot welcome someone who is already in such a high rank!") else: visitor_role=ctx.guild.get_role(698500675306258452) if visitor_role in user.roles: try: await user.remove_roles(visitor_role) initiate_role=ctx.guild.get_role(698500328169013258) await user.add_roles(initiate_role) try: await user.send_message(f'You are not a member of {ctx.guild.name}!') except Exception: pass await ctx.message.delete() await ctx.channel.send(welcomemsg.replace("(userhere)", f"{user.mention}")) except Exception: await ctx.reply("Missing permissions for that user") else: await ctx.reply("User doesn't have visitor role")
wtf
Its was IDK lel
i need help
??
welp
I'll help later busy atm
¯_(ツ)_/¯
my goal is to make a discord bot that will tell me if someone is online in a minecraft server, for exemple :
online (mc name)
yes : (the name) is online !
no : (tne name) is not online !
using an account 24 / 7 inside the server
can somone send me a code for a modmail?
I didnt
lol I didnt pinged
Doesn't matter
I just did this to draw attention 😄
no do it yourself
ok?
#bot-commands please
the role is not pingable, he just embeded it lol
i know
thought it was pingable
considering the role is called helper
¯_(ツ)_/¯
@client.command()
async def welcome(ctx, user:discord.Member=None):
if ctx.author.guild_permissions.manage_messages:
if user is None:
await ctx.reply("Woah, how can you think of welcoming no one?", delete_after=4.0)
await time.sleep(4)
await ctx.message.delete()```
indentation error
ur ide bugged xD
why this error appears?
member.avatar can be None, use member.display_avatar instead
ok thx
replit?
whats the ide
I dont use ide
bruh cmd?
so notepad++ is your ide
you can say
Is there a way to disable a cog commands in a specific guild?
cog check
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
I am trying to make a cmd to save the message and response when that msg is in message. How can i do it?
Like if there is a msg hello the bot to reply with hello sir.
code
@client.event
async def on_message(message):
find = collection.find({"_id": message.guild.id})
for i in find:
l = i['channel']['current'] + 1
f = i['channel']['id']
if message.channel.id == f:
if message.content == l:
await message.add_reaction('☑️')
else:
await message.delete()
embed = nextcord.Embed(title='Counting', color = nextcord.Color.random())
embed.description = "It seems you typed the wrong number. If this was done interntionally please stop it ruins the fun for others. If this was a mistake please make sure nobody else it typing a number so this doesn't happen again."
await message.author.send()
else:
return
error
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 45, in on_message
l = i['channel']['current'] + 1
TypeError: list indices must be integers or slices, not str
{"_id":{"$numberLong":"900936824803958834"},"channel":[{"name":"counting-channel","id":{"$numberLong":"904243700798984272"}}]}
the _id is the guild id
the id is the channel id
name is the channel name
and channel is a dictionary with those values in it
on_message event will be called when someone sends a message. you may check it's content and match the content with your database
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
As it says list indices are supposed to be int not str so for example channel[0]
If you want to get it by name then do a for loop and check the name key
So i gotta use a db for it? Ik the on_message
yes
or maybe a dict in the code if you're the only one who is going to change them
is using io.bytesio in a discord bot good/fine?
and for how much time does it save the binary data in the memory?
It basically says "hey! Your thing is a list and to get an item from list you need to use a number and not string"
ok that makes sense
In a dict you use the key
but in a list theres no key so you use the item position
please ping me when someone replies, thanks
#bot-commands ty
It's fine, Idk about how long it stays.
What?
nah i just wanted to navigate to that channel
so i just mentioned it
ah ok
I want to make Tickets System, is there anything to know how it works?..
I created cross server code do anyone test it
whats cross server code
How can I edit/change a file from a message? something like this
message = await ctx.send(file=discord.File(...))
await message.edit(?=discord.File(...))
There is no file param
you cant
I have seen discord bots do it
hm
oh yeah your right, it is an embed
😂
then I know how to do it, thanks for pointing it out
Hi
show if self.guild.owner_id == member.id:
btw on_guild_remove gets triggered after the bot got removed from the guild
u cant send messages to it 😂
no.. like.. i want to know what does it do and how
use buttons
upon a button click it shud create a channel such that mods and the person who created it can talk in it
hm ok
when i put color=000000
it just comes up with an error
i cant set it to a specific color
help?
On an on_message event, How do I extract the title from the embed from a different bot
0x0000
like if discord.embeds.title == 'Something'
ive used 000000 for other embeds
!d discord.Message.embeds
A list of embeds the message has.
it just wont work for this one
show full code of this
message.embeds[0].title
1st - use em.add_field and em.set_footer
2nd - so what isn't working? what error you get?
!d discord.Embed.to_dict
to_dict()```
Converts this embed object into a dict.
wtf
why do you need the () there tho?
learn more python xD
i think i need to sleep more
# @has_permissions(manage_roles=True, manage_channels=True)
async def rename(ctx, *, text=''):
if text == '':
await ctx.send('.rename `oldname:newname` ')
else:
tag = text.split(';')[0].split(' - ')[0]
oldname = text.split(';')[0]
newname = text.split(';')[1]
print(oldname)
old_role = discord.utils.get(ctx.guild.roles, name=oldname)
old_team_name = text.split(';')[0].split(' - ')[1]
while old_team_name[0] == ' ':
old_team_name = old_team_name[1:]
old_Channel = f'{tag.lower()}-{old_team_name.lower().replace(" ", "-")}'
print(old_Channel)
old_channel = discord.utils.get(ctx.guild.text_channels, name=old_Channel)
await old_role.edit(name=newname)
await old_channel.edit(name=newname)
await ctx.send('Done!')```
it says in error:
```Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
i am the owner of the server
no
but i have to end the brackets
you create variable em
and on next lines use em.add_field
ok
can someone help with this?
like py emb = Embed(...) emb.add_field(...)
full traceback pls
i specifically put anything in the brackets?
File "C:\Users\dell\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\dell\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\dell\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
what is the question bruh?
learn py and read docs
ok i give you example
embed = discord.Embed(title="yes", description="no", color=discord.Color.blue())
embed.add_field(name="no", value="yes")
embed.add_field(name="ok", value="bruh", inline=False)```
that means that your bot doesnt have permissions to do something
ah okay thanks
bot doesnt have enough permissions
in discord.VoiceClient.cleanup do you call disconnect in side it like this: VoiceClient.cleanup(await VoiceClient.disconnect)
It's the AudioSource that has cleanup, not VoiceClient
!d discord.AudioSource.cleanup
cleanup()```
Called when clean-up is needed to be done.
Useful for clearing buffer data or processes after it is done playing audio.
Whats the error/problem
sync def setup():
await client.wait_until_ready()
client.db = await aiosqlite.connect("ekavData.db")
await client.db.execute("CREATE TABLE IF NOT EXISTS money (money int, medkit int)")
await client.db.execute("CREATE TABLE IF NOT EXISTS medkit (medkit int)")
for guild in client.guilds:
for invite in await guild.invites():
await client.db.execute("INSERT OR IGNORE INTO money (money, medkit) VALUES (?,?,?)")
await client.db.execute("INSERT OR IGNORE INTO medkit (medkit) VALUES (?,?,?,?,?)")
and the code is
@nextcord.ui.button(label="+1 Medkit", style=nextcord.ButtonStyle.green)
async def Medkit1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await client.db.execute("INSERT INTO medkit (medkit)")
await client.db.commit()
await interaction.response.send_message(f'test', ephemeral=True)
@nextcord.ui.button(label="-1 Medkit", style=nextcord.ButtonStyle.red)
async def Medkit2(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await client.db.execute("IGNORE INTO medkit (medkit)")
await client.db.commit()
await interaction.response.send_message(f'test', ephemeral=True)
i want it to make it when you click +1 medkit it add one in the database and when -1 medkit is clicked, it removes it
any ideas @boreal ravine ?
well i have no experience with sql
You might wanna ask in #databases
the values
Because you need to remove the parameters...
You just need to compare with the class without parameters
So just ...BotMissingPermissions
Then you can access with error.missing_perms the list of permissions missing
if isinstance(......):
print(error.missing_perms) # will give list of permissions missing
But that's what you have to do
As you can't choose
Just make an if statement to check if the missing permissions list contains the send message permission

Come on, that's basic Python....
Then do it
Use this and look what it prints when the bot is missing permissions, then do your if statement
Sometimes you got to search and try things on your own
Not everything will be given one to one to you in life...
def drinks(user: discord.Member):
db = sqlite3.connect("coin.sqlite")
cursor = db.cursor()
result = cursor.fetchrow(f"SELECT drink FROM coin WHERE member_id = {user.id}")
if result[2] == None:
sql = "INSERT INTO coin(drink) VALUES(?)"
val = (1,)
else:
sql = "UPDATE coin SET drink = ? WHERE member_id = ?"
val = (result[2]+1,user.id)
db.execute(sql, val)
db.commit()
cursor.commit()
a = cursor.execute("SELECT * FROM coin WHERE member_id = ?",(user.id,))
print(a)
cursor.close()
db.close()```
my sql database is not getting updated
is my code right?
you aint commiting it in the last part
oh nvm , its just a select thingy
any errors tho?
question, which coding website is a good host for making my bot online every time? (ONES THAT ARE FREE AND WORK 24/7!)
None
You literally won't find any free one that's good or even runs for 24/7
If you need it that bad you can buy a VPS for like $5 a month
help me please
enable intents?
bot can send server's emoji on dm?
how?
!d discord.Client.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
I have the same question
pass the id in
lol
buy a vps , check the pins
Run it forever on a computer that won't burn
Lol
It might work though
waits for a response
buffering
i'll go check thx
!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.
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
?
read what it says
its a command for ban everyone
its correct?
mass banning is against tos , sir
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
am a helper helped me for that
im sure you asked for "how to ban someone" and not how to ban everyone
no i asked "can u help me with a ban everyone command"
and who was that?
idk the name
well its not allowed so noone here would be providing that help
oh im sorry
it is
¯_(ツ)_/¯
no
can you tell me the command name?
A lot of verified bots break ToS
and this is obviously for raiding servers
Dyno also has music so 🤷♀️
?ban
im aware that vortex bot has a ban command which can ban 'all the members mentioned' while using ban command
but not everyone
no
If you tried to ban everyone you would probably just get rate limited
BetterDiscord momentum

You would need to have a sort of cooldown so that doesn't happen.
huh , how is that better discord?
Purple verified bot tag
it isnt lmfao
^
I was going to say it could just be a beta feature but yeah
Ubuntu 
no it isnt
Damn good thing I gotta go
its common sense
I know now...
was going to
What is wrong with people here now?
just because something is not the right thing

doesnt mean its wrong
It's fine though, let's just chill out and get back on topic :)
emoji = ctx.guild.get_emoji(904322924511641621)
'Guild' object has no attribute 'get_emoji'
so it's wrong like i done?
!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
try bot.get_emoji
module 'discord.ext.commands' has no attribute 'get_emoji'
please read that again
bot.get_emoji
Yeah. You need to use whatever bot variable you have instead of ctx.guild
your discord.ext.commands.Bot variable is bot
i'm in cog so i used commands.get_emoji
doesnt matter , use ctx.bot.get_emoji then
wut be this for?
Nothing
Just put the id as parameter
aighty
Lol
Can you even use cogs without the init?
now Cannot send an empty message --_--
emojis id is invalid
so it returns None
simple
ye
dunder cringe
please only tell us errors when providing code aswell
right click on emoji, copy id, done right?
in get_emoji
In this case all you need is the ID
⚠️

904326122114781194
The bot probably just doesn't share a server with the emoji or something
it's in as admin
does it have emoji intents
by default it does
!d discord.Intents.emojis
Alias of emojis_and_stickers.
Changed in version 2.0: Changed to an alias.
hm
yes
( dont mind the ctx.respond)
dunno
what are your intents rn?
you can add cogs within a cog?
sure
hm
you can add a cog even with the main file
a cog is subclassed
it wont need a setup function tho , just bot.add_cog
how can i get discord.py scripts?
or commands?
wdym scripts
in the code i mean
noone
you need to code them yourself
where is that?
ok
u mean youtube?
no one
oh ty
whats the emoji id? and name
its jishaku , and _bot is already defined
its jsk oops
ye
why underscore though
no underscore more easier
use
await ctx.send("<:emoji_47:904322924511641621:>")
id is 904322924511641621
( i have no nitro)
thats how it is designed , it can be changed using JISHAKU_NO_UNDERSCORE=true in environment variables.
@floral jacinth try this
no underscore more easier
opinions
it send as string
is the bot in the server where the emoji is from?
yes
you sure that the id is correct ? how do you get it?
right click, copy id
nu thats the message id you get
use \:emoji: it will give the emoji id
paste that in get_emoji
How can i set prefix as mention? i.e i want to ping bot and bot will say smthng
\⚠️
i don't
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
the id thing applies only to custom emojis
try using with one in this server
command_prefix takes when_mentioned_or(prefix)
ohw
yea , now try that with your emoji
ok it works, <3 <3 <3 <3
cool !
Well, how can i print something on the bot when i just mention it? For example;
Me: @bot
Bot: hey
Tysm!
use a library for that
that's probably an image?
^
okay
!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/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
My question is more like "Which library is used to do this"
Some help here please
how am i supposed to know
You might not know but others might
!pypi matplotlib
that?
Yeah that's not a bad one.
¯_(ツ)_/¯
i do <clear 2 and it clears 2 messages but later the massage "Cleared 2 messages" gets not deleted
Say the message after clearing
are you sure
u want see?
await ctx.send("message", delete_after=seconds)
you first delete the messages and then send another one, that's not gonna get deleted
I first see this error pls help
lucas purge command
this has nothing to do with dpy
what is lucas?
i will delete the code await ctx.send(f'cleared {amount} messages. ') ?
i know but how fix?
no, you pass in a delete_after keyword-argument @slate swan
it isn't bad, the videos were made in 2017-2019 it's just old
why should we know
idk im just asking
please not here
k
it’s not an f string
oh
👍
btw you can add +1 to amount so the message which triggered the command gets deleted too
that would change many things
how and what?
I find this the absolute easiest way
well for beginners
put an f before the first quotation mark or .format() with the right variable after the string
mhm yeah
switch the purge and the send, sleep some seconds
i have an biiiiiiiiiiiiiiiiiiiiiiig problem
how do my bot 24/7?
beginners should know Python though
CubicHosting
type on google CubicHosting
should != do
and see video
Hosting methods aren’t really related to discord bots

Well you gotta start somewhere
Please don't.
start with learning python in schools , and then miss school classes because you make bots on discord
y'all learn programming in school?
yes
but starting without any programming knowledge will end up with people asking annoying basic questions
and it’s not really programming tho
i started learning py from class 9th , but thats too basic
oof
the things i learn now in class12th is not too high level either
grandpa
just some file handling and sql interactions
well those are useful things for sure
well it’s something
not really hard, maybe the school isn't designed for that
yeah , i learned sql which i use in my bots there
we too ,python was added just for practical things
earlier it used to be python for 9-10 and c++ for 11-12 ( its getting kind offtopic now lol)
Can I make whatever discord bot I want using python?
yes
but music bots or anything breaking ToS
wow like databse of cards and they should appear once in a while
discords?
any ToS
like a discord bot for my playlists,I think im gonna make it
whyy though, should i have playlist in youtube to make it
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
this would probably not be a problem if you ask youtube itself to give you permissions
and they agree, which they wouldn't


How would I check if a user was mentioned in a command? For example, !kick @mention
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
why would you need that in a kick command tho? just use the command builder
like if I was to kick a member i would write !kick @slate swan
And it kicks the user that was mentioned in the message
Sorry if im wrong but im new to discord.py
are you using discord.Client , and on_message events?
Nope
command
what do you have rn ?
@Commands.command
oh a cog?
@commands.command(pass_context = True)
@commands.has_role("Owner")
async def kick(ctx):
no
just a simple command
did you define your bot object?
yes
should I send my whole code?
Why pass_context
Cause otherwise commands.has_role wouldnt work. idk
use parameters
no?
so , it will be py @botobject.command() @commands.has_role(....) async def kick(ctx , user : discord.Member):
commands.command is meant only to use in cogs
pass_context is no longer needed
oh yeah
thats literally commands but in a class my bad
user??
you cant kick users objects
my bad
you can only kick member objects
it would be a member
👍
@botobject.command()
@commands.has_role(....)
async def kick(ctx , user : discord.User):
when i try this
change .User to Member
the commands.has_role doesnt work
the role doesnt get found
uh , that was just for explanation
you need to add your botobject and role there
oh ok
.
i have
quick question are banners changeable for bots
like to a certain photo
or does the owner need nitro or smth
not atm
can someone help me in #help-chestnut
how i can increase time by adding numbers ?
like time is 5:30
if i want to add 5000 seconds in it
then how i can get the time after 5000 seconds ?
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
add this to your datetime
Is there a way make a bot account and have a bot tag next to ur name? Im testing the discord API and I see u can actually do it
I know its against ToS, but imma do it for testing reasons
a bot tag next to a normal user account?
Yeah
even if one selfbots its not possible
ofcourse , its just a explanation how the api works , discord already told it multiple times that automating a user account is against tos
@t0xapex Are you logging into the bot or your user account? Bot user accounts aren't allowed.
Im not automating an account, I’m asking how to put the tag BOT next to ur name, its official in the API. Im doing this for api testing reasons.
you cannot
Wasnt it part of the official API? I thought it was
it never was
How difficult would it be to integrate slash commands into disocrd.py? Like is there any support at all?
do you guys continue to use discord.py?
yes
Yeah, it has all of the up-to-date things except slash commands
but u can just use the beta
aren't slash cmds in the beta of dpy?
no
2.0 includes everything but slash commands
you need to defined client.sniped_messages as a dict first
client.sniped_messages = {}?
@slate swan learn python bro it willl help you
yes tell me please
if you found an
ok
bruh
Instead of asking here and making like you know the answer when replying to the user, you can directly tell them to come here... ¯\_(ツ)_/¯
why not ask him instead of here?
Random memes?
yup
how
apis
hm
How to make sure that every time a ticket is created, its number changes? That is, 1 + 1 = 2 + 1 = 3 and so on.
how is this random?
bro can you tell me how do i use that
Learn to use JSON and lists 🤡
These are the top/latest x memes posts, get a random one from there
hm
Not rocket science and basic Python knowledge lets you do that easily
So yes, you can make it random if you have enough knowledge
Which apparently you don't 
No problemo
how would I know how to make it random if I haven't even looked at the json yet? ¯\_(ツ)_/¯
Then use your eyes, look at it, and only then say it's not random and make your comments 🤡
Judging before looking at it #typical
how we use json
i dont know! maybe i can change it into txt and then split them with /n and then use random module will it work?
How to make sure that every time a ticket is created, its number changes? That is, 1 + 1 = 2 + 1 = 3 and so on.
@rare saddle
Basic Python
Create a counter per guild
Save it in a database or json if it's not big
Increment it every time after creating the ticket
No need to send that lmao
^
I don't need to save
Well if you restart your bot it will start counting at 1 again
So maybe you want to save the counter of the guild, yes.
I know
And if you don't care of that, just make a counter
How easy it is to add it every time
It's python knowledge
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Variables is the first thing you learn.
I know about variables, but I don't know about While True or While False
You don't need that anyways
So how can you make a counter just using variables?
!botvar
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!
Create a bot variable and increment it when you create a ticket
what am i doing wrong? ```py
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="MUTED")
await member.remove_roles(member.roles)
if not mutedRole:
mutedRole = await guild.create_role(name="MUTED")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
embed = discord.Embed(title="muted", description=f"{member.mention} was muted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
await ctx.send(embed=embed)
await member.add_roles(mutedRole, reason=reason)
await member.send(f" you have been muted from: {guild.name} reason: {reason}")
using copied code
is it a type of crime of smth?
how to write deleted messages to the python discord variable.
For example: there are 2 messages and 1 command in the channel.
the bot is trying to clear 5 messages and output that it deleted 5 messages and there were 3 of them in total
nope, just cant help you considering im on mobile
Is it worth it to copy paste?
What's your error
i copied as i was working on it for a week so i looked up
.purge returns the list of messages deleted, get it's length
x = ...purge()
len(x) # number of messages deleted
in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
it cant remove roles
as it works without it
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
Traceback (most recent call last):
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/media/ranveer/New Volume/VS Code/Practice/Bot/bot.py", line 170, in mute
await member.remove_roles(member.roles)
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/member.py", line 822, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'id'```
code
here
aight i'll try
for role in member.roles:
#remove it```
async def removeserverstats(self, ctx):
guild = ctx.guild.id
for guild in self.serverstats.keys():
await guild.pop()```
how can i remove the key here?
is that a json , or a dictionary?
824359600584523876 and 695919805772988506 are keys
json
how to do it here
@commands.command(name= "очистить")
async def clear(self, ctx, *, amount: Optional[int]) -> None:
amount = amount or 0
if amount == 0 or amount >= 101:
embed = discord.Embed (
title = 'Команда `s~очистить`',
description = 'Команда `s~очистить` очистить какое-то количество сообщений \n в данном канале. Не забудь что я могу очистить 100 сообщений за раз, а также \n очень древние сообщения я не смогу удалить.',
colour = 0x694c5f
)
embed.add_field(name= "Использование:", value= "> `s~очистить` `(Количество)`", inline= False)
embed.add_field(name= "Параметры:", value= ">>> <> - Необязательный параметр \n () - Обязательный параметр", inline= False)
embed.add_field(name= "Пример:", value= ">>> `s~очистить` `100` \n ⮩ Очистит 100 сообщений", inline= False)
await ctx.reply(embed = embed)
else:
await ctx.message.delete()
await ctx.channel.purge(limit=amount)
embed = discord.Embed (
description = f':white_check_mark: Удаленно `{amount}` сообщений',
colour = 0x694c5f
)
await ctx.send(embed = embed, delete_after= 3)
@spiral frigate
you would be using .pop function
its here
it works like py thedictionary.pop('the key')
hm
so
@commands.command(name= "очистить")
async def clear(self, ctx, *, amount: Optional[int]) -> None:
amount = amount or 0
if amount == 0 or amount >= 101:
embed = discord.Embed (
title = 'Команда `s~очистить`',
description = 'Команда `s~очистить` очистить какое-то количество сообщений \n в данном канале. Не забудь что я могу очистить 100 сообщений за раз, а также \n очень древние сообщения я не смогу удалить.',
colour = 0x694c5f
)
embed.add_field(name= "Использование:", value= "> `s~очистить` `(Количество)`", inline= False)
embed.add_field(name= "Параметры:", value= ">>> <> - Необязательный параметр \n () - Обязательный параметр", inline= False)
embed.add_field(name= "Пример:", value= ">>> `s~очистить` `100` \n ⮩ Очистит 100 сообщений", inline= False)
await ctx.reply(embed = embed)
else:
await ctx.message.delete()
await ctx.channel.purge(limit=amount)
deleted = ...purge()
len(deleted)
embed = discord.Embed (
description = f':white_check_mark: Удаленно `{amount}` сообщений',
colour = 0x694c5f
)
await ctx.send(embed = embed, delete_after= 3)
@client.command()
@commands.has_role(904013595208216598)
async def report_taken(ctx, message_id : int) :
if message_id is None :
await ctx.send("Syntax : er!report_taken <message_id>")
else :
help_log = client.get_channel(help_log_channel)
report_message = await help_log.fetch_message(message_id)
if report_message.author == client.user :
if "Not Yet" in report_message.content :
await report_message.reply(f"Report case taken by {ctx.message.author}")
# await edit_message(message_id, f"Report Taken Staus : Taken by {ctx.message.author}")
await report_message.edit(message_id, f"Report Taken Status : Taken by {ctx.message.author}")
else :
await report_message.reply("That is not my report message")
else :
await ctx.message.reply("That is not my message. Maybe you got the wrong message id?")
Ignoring exception in command report_taken:
Traceback (most recent call last):
File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\DELL\Desktop\The Epix Bot\main.py", line 235, in report_taken
await report_message.edit(message_id, f"Report Taken Status : Taken by {ctx.message.author}")
File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord_components\dpy_overrides.py", line 72, in edit
data["embeds"] = [embed.to_dict()]
AttributeError: 'str' object has no attribute 'to_dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'to_dict'
how i fix?
It won't bring out anything I don't understand
how can i fix this ??
how do i keep the key for it?
key is the name of the part you want to remove
!e py dict = { 'hm' : 34 } dict.pop('hm') print(dict)
you havent not defined guild
how did you define guild?
Store the returned value of when you used purge() then get it's length. That's the very basic Python knowledge.....
he has, just wrong
@slate swan :white_check_mark: Your eval job has completed with return code 0.
{}
ohh thanks i have forgotten
oh lol
for you case it would be str(guild.id) if they are the guild ids
np
hm
I still didn't understand where I was studying, they didn't talk about it there
I literally explained what to do....
How to save something I do not know
I'm just Russian and I don't understand
- Add
x=before where you used.purge()- Use
len(x)to know how many messages got deleted
More than that I can't do
Aside from adding these 10-15 characters by myself in your code
Which is pretty much useless
async def removeserverstats(self, ctx):
guild = str(ctx.guild.id)
dict = self.serverstats[guild]
await dict.pop(f"{guild}")```
like this?
anyone
if self.serverstats[guild] returns something like py { '12345666777' : {THE STATS} }
SURE!
lemme print
embeds key/embed is a string
{'member_count': 891289849821298709, 'bot_count': 891289851108929546, 'text_count': 891289852631453766, 'voice_count': 891289853726191626, 'tier': 891289855018008596}
well it shouldnt have the [guild] part
you would do self.serverstats.pop(guild)
i tried before some error came.



