#discord-bots
1 messages · Page 463 of 1
missing permission
share the whole traceback
@slate swan
The above exception was the direct cause of the following exception: above this
how can i give everyone a role, like mass role or smtng
for member in guild.members and add_roles(roleid) for each member.
oh ok
should i define guild?
or no
your bot will probably get rate limited
If it's where the command is used then ctx.guild.
you can use await asyincio.sleep() to get rid of this
Yes. So you can do await asyncio.sleep(3) after each member.
how to kick/ban/making invites in python?
https://google.com
https://youtube.com
https://discordpy.readthedocs.io
You can find answers in those.
dont, get ratelimitted, or take a long time
They can asyncio.sleep after each member.
dyno took 6+ hours for my 20k members server
use carlbot
yeah you can but i prefer using a throwaway bot for that
its better for mass roles
oh i forgot to mention, i used both of them
at the same time lol
It's not "better", it's just which one sleeps less, and how many members you have.
do i really need to type is at for member in guild.member?
Assuming there 20,000 member, and rate limit at 50 call per minute. That's 400 minute
That's bad especially if you want the bot to do stuff.
use multiple bots
like 10 of them communicating with each other to add role
for m in guild.members
You want to add_roles() for each member in the guild.members.
Python is just English in a snake way.
File "main.py", line 43
for member in guild.members
^
SyntaxError: invalid syntax
```
o
i forgot to remove s
Invalid syntax, learn Python.
carlbot better
make a botvar
they said bad lol
!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!
yeah sure man try adding roles to 21k people and not get ratelimited
use parallel processing for those type of commands @reef shell
multiple bots = more rates
what
idk about global rate limit tho
multiple bots??
why not
idk man , both of the bots maybe got rate limited, and took more time than ETA
isn't rate limit computed in a per bot basis?
the idea is just dumb

no its token based
||
How to cope with Alzheimer's disease
Step 1: Always write things done
Step 1: Always write things done
Step 1: Always write things done
Step 1: Always write things done
||
XD
well how are you exactly going to split the tasks
maybe shard based?
well first is with queue and threads
asyncio with threads is a big no go
Dyno has over a hundred shards.
who said i'm gonna use asyncio. use raw api
does anyone know how to make a play music command? I've tried so many times and still can't do it
which internally uses asyncio.open_connection
Play music?
ye
try youtube_dl
like rythm
it takes ages
its against tos
!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)
dpy handles rate-limits by default , doesn't it?
yeah you're right nvm then.
I used multiple bots for my music bot i just thing same idea would work
I want to make one
define music as music = DiscordUtils.Music()
there are ways to counteract ratelimits
and so on
Imo, you can set a maximum amount of members that the bot can purge add roles to. If the amount is more than the maximum, either return an error, or just do it with the maximum amount.
so you can have 5 active music at the same time in the same guild
why
there are tutorial at youtubes if im not mistaken
they all use yt_dl
so people can listen to music even tho the first bot is in use
that uses youtube_dl
mine isnt.
how
wait what
read source code
It's DiscordUtils tho
??
but thats the method I used anyways
it doesn’t matter
Even if it does not use youtube_dl specifically, it still takes content from YouTube in a way that breaks their ToS.
ytdl is usually against tos
technically discordutils uses youtube_dl too
Ok
youtube is just stupid, as they didn't say anything for years, but now they're making this shi
unfunny comment:
they're jealous
lol
it’s called copyright laws
nothing has been said for years
Copyright is a thing yk
yeah sure, let you use other people’s videos without their permissions
ye
youtube doesn't care usually
what
that apply to everything
yep
yes and groovy devs didn't want to pay fines
how long does Groovy exists and how many user use Groovy ?
well a spotify bot is ok then?
spotify doesn’t allow streaming
heh
nor any other platform

so music bots will never exist anymore on ds?
why do you even need music bots
it will still do. Many people will keep breaking laws. That' why there's pirated movies
😂
imo, they’re pointless
anyone want some while reading? 🍿
In the future if you want a music bot then make it your own and only for yourself.
correction.
make the song yourself
or
music bot with only non copyrighted music
Lmao
Yeah, screw programming, music producing is the future. Cars will use musical notes as fuel.
just use spotify :kekw:
what is this again
imagine music bot but only vlog musics on the background
People can instead make a bot that plays music only from No Copyright Sounds channel.
ye
i can probably make that tho
youtube has these for copyrighted contents
Check if this exist, then don't play
for m in guild.members:
await m.add_roles(role)
await asyncio.sleep(5)``` @dapper cobalt this?
incomplete traceback
Or "radio" bots that play music set by the developer of the bot so they can assure it doesn't break any copyright laws, and also it would be fun to listen to random music instead of having to keep setting certain songs.
Yes, that should do the job.
did you even read your own quetion?
by solving it
Your traceback is incomplete. Please provide whole traceback for debugging purposes
how about you send the error
this was your question right?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
```This is just half of the traceback.
Please provide the other half
@client.command()
async def mass_role(ctx):
guild = ctx.guild
role = discord.utils.get(ctx.guild.roles, name="role name")
for m in guild.members:
await m.add_roles(role)
await asyncio.sleep(3)``` @dapper cobalt funny how it only gave a role to a single member
@client.command()
async def mass_role(ctx):
guild = ctx.guild
role = discord.utils.get(ctx.guild.roles, name="role name")
async for m in guild.members:
await m.add_roles(role)
```try this instead
Use try...except so if it couldn't add roles to the other it would pass.
whats difference?
it's shorter
how can i check if a user have a role by if condition?
error
!d discord.AsyncIterator
class discord.AsyncIterator```
Represents the “AsyncIterator” concept. Note that no such class exists, it is purely abstract.
`async for x in y` Iterates over the contents of the async iterator.
Ignoring exception in command mass_role:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 37, in mass_role
async for m in guild.members:
TypeError: 'async for' requires an object with __aiter__ method, got list
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/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: TypeError: 'async for' requires an object with __aiter__ method, got list```
not sure ngl i followed this
where do u put except again ._.
@client.command()
async def mass_role(ctx):
guild = ctx.guild
role = discord.utils.get(ctx.guild.roles, name="role name")
for m in guild.members:
try:
await m.add_roles(role)
await asyncio.sleep(3)
except:
pass
```idk what error it produce so pass everythng
how i can check if a member have a role by if condition?
Get a role object of the role you want to check
Then check if that role is in user.roles
if (discord.utils.get(ctx.guild.roles, name="Muted") in member.roles):
embed = discord.Embed(color=0x000000)
embed.add_field(
name="\u26d4 Error!", value=f"<@!{member.id}> is already muted.", inline=False)
await ctx.send(embed=embed)
return```
May you not spoonfeed?
get_role(role_id)```
Returns a role with the given ID.
Then simply check if the role is in user.roles
why user?
if role in member.roles ??
Basic python ¯_(ツ)_/¯
It is correct
Just it's basic Python, so you should know that without really asking
No omg
This is like completely wrong
Hi!
So i'm trying to make an embed command and it gets a data from api and .txt file
And it's a lot of data that it gets and it's more than 4096 character
So is there's any way to make the bot send another message if the first message reached the limit aka 4096 character ?
No line is close to correct
Use pagination
is there's a lib for it ?
or it's discord.py lib built in ?
I believe it's built-in.
@bot.listen()
async def on_message(message):
if any(word in message.content.lower() for word in blacklist):
await message.delete()
await message.channel.send(f"{message.author.name}, Dat woord is niet toegestaan 😂 ")
I want It to see capitalized letters too, but they dont notice them.
So if the first page reached the limit the second page will continue sending the informations ?
now i understand thanks 
f"Channel overwrites successfully created in `{(len(ctx.guild.text_channels) + len(ctx.guild.voice_channels))}` channels, with `test` skipped channels."```
I want to make **test** become the channels not overwrited. How?
is on_member_join inbuilt command?
You can make a paginator
https://gist.github.com/Rashaad1268/3fcaaef6cc402b026ae09ac9fa6a173a
Not a command, but an event
oo that only i meant
r u italian?
@bot.listen()
async def on_message(message):
if any(word in message.content.lower() for word in blacklist):
await message.delete()
await message.channel.send(f"{message.author.name}, Dat woord is niet toegestaan 😂 ")
How can I make It recognize capital letters either?
It does already recognize capitals
But It doesnt recognize full capitals?
it recognizes the capital letters but makes them lowercase
Write your blacklisted words in lower case and works fine
helpppp
I have that rn but If I send one of the blacklisted words
Like I have hi blacklisted
If I send HI It ignores It.
It doesn't
message = "HI"
blacklist = ["hi"]
if any(word in message.lower() for word in blacklist):
print("yes")
Prints 'yes', which is exactly what you've described above
still not
it only give the role to itself
Do you have the members intent enabled?
what
Lol
how do I check if it's not a member?
example
kick vbkervbrv
bot: this is not a valid user
That will raise commands.MemberNotFound
Try using client.fetch_user
line 18
Nah
Ye
my real name is SIDDHANT
i changed it forreall
yea
oh lol i see
i thought no one kept their discord name as real name
yes :/
keep this chat focused on #discord-bots
kk
whats the problem?
There's an 'error' section, and it has already been answered I think?
what is leaderborad @slate swan
can you give me an example of that?
It got answered?
can you give me an example of that?
And what do you get when using fetch_user then?
i mean can you give me an example of how the dict looks like
i believe your using the wrong key/value in get_member
Your issue is that the user with the ID is not being found
Eventually print the ID you're gathering from the file
what commands will stop working after the discord slash command update?
look at where they define id_ and where they append to the dict
You won't be able to read message content, so all commands if your bot is verified
they have leaderboard[total_amount] = name,, where does leaderboard[amt] come from?
everything in the discord.ext.commands?
oh wow
Use slash commands
no documentations
Or eventually use the bot's mention as prefix, since bots will be able to read message contents from messages where they're mentioned
But it's a bad workaround
oh
probably the only
Or ask for the message intent
the on_message event will completely break, talk about leveling bots
If you have a use case
File "/home/container/bot.py", line 165
embed=discord.Embed(title="Poll!", description=vraag)
TabError: inconsistent use of tabs and spaces in indentation
But why?
no spaces
unless yk how much space a indention yas
That's not the issue
Oh tabs
I tried tabbing it and using spaces but both give me an error
File "D:\Discord Bot\ecrpgbot1-main\cogs\admin.py", line 67, in setname logChannel = self.bot.get_channel(id) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 793, in get_channel return self._connection.get_channel(id) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 1118, in get_channel pm = self._get_private_channel(id) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 329, in _get_private_channel value = self._private_channels[channel_id] TypeError: unhashable type: 'dict'
what is the problem here?
id is a dictionary rather than an integer @waxen granite
ah
guild = str(ctx.guild.id) try: id = self.guilddata[guild]["logs"] except KeyError: id = {} logChannel = self.bot.get_channel(id)
how to fix this?
The issue seems to be the KeyError section
id = {} is going to assign the id to an empty dictionary
I'd assume that if the id isn't already configured you'd either return (stop running the function) or use ctx.channel.id or something
hm
Guys, my bot turned off on heroku, is it normal ?
Yes
On website in resources it’s ON
Because Heroku is bad for hosting
Do you know what happened ?
Limited hours of uptime per month etc.
🤔🤔
But my friend said it’s for free always
You should not use Heroku to host your bot.
Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
Yes, it's free forever. But your bot won't be online forever, there's a difference
Hmhmhmhm
@slate swan which best hosting then ? Better free

No free hosting is good, simple answer
If you want a reliable and good hosting then pay the $2 per month or something
Haha, oke
if message.content.lower() == 'y':
print('working')
if message.content.lower() == 'n':
print('deleting..')
else:
while True:
print('moving back up to "working"')```
So what I'm trying to do is if the user does not type `y` or `n`, I'm trying to make the code go back up, and print `working` but it isn't doing that, anyone got any ideas?
someone help me with todo commands 😕 i'm confused
Show your current progress maybe
@slate swan which hosting do u use ?
We won't code for you
How does that matter?
Idk
Take the one you need
Just interesting
^^
# Todo
@commands.group(name="todo", help="Will tell you, your todo list", invoke_without_command=True)
async def todo(self, ctx):
await ctx.trigger_typing()
todo = await self.bot.db.fetch("SELECT task, position FROM todo WHERE user_id = $1", ctx.author.id)
if len(todo) == 0:
await ctx.send("You don't have a todo list\nTry to make one with `todo add` command")
else:
todombed = discord.Embed(
title="Here is your todo list",
)
todombed.description = "\n".join("{position}: {task}".format(**_) for _ in todo)
await ctx.send(embed=todombed)
# Add
@todo.command(name="add", help="Will add the given task", usage="<task>")
async def add(self, ctx, *, task):
await ctx.trigger_typing()
await self.bot.db.execute("INSERT INTO todo(user_id, task) VALUES ($1, $2)", ctx.author.id, task)
await ctx.send("Your task has been now added")```
the code is kinda fine, but the problem is, if 2 users does the todo add the number for their will be different
like
user#1:
2 - {task}
user#2:
1 - {task}
3 - {task}
the types for the columns btw:
user_id = Bigint
position = serial
task = text
And let me guess, position is auto incrementing
i think so
I am trying to make a calculator and when i try to press a button, it says, interaction failed, here is the current code
@client.command()
async def calc(ctx):
m = await ctx.send(content="Loading Calculator")
expression = "None"
delta = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
e = discord.Embed(title=f"{ctx.author.name}\'s calculator | {ctx.author.id}", description=expression, timestamp=delta)
await m.edit(components=buttons, embed=e)
while m.created_at < delta:
res = await client.wait_for("button_click")
if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
expression = res.message.embeds[0].description
if expression == "None" or expression == "An error Occurred":
expression = ""
if res.component.label == "Exit":
await res.respond(content="Calculator Closed", type=7)
break
elif res.component.label == "←":
expression = expression[:-1]
elif res.component.label == "Clear":
expression = None
elif res.component.label == "=":
expression = cal(expression)
else:
expression += res.component.label
f = discord.Embed(title=f"{res.author.name}\'s calculator | {res.author.id}", description=expression, timestamp=delta)
await res.respond(content=None, embed=f, component = buttons,
type=7)
Shoud go in #databases as this is more related to database questions though
i said i think so, because i don't know
i said what is the problem, and gave you the whole code
Nothing to do with the code
It's how you store the position integer
That is wrong
Maybe look how your database looks like and you will realize
wdym how it looks ?
Anyone?
Does discord.TextChannel raise error when channel is not found?
I meant if the mentioned channel does not exists, will it raise error
If so how can I modify it
It will be None?
Is it HTTPException ?
What are you trying
If that channel exists, send msg to that if that doesn't exist, send msg saying that channel does not exist
Then get the channel and it will be none if channel not found
Ok
Anyone can help?
wydm ??
hello,
uhh i am getting this error when i am trying to run a discord bot file
RuntimeError: Event loop is closed```
Without code, we can't really help
how i can change registered help command in discord.py :/
i just want to change the look when author type >help
but i want >help [command] of that
:/
:/
@steep estuary^
client = commands.Bot(command_prefix = '~', help_command=None)
```and this ?
@slate swan
Can anyone here help me changing code to cogs please ping me
why is the emoji not sent?
Hey @serene lynx!
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:
Is the bot in the server where the emote is?
how i can add link with a name in an embed?
text
Doesn't work in embed title, footer and field names
kk
i can use like this ```py
embed.add_field(name=name,value=Abcd\nLink,inline=False)
yeah, https though ^^
This makes me mad for some reason.
\:
why everyone say this to me when i use this ":/" :(
srry :(
https://
It's a little "childish" imo.
Anyways let's not go ot.
lol
btw i use ":/" to show that i am confused and also to give u respect :(
:/
lol srry nvm
Please tell me what's the problem in this code
Please ignore indentation
@bot.event
async def on_member_remove(member)
await member.send("xyz")```
error
```Ignoring exception in on_member_remove
Traceback (most recent call last):
File "C:\Users\GSSS OLWARA\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\GSSS OLWARA\Documents\Pikachu\cogs\welcome_leave.py", line 70, in on_member_remove
await member.send(f"Hope You Had A Good Time In {member.guild.name} {member.name}")
File "C:\Users\GSSS OLWARA\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\GSSS OLWARA\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
Read the last line of the error.
If the member doesn't share any servers with the bot, the bot won't be able to send them messages.
Tried to customise Jishaku
!d discord.Embed.title
The title of the embed. This can be set during initialisation.
Self explanatory lol
what is the difference between fetch_guild() and get_guild() ?
i'm using the latter one and it doesn't work the way i want
Fetching will send an API call to get an object from outside the bot's cache while getting will try to get it from the bot's cache.
mhm is it possible to refresh cache?
oh then i have to use the api call method :sad:
guys i want this command to work like that
+dm (user) (message) and it dms only me how can i do it
@bot.command()
async def dm(ctx, msg=None):
await ctx.author.send(msg)
Pass member before msg and type hint it with discord.Member.
you are not accepting the user in the args
like how can i do it
@bot.command()
async def dm(ctx, user: discord.Member, msg=None):
await user.send(msg)
¯_(ツ)_/¯
naming a Member object user 

is there's a way that pillow get image asset from a website ?
thanks
I have been summoned, altough it's on a weekend so i won't be on at that time lol.
@commands.cooldown(rate = 1, per = 5,type= BucketType.user)
use this command deco
and also import the BucketType
Can you give an example?
!d discord.ext.commands.cooldown
discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error") and the local error handler.
A command can only have a single cooldown.
How to set a message that its a cooldown and the command can be accessed agian in for example 2 minutes
!d discord.ext.commands.CommandOnCooldown
exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after)```
Exception raised when the command being invoked is on cooldown.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
front-end is either html,css,js or any framework of that.
||brython||

import discord
from discord.ext import commands
import BucketType
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
await ctx.send("test")
``` how long would this be for?
?
1 per 5 seconds
per user
what is the error
How to add an error message to it? Like You can only use this every 5 seconds. You need to wait 3 seconds more.
Did you try reading it?
This has already been answered -> #discord-bots message
i am swiching my bot to haruqu i am deleting my account
yes
Then?
ok one sec
I didnt uderstand that
This raises an exception commands.CommandOnCooldown
What you didn't understand?
!d discord.on_command_error
discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
"Improper token has been passed"
one sec i will tell you
bot.run('Improper token')
``` Now the error makes sense
discord.errors.LoginFailure: Improper token has been passed.
did you reply me
You can set a hyperlink in the title too.
Ignore that hehe
Do you know what improper means?
hmm
What do I explain in this? "Improper token has been passed"
It's self explanatory
Yeah invalid
Are you sure?
then how i improve my Improper token
Put in the right token???
yes
import discord
from discord.ext import commands
import BucketType
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
try:
await ctx.send("test")
except commands.CommabdOnCooldown(cooldown, retry_after):
await ctx.send(f"On cooldown! Use agian after: {retry_after} seconds.")
```?
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.
embed = discord.Embed(title='My Bot Invite Link', url='https://discord.com')
Oh url argument
no thats hyperlinks?
They're just mocking the error lol, not being serious
Kwarg*
I forgot about that, thought you meant that in []() format
Me too 😓
Is this how you use cooldowns?
ok.
¯_(ツ)_/¯
"improve my Improper token"
?? How can you improve it, just pass the valid token
I told you to use on_command_error
Where
no, because the error isnt being raised inside the function
mm
It's a listener.
import discord
from discord.ext import commands
import BucketType
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
await ctx.send("test")
@client.event
async def on_command_error(ctx, error: commands.CommandOnCooldown(cooldown, after)
await ctx.send(f"Can be used agian after {after} seconds.")
``` like this?
no bot.event or that ig both works
whats that typehint
Hi
So i was trying to use pillow to make a command and everything was working fine but now i've got an error
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/track.py", line 668, in add
data = BytesIO(await asset.read())
File "/home/container/.local/lib/python3.9/site-packages/PIL/Image.py", line 546, in __getattr__
raise AttributeError(name)
AttributeError: read
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/container/track.py", line 275, in on_command_error
raise error
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.9/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: read```
> This is the image code
```py
file = Image.open("trackeradd.png")
asset = Image.open(BytesIO(headreq.content))
draw = ImageDraw.Draw(file)
font = ImageFont.truetype("mc.ttf", 24)
draw.text((0,150), name, (0, 0, 0), font=font)
data = BytesIO(await asset.read())
head = Image.open(data)
head = head.resize((185, 185))
file.paste(head, (1241, 140))
file.save("added/added.png")```
This is not related to discord could you please open a help channel? #❓|how-to-get-help
it's related to discord
i'm using discord.py
Just because you are using it inside your discord bot doesn't automatically make it related to discord.
If I use client.event it will trigger on all cooldown errors? But not if I use @COMMAND.error it wont?
client.event is for all cd errors and @command.error are for command errors
Okay
on_command_error is meant to catch all discord related errors.
Your using another module inside discord.py trying to make a command?
So this would work?
wdym sorry
@commands.cooldown(1,5,type=BucketType.user)
``` I think?
only command errors
He has the same.
I defined it in (cooldown, after)
o
you havent defined it
Yeah obv 😋
import discord
from discord.ext import commands
import BucketType
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
await ctx.send("test")
@client.event
async def on_command_error(ctx, error: commands.CommandOnCooldown(cooldown, retry_after)
await ctx.send(f"Can be used agian after {retry_after} seconds.")
``` like this?
What
you can also just send the error without isinstance
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3.10/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3.10/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union).
It checks of an object is an instance of a class
@client.event
async def on_command_error(ctx, error):
error=discord.Embed(title='Error', description=error)
``` this mine :)
Yeah, but they want to handle CommandOnCooldown error
Who from Indian here .
use instance then
import discord
from discord.ext import commands
import BucketType
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
await ctx.send("test")
@client.event
async def on_command_error(ctx, error):
if isinstane(error, commands.CommandOnCooldown):
await ctx.send(f"Can be used agian after {error.retry_after} seconds.")
``` like this?
No
Whats wrong with that one
if isinstane(error, commands.CommandOnCooldown):
#handle it
Yea
I did so
I have (cooldown, after)
remove cooldown, retry_after from that line
But how to see how much time its left then
so it looks like this
do it on the next line
How
error.retry_after
Is this right?
yes
yep
Oh
Cool
Thanks!
Can I format the error.retry_after so it says in hours and minutes instead?
you're cooldown is in hours?
and sure you can do that
Hi. I have made my bot.py cooler, care to see it and help me improve it?
And check it, cuz idk if it works
uh
the imports...
oh god
need help
how do you make an anti-spam bot in discord.py?
are people still here?
bruh
other thn tht?
- Imports can be more cleaner
- Categorize them like inbuilt packages at starting, discord and pil ones at second block, and your bot's files at the last
- Just do
from Foo import bar, baz, idk, no need to separate them in separate lines.
- For data which needs to be accessed very frequently (like prefix), it's good to cache it instead calling Database on every event
bot.remove_command('help')....- Some line spacing
- Instead of overwriting events, I prefer to use listeners, but doesn't really matter much
- PEP8 👀
Isn't tinydb just json?
yes
yep
You read that very quick
i didnt get that
Use pg_orm instead
how to cache?Im using a vps btw
?
hello pls help me
tinydb is json? 
+- JSON is not a DB
You can use that module for anti spam
how do you make an anti-spam bot pls
where am i overwriting events? and wht is pep8
that is a module i made
Cache means storing your stuff in variables, like a = 1 is also cache technically
!pep8
an ORM for postgres
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
oh alr
he gave u wht u want
i dont understand it
but everything else should work right? Nothing wrong... Also how is it
but im using different prefixes
store them in dict
gah just scroll up
there are million ways to cache
why? Its easier to store in json right?
and more efficient
Ah I think you didn't get what is cache.
No, it's like 30min
ye, thats how cache works
Is there an easy way?
Thanks
https://en.wikipedia.org/wiki/Cache_(computing)
https://realpython.com/lru-cache-python/#caching-and-its-uses (the para which I linked in particular)
but i dont want tht.. Im happy with current way of storing
k
How to make click text?
?/
how to make anti-spam bot in discord.py
how do you make an anti-spam bot in discord.py pls
Btw, is it possible to cache your main app stuff in cython?
pls
pls
pls
pls
lol
lol
lol
is there a way to make link look like smth else, go somewhere else
idk tbh
idk tbh
idk tbh
idk tbh
😦
just help me
just help us
pip install git+https://github.com/Pycord-Development/pycord
i installed this how do i uninstall it pls help
should i just do pip uninstall pycord?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API

pretty pls
imma go nobodys being helpful
me too
how do i uninstall a git repo setup?
agreed
How to make click text? Like click on text and it becomes a link
just pip uninstall <package>?
how to make anti-spam bot in discord.py
bruh, i sent a link to a project, check it
i didnt understand it
https://stackoverflow.com/questions/64961125/building-a-discord-antispam-bot-and-getting-errors i just searched a random thing up, try look at what they are doing in the answer to the question
Please put your efforts to read it atleast, what you didn't understand?
k thx ill try
So i have a discord bot, where im plotting some data of my bot on a graph. problem is, its deployed on a vps. How can i see the graph live on my pc?
Matplotlib?
Make the bot send the graph
i didnt work guys
oh wait theres error
Traceback (most recent call last):
File "C:\Users\*\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\*\Documents\Stuuf\botol.py", line 30, in on_message
if authors[author_id] > 5:
KeyError: 881537676094881793
that key doesnt exist
how do you know
i didnt send a stackoverflow link
https://pypi.org/project/Discord-Anti-Spam/
It has an example for a basic bot
The error is exactly same as the user who asked that question on sof
with pip install antispam
ok but i nstalled and got error
from antispam import AntiSpamHandler
ImportError: cannot import name 'AntiSpamHandler' from 'antispam' (C:\Users\*\AppData\Local\Programs\Python\Python39\lib\site-packages\antispam\__init__.py)
[Finished in 817ms]
hello
do you knwo answer
Anyone?
try py from discord.ext.antispam import AntiSpamHandler
Did you install it properly?
How did you install it
bruh
wat
thats not the proper package name
whats it called
the instructions are right there in the web site
k i did it
is there something wrong with this
@client.command()
async def sue(ctx, member : discord.Member):
money = random.randrange(50001)
description = [f"You took {member.mention} to court and sued hime of {money}",
f"You took {member.mention} to court but the judge found no dirt on him lol"]
ok = random.choice(description)
beddy = discord.Embed(title=f"Attempting to Sue {member}...", description=f"{ok}", color = discord.Colour.purple())
await ctx.send(embed=beddy)
hello?
@lament mesa
@client.command(aliases=['tm'])
async def tempmute(ctx, member: discord.Member, time: Union[int, str] = 0, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
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} has been tempmuted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
embed.add_field(name="time left for the mute:", value=f"{time}{0}", inline=False)
await ctx.send(embed=embed)
if 0 == "s":
await asyncio.sleep(time)
if 0 == "m":
await asyncio.sleep(time*60)
if 0 == "h":
await asyncio.sleep(time*60*60)
if 0 == "d":
await asyncio.sleep(time*60*60*24)
await member.remove_roles(mutedRole)
return```
is there something wrong?
it is not adding muted role to the member 😦
Seems like a jsk bug as long as u didn't subclass/changed its internals lol
Nah I had to do bot=bot in CustomJishaku(), as it's a kwarg
Ah, ok
Wym?
with bot I can do ```python
async def close(self) -> None:
print(f"[EXIT ] Shutting down...")
await super().close()
.
!d discord.ext.commands.Cog.cog_unload
cog_unload()```
A special method that is called when the cog gets removed.
This function **cannot** be a coroutine. It must be a regular function.
Subclasses must replace this if they want special unloading behaviour.
Hi guys, can the bot accept attachments sent to it? For example pictures
My code:
@bot.listen("on_message")
async def log_message(message):
channel = bot.get_channel(bot_msg_log_channel)
if message.guild is None and not message.author.bot:
embed = discord.Embed(
description = f'Author: {message.author.mention}\n\n'f'Msg:\n'f'{message.content}',
color = 0x0068c9
)
embed.set_thumbnail(url=message.author.avatar_url)
await channel.send(embed=embed)
But if they send a picture or something attachment, just an empty message comes
!d discord.Message.attachments
A list of attachments given to a message.
for msg sender would it be ctx.author.message?
but that shows the author
not his msg
like
seatch : hi
ctx.message.author = seatch
hi = ?
@lament mesa any clue mate?
if you want to get the message it will be ctx.message
ah ok thanks
Oh
@lament mesa is there something wrong
the integer 0 will never be equal to a string
Thank you
@client.command(name = "exp")
async def exp(ctx,user : discord.User = None):
if ctx.author.bot:
return
elif not user:
abc = ctx.author.id
cursor = levelsystem.cursor()
cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
result = cursor.fetchall()
currentxp = result[0][0]
await ctx.message.reply(f"{ctx.message.author.display_name}#{ctx.message.author.discriminator} Has {currentxp} XP !")
else:
abc = user.id
cursor = levelsystem.cursor()
cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
result = cursor.fetchall()
currentxp = result[0][0]
await ctx.message.reply(f"{user.display_name}#{user.discriminator} Has {currentxp} XP !")
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "exp" is not found
why
although i change the code into pass and the result is same
@client.command()
async def get_author(ctx, msg_id: int):
msg = await ctx.channel.get_message(msg_id)
await ctx.send("The author is %s" % msg.author)```Alternative or no ?
how to make bot reply like this
Except 0 i should use 1 ??
channel.get_message isnt a thing 
Tatti bot 😂
Integers will never be equal to a string 
u know hindi ??
Yez i m indian
llol my friend was telling my bot bad and telling that dank is better so i named it that
if msg.content.startswith('abcidc'):
channel = message.channel
await channel.send('Enter the news')```
this should work in on_message event right?
yes
So what to do ?
then why isnt it ._.
what are you typing?
U want a message which can be only seen by that user
yes and with that color
Making tempmute command
File "C:\Users\HP\Desktop\dc bot\main.py", line 33, in on_message
channel = message.channel
AttributeError: module 'discord.message' has no attribute 'channel'
!e py print(0 == "s")
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
False
I think
message.reply
But how can i do
channel.fetch_message
Hmm
anyone?
@client.command()
async def hello(ctx):
pass
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "hello" is not found
what
Hello is not any command
is it in a cog?
why
but i want that blue color
is msg what you put?
If you did
@bot.event
async def on_message(msg)```
then you need `msg.channel`
np
its a empheral message
Bcoz it is a custom command
no i tried to add some codes into it but it not work
What were the codes ??🤨
await ctx.send("OK")
!paste <-- put your full code here please
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
how to make that :/
idk never messed around with it
!paste
@client.command()
async def hello(ctx):
await ctx.send("OK")
try checking the docs
it not work
what
Ig it is right
no
Hmm
async def on_message is an event
that is not correct
I m new
no i add my prefix
Lmao noo
restated your bot?
i tried
you must pass message instead of 'hello'
also its a command
don't use that on_message for commands anyway
is it in a cog?
i dont need it
f my nitro ended
only gonna say this: https://vcokltfre.dev/
bre
just add extra in client.run right
client.run is suppose to be in the bottom of the code after everything else
not before the command
heh?
So im using praw to get posts from a subreddit, and i always get this prompt when someone uses the command. now, i did try to move to asyncpraw as its faster, but i was getting a few errors, so i moved back to praw, and i dont want this to show in the terminal:
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.```
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.login "discord.Client.login").
Roughly Equivalent to...
A blocking call that abstracts away the event loop initialisation from you.
then use asyncpraw
im gonna move to it later, but for now i just want to stick to praw
def generateXP():
return random.randint(1,5)
@client.listen('on_message')
async def on_message(message):
if message.author.bot:
return
elif message.content.lower() == "!exp":
pass
else:
xp = generateXP()
cursor = levelsystem.cursor()
cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = " + str(message.author.id))
result = cursor.fetchall()
if (len(result)) == 0:
cursor.execute("INSERT INTO levelsystem VALUES(" + str(message.author.id) + "," + str(xp) + ")")
levelsystem.commit()
await message.reply("Done")
else:
newXP = result[0][0] + xp
cursor.execute("UPDATE levelsystem SET userxp = " + str(newXP) + " WHERE client_id = " + str(message.author.id))
levelsystem.commit()
await message.reply("Done")
@client.command()
async def exp(ctx,user : discord.User = None):
if not user:
abc = ctx.author.id
cursor = levelsystem.cursor()
cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
result = cursor.fetchall()
currentxp = result[0][0]
await ctx.message.reply(f"{ctx.message.author.display_name}#{ctx.message.author.discriminator} Has {currentxp} XP !")
else:
abc = user.id
cursor = levelsystem.cursor()
cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
result = cursor.fetchall()
currentxp = result[0][0]
await ctx.message.reply(f"{user.display_name}#{user.discriminator} Has {currentxp} XP !")
it recognized !exp as in on_message
why are you using on_message as a command
try putting print('works') before and after everything you do in the command you can find out where it gone wrong
no
@client.command(aliases=['ac'])
async def announce(ctx, message):
embed = discord.Embed(
title = '',
description = '',
colour = ctx.author.colour
)
embed.set_footer(text='By oSeatch#6969')
embed.set_author(name=ctx.message.author)
embed.add_field(name='News', value=message , inline=False)
await ctx.send(embed=embed)
await ctx.message.delete()```
Im trying to make it embed the msg after the command so in
.announce `hi this is test`
This is a test should be embedded, i still dont get how i can do this though..
im always scrolling in here and see that i always ask for the most easiest stuff, other's people stuff so hard smh ._.
maybe this?
@client.command(aliases=['ac'])
async def announce(ctx, message):
embed = discord.Embed(
colour = ctx.author.colour
)
embed.set_footer(text='By oSeatch#6969')
embed.set_author(name=ctx.message.author)
embed.add_field(name='News', value=message , inline=False)
await ctx.send(embed=embed)
await ctx.message.delete()
doesn't hurt trying
what are you trying to do?
idk why your deleting the message right after it sends it
ik wrong reply
help, the variable currentxp in exp command didnt return anything
poggerss it works, thanks alot man
try printing currentxp?
i think it was because there was an error in the other part of the code
it not return anything
so that means my original code might work too ._.
Its because discord requires a title and description if you add the option, if you don't want those remove them rather then using empty strings
i think it was because of the title = '' and description = ''
im using cogs and so the cog reloading commands..can such command be used for a json file ???
@client.command()
async def purge(ctx, amount=5):
if (not ctx.author.guild_permissions.manage_messages):
await ctx.message.delete()
await ctx.send("This Command Requires A Higher Rank!")
return
if (ctx.author.guild_permissions.manage_messages):
await ctx.channel.purge(limit=amount)
await ctx.send(f"__**{amount}**__ messages have been removed.")
await ctx.message.delete()```
Here's my normal purge code, yeye everyone has it, simple stuff- now how can i make it so that after like 5 seconds of sending "Amount of messages have been removed" it get auto deleted, is it even possible?
na
i added it back and it worked
send the message after await ctx.message.delete()
the problem was that i made a mistake in the code and left broken code in there, that just didnt allow the rest of the code to work
okok
i would suggest to add +1 to the amount
In ctx.send it has a delete_after kwarg, you pass in 5 and after 5 seconds it gets removed
!d discord.abc.Messageable.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.
*the message gets deleted
git gud
shhh python the lang is typing 
bad helper
thats what i want it to do..

like "Message has been deleted", stays there for 5 seconds and gets deleted
that :| face reminds me of a certain cat
await ctx.send(f"__**{amount}**__ messages have been removed.", delete_after=5)

?? how can i reload json files
i dont think json files can be reloaded
ic thanko
np
what is reloading a file 
Write -> Save -> Load
as for this, in amount=5 or limit=amount?
Hello everyone, I am trying to use slash commands but I am not able to, it just simply dosent show there. The normal command works fine, heres the code so can someone point out what wrong thing I did or how to fix the issue?
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
from discord_slash import SlashCommand
load_dotenv('.env')
client = commands.Bot(command_prefix="sw:", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
@client.event
async def on_ready():
print(f"Bot activated.")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="sw:help"))
@client.command(description="Sends bot's latency")
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(client.latency, 1)))
@slash.slash(name="Ping", description="Sends bot's latency")
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(client.latency, 1)))
client.run(os.getenv("TOKEN"))
ok so like the code using the json file if i reload it would it use the newly written json file or the old one only
You might mean appending to the json file
Guys, i am trying to make a calculator, but when i click on a button, it says, interaction failed, Here is my current code
@client.command()
async def calc(ctx):
m = await ctx.send(content="Loading Calculator")
expression = "None"
delta = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
e = discord.Embed(title=f"{ctx.author.name}\'s calculator | {ctx.author.id}", description=expression, timestamp=delta)
await m.edit(components=buttons, embed=e)
while m.created_at < delta:
res = await client.wait_for("button_click")
if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
expression = res.message.embeds[0].description
if expression == "None" or expression == "An error Occurred":
expression = ""
if res.component.label == "Exit":
await res.respond(content="Calculator Closed", type=7)
break
elif res.component.label == "←":
expression = expression[:-1]
elif res.component.label == "Clear":
expression = None
elif res.component.label == "=":
expression = cal(expression)
else:
expression += res.component.label
f = discord.Embed(title=f"{res.author.name}\'s calculator | {res.author.id}", description=expression, timestamp=delta)
await res.respond(content=None, embed=f, component = buttons,
type=7)
the full error message and line number it occured at?
yep
and like using the newly appened json file
Are you making a copy of the json file and appending it there? just using it again will solve it
it just says, 'interaction failed' when i click a button
any error in your shell?
i think u have to enable an option when you invite the bot to your server
nope
await ctx.send(f"__**{amount}**__ messages have been removed.", delete_after=300) umm this just doesn't show the msg has been removed anymore..
ummm? Like mee6?
so i want it to show
"messages have been deleted"
and it stays there for 5 seconds, and gets deleted
okayy, so first of all you purge the number of messages, then u send blah blah blah
then:
how do i send a looped message to users in a json file ??
import asyncio
@bot.command()
async def clear(ctx, messages):
await ctx.channel.purge(limit=int(messages))
await ctx.send(f"{messages} have been deleted!"
await asyncio.sleep(5)
await ctx.channel.purge(limit=1)
oh so u re-purge it
ye
but if someone sends another msg
I think he wants to use the delete after property instead
then it will just purge their msg
that can be a problem, i see
yes
dude...i send u the code for it..
didnt work
whats the error
can u wait for a minute
then ? what do u need ?
.
and thats what the code does..
sadness i try once more
its 300 seconds..
ok wait
😑
lol
u wanna delete the msg but no auto delete...
bruh i seriously.. it worked

lol
i put it in this format thats why it didnt work
You have my last respects
takin' it with me to heaven
scratch that, i wanna check out hell first
kk
hi guys how can i mention channel with bot ?
<#channelid>
why so many indians
Bcoz india is best
is there an api for new post reddit events?
i normally just use the raw json for reddit but i couldnt automate this my self for new post i dont think
How would I make a command that sends how many times a certain word was said in a server
I'm guessing I would have to use on_message
I just have no idea how I would implement that with a command
The origin of programming and computers was in India.
