#discord-bots
1 messages · Page 794 of 1
My code just stopped working?
This worked fine yesterday?
is there a bot event to check if being ratelimited?
Im pretty new to python and Im just watching this video right now, https://www.youtube.com/watch?v=wjQ9Nin21d8&list=LL&index=53 and when he begins to code it sounds like you have to include that little line of code in order for the bot to even function
Understand how to code a discord bot without spending an hour watching a tutorial. Our goal is to cut all the fat from learning and allow you to move onto bigger and better things!
After this python tutorial you will be able to create a custom discord bot from scratch. In this video we will cover responding to message events and creating bot c...
He says to use on_ready but what is @discord.Client().event?
thats never used...
what does bot.reload() do? does it need parentheses
uh
uhhhh wut
who uses the class to make the decorator?
import discord
client = discord.Client()```
not a thing
i did it myself cause I just didnt set the discord.Client to a variable; i did it a lot in lua, does stuff like that not work properly in python?
@quaint epoch
i guess it isn't documented
no but look
brb
disnake..
What happened
well you need a class so you know which cog to reload
!d disnake.ext.commands.Bot.reload
Whether to enable automatic extension reloading on file modification for debugging. Whenever you save an extension with reloading enabled the file will be automatically reloaded for you so you do not have to reload the extension manually. Defaults to False
New in version 2.1.
no, just bot.reload() no args
^
alr
!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)
Can anyone explain to me why these commands aren't working?
from discord.utils import get
TOKEN = ''
client = commands.Bot(command_prefix="?")
@client.command()
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice is not None:
return await voice.move_to(channel)
await channel.connect()
await ctx.send(f"Joined {channel}")
@client.command()
async def leave(ctx):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
print(f"The bot has left {channel}")
await ctx.send(f"Left {channel}")
else:
print("Bot is not in a vc")
await ctx.send("I am not in a vc")
client.run(TOKEN)```
Btw if I make a project like discord bot then do you guys recommend buying another domain for it's website? Or use subdomain in the main website? By main website I mean like "supercell" created "clash of clans" so the game is a subdirectory of supercell.com
That's honestly whatever you want to do
But buying another domain seems useless to me since you can advertise the main website and the bot website with a subdomain instead
!d disnake.Member.voice
property voice: Optional[disnake.member.VoiceState]```
Returns the member’s current voice state.
Are there any errors?
Saying that they aren't working doesn't help anyone
Okay 👍
No errors, just that when you call them like this "?join" they don't respond
Do you have an on_command_error or on_message event?
uhh yes
Should I send the full code?
if u have on_message event thats what causes no command uwuwuwuw
process_commands(message) will fix that up, that or you can use a listener instead
Ignoring exception in command userinfo:
Traceback (most recent call last):
File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\rebellion\Desktop\cult\cogs\utility.py", line 33, in userinfo
await ctx.send(embed=e)
File "C:\Users\rebellion\anaconda3\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\rebellion\anaconda3\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.2.value: This field is required
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\rebellion\anaconda3\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: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.2.value: This field is required
code:
@commands.command(aliases=['ui'])
async def userinfo(self, ctx, member: discord.Member = None):
member = ctx.author if member is None else member
roles_string = ', '.join([r.mention for r in reversed(member.roles[1:])])
permissions_string = ', '.join([str(p[0]).replace("_", " ").title() for p in member.guild_permissions if p[1]])
e = discord.Embed(
timestamp=datetime.utcnow(),
color=0x99FFFF,
description=member.mention
)
e.set_thumbnail(url=member.avatar_url)
e.add_field(name=f'Joined', value=member.joined_at.__format__('%a, %b %d, %Y %I:%M %p '))
e.add_field(name=f'Registered', value=member.created_at.__format__('%a, %b %d, %Y %I:%M %p '))
e.add_field(name=f'Roles [{len(member.roles[1:])}]', value=roles_string, inline=False)
e.add_field(name=f'Key Permissions', value=permissions_string, inline=False)
e.set_footer(text=f'ID: {member.id}')
e.set_author(icon_url=member.avatar_url, name=member)
await ctx.send(embed=e)
for some reason it's giving me an error on sending even though it's supposed to work
anyone got an idea?
You'd need a persistent data storage for that, It's very likely there will be some downtime within the time-frame
Your task would restart back to the start unless otherwise made to work persistently
You could store it as a unix timestamp somewhere (preferably in a database) and if the bot restarts, you can figure out how much longer until you have to remind them
Probably a more efficient way to do it though
Robin im loving the new drip
haha, thanks just got it :D
you deserve it my man
Thanks! Had a really warm welcome 😄
love to hear it
That's more of a problem due to the way Python is built. It's difficult to statically analyze classes due to the nature of Python.
how to ban someone with request to discord api?
discord.Member objects have a .ban() coroutine
Yep, tasks would be the right choice here
i dont want to ban with it it is slower ban idk why nukers bypasses it's ban spd i need more speed for my antinuke anti ban and ban then fast before they could ban someone else
i want to use aiohttpx btw dk how to
isnt it slow for a reason?
You can
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
start = datetime.now().timestamp()
reason = "R Anti-Nuke | Banning Members"
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.datetime.now().timestamp() - start), 3)
log = await r.text()
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
c = self.bot.get_channel(892973735802449943)
await c.send(f"Banned %s, took: {took}" % (user))
else:
logging.error(f"Could not ban %s" % (user))```
bro idk i was using this btw it is not working now i dk why
youre gonna get flagged as a nuker prob
bans are slow because there dynamic iirc andy knows
@slate swani am asking about this
Congrats!
:D Thanks!
no btw my frnd made darkz sec and it uses aiohttpx and it bans nuker faster
than mine @slate swan
Be careful with things like these, also add a little bit of a sleep so you don't get ratelimited
thats the thing youre banning to fast
bro why rate limited? just 1 ban
use the coro then?
how did my frnd bot do it then
Not for one ban, but for many more members you can get ratelimited
how to
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
Same as you normally would
wut
i think you replied to the wrong msg andy?
I did
lol
i just use normal antiban btwjust wanted to make it faster any how
@commands.Cog.listener()
async def on_member_ban(self, guild, member):
if self.db.find_one({ "guild_id": guild.id })['toggled'] == True:
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
reason = "R- DYNAMIC PROTECTION | ANTI BAN"
whitelisted = self.db.find_one({ "guild_id": guild.id })['whitelisted']
if logs.user.id in whitelisted:
return
punishment = self.db.find_one({ "guild_id": guild.id })['punishment']
if punishment == 'ban':
try:
await logs.user.ban(reason=f"{reason}")
return
except:
pass
if punishment == 'kick':
try:
await logs.user.kick(reason=f"{reason}")
return
except:
pass``` i just used to use this btw this is not faster how to make it faster ? allacrity named nukers bypasses my bot and does 50 bans btw on my frnd's bot it performs only 8 bans and get banned
?
you cant make it faster
the api wrapper must handle the ratelimits so it handles it so you wont get ratelimited if you request it directly to the endpoint you will just get ratelimited if you ban many members
ok btw for that they have a backup i think so cuz if my bot stops them at 8 bans then it wont cause rate limit i think so instead of 50 bans
@slate swan
why the ping
and my frnd gave me this
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
start = datetime.now().timestamp()
reason = "R Anti-Nuke | Banning Members"
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.datetime.now().timestamp() - start), 3)
log = await r.text()
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
c = self.bot.get_channel(892973735802449943)
await c.send(f"Banned %s, took: {took}" % (user))
else:
logging.error(f"Could not ban %s" % (user))```
btw this used to work before not now 😦
sorry
just use the coro tbh why make a request to the endpoint
is coro faster than it?
no but it wont ratelimit you?
theirs a reason why the wrapper manages the request
lmao does discord rate limits verified bots too?
yes but they have bigger caps
ok btw tell me is discord v9 api notworking or wott
why wouldnt it
ratelimits are dynamic
ooo
If ur using pymongo I think u should use motor
No, a coro is just an easier way to make a request to the endpoint
The code also looks much cleaner & easier to understand
async def on_member_join(ctx, member: discord.Member):
logchannel = client.get_channel(911702069839294516)
embed = discord.Embed(title=member.name, description=member.mention, color=discord.Colour.red())
embed.add_field(name="ID", value=member.id, inline=True)
embed.add_field(name="member joined on ", value=member.joined_at, inline=True)
await logchannel.send(embed=embed)``` this will not work doesn't send an error just doesn't work on insight on why would be appreciated.
How does it "just not work"?
Is it picking up the event? (a print statement inside would help)
You need member intents for this event to be dispatched to your client
Do you have it?
let me check
!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.
should look like this
letme try wait
have intents
and the event doesnt take 2 arguments
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
ah yeah that's probably why
what is the best discord python? discord.py nextcord or something else?
good catch didn't see that
you mean api wrapper for the discord api?
thanks
it's subjective, people will tell you their favourite fork. find out what you like best and use it
prob hikari
and don't feel pressured to use a fork, even as a verified bot you can get by with updating d.py yourself with the newest features
some verified bots still use 1.7.3 or main branch
if you have message intents
yup
if you get it
or use the bot's mention as prefix lol
I don't think we can help with that, since you can easily repurpose it to spam someone else's DMs
how?
doesnt the bot need to fine <@itsid>? in the content of the msg?
commands.when_mentioned
And you get all message properties if you are.mentioned in the message
ah yeah good point
That's the point, if the bot is mentioned in the message, it gets the content
get_user is not a coroutine, you do not await it. and get_user won't work as tasks start before the cache is populated. You need to wait for the cache
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
You also don't need to create the DM yourself, just use the send method
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
Note, get_user is not a coroutine like I said above
do discord bots get banned a lot?
Only if you break the TOS
like do they give warning before banning it or do will they IP ban me from discord
Does print(f"{bot_settings['name']} - {bot_settings['version']}: All logs posted to relevant guilds.") run? It could be that asyncio.wait hasn't finished unblocking
Does it print the second time around?
Yes prints the second time around too. This is whats confusing me
if guild.id not in server_settings:
continue # no settings for this guild, skip to next one
```? Maybe this? Not sure
Not sure, haven't had any bots banned. You'll probably have to go looking around their site to find it
After some de-bugging im thinking its maybe something to do with the SQL as ive put prints inside the functions and they print too?
You can try 🫂
i'm not doing anything malicious just that, like people might report my bot just to troll me
Don't have to worry about that
i'm not breaking TOS but i don't want to suffer some extreme consequence for as punishment for making a bot
False bans are rare and I'm sure discord will help you get it sorted
thanks
Start the loop?
Or maybe the get_user retuurns none
Or the user isnt in any server with the bot
If that were the case we'd have a NoneType has no send() method exception or something along those lines
Is that the case?
Error handlers may eat up those
Hoping we don't have bad error handlers yes
Did you start the loop?
Where are you starting it from? __init__?
You are passing self to the method, so to me it seems like it's bound to a class. But when you call .start it isn't from a class?
If it's bound to a class you need to do instance.reminders_message.start()
Doing it from __init__ is probably the easiest but it would work from anywhere within that class really
instance is a generic variable name, the instance you use is the instance of your class, or in this case Cog
which lib for bots we are following here
__init__ will provide you with self
Actually any non-static or classmethods should do that which is why I said you can start the loop from anywhere in the class
Are there any good discord API wrappers for python that are being actively maintained?
Any of them which are written for python usage
Are all of the libs forks of dpy?
No oof
Two of the popular forks are, disnake and nextcord
Others are made completely from scratch
Like hikari
Nope, there are libraries that are sort of contesters of d.py you could say
Eh, why did people say its not ;-;
Oh ooof
i guess it was pycord ;-;
What would be faster and more efficient:
Saving server settings into .json or in a sqlite3 db?
Or even mongodb?
I currently have .json files for small stuff and a sqlite3 db for some settings (blacklist/whitelist f.e.).
And how could I be sure that my db is secure enough? I know of SQL injection and how to prevent it on inserting data into the db, but I also want to make a web dashboard now and maybe open my bot up for public usage
yes
Pycord is a fork of discord.py
Always suggest sqlite
.json is usually more suited for static data like configs and whatnot
So I role on join one role do I need to make multiple role on join events or can I combine them into one? With comas? Something like this many in one event? List: @❗️Server Notify @✨ Highlights Ping @📩 Vote ping @🤝 Partners Ping @🙋♂️he/him @🙋♀️she/her @👫they/them @🙋♂️👫he/they @🙋♀️👫she/they @🕹Gamer @😂Meme Master @🎻Musician and @🎨Artist
If you're planning on growing your bot, id recommend starting off with something like postgres instead of having to rewrite later
Sorry what?
Are you asking for help with something or?
I think if you're asking can you assign multiple roles at once, member.add_roles() can be used, and you can pass in a list of snowflake objects
Yes for smaller bots, consider switched to a more heavy-duty database I guess you could say, such as PostgreSQL later on as your needs grow
@vocal snow @sick birch Thanks to both of you ^^
ghost message?
yea
I got 0 idea of what your question meant
yea that what i ment let me get ya code
i did this witch i think i did way wrong py @commands.Cog.listener async def on_member_join(self, member: discord.member): role = member.guild.get_role(904216437399355402) await member.add_roles(role)
do i just do this? ```py
@commands.Cog.listener
async def on_member_join(self, member: discord.member):
role = member.guild.get_role(904216437399355402,role2, role3, role4, role5, role6, role7, role8, role9, role10)
await member.add_roles(role)``` ???
how do you attach a file into the bot's message
.send() has a file kwarg
why do i get this error
Command raised an exception: IsADirectoryError: [Errno 21] Is a directory: 'images/'
im trying to upload a file to a msg
whats your code
its kinda long but ill show the important part
elif taiwan_q.content.lower() == "n":
await ctx.send("you passed that question, next question")
await asyncio.sleep(0.5)
await ctx.send(
"is this dwayne the rock johnson? (y/n)",
file=disnake.File(fp = "images/",filename="thewok.jpeg"),
)
thewok_q = await self.bot.wait_for(
event="message", timeout=60.0, check=check
)
you are using disnake?
mhm
I never used it 🤷dont know how I could help ya here
whats disnake.file do
It's the same as dpy, this error would occur in dpy too
fp means filepath, you need to add the thewok.jpeg after images/, not at filename
this just means that its a directory not a file
oh so i swapped it
Mhm
@fast vortex i got a Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'thewok.jpeg' even tho the file exists
Full path
is the file in the same directory/folder?
this
images/thewok.jpeg
in which arg should i put that in lol
Fp
fp?
anyone know how I could host my bot?
Mhm
Vps
I know, but like I have 0 clue how to set it up
Here are some good ones
Watch a yt tutorial
those are just sites, not how to set it up
A tutorial on how to set it up using the service you choose from those sites
hmm why do i get this error (picture) code: py @commands.Cog.listener() async def on_member_join(self, member): if member.guild.id == 902404450432483378 : return role1 = member.guild.get_role(933104091066941530) role2 = member.guild.get_role(936481481113632839) role3 = member.guild.get_role(936712347211419708) role4 = member.guild.get_role(936712664950931476) role5 = member.guild.get_role(842254098266718219) role6 = member.guild.get_role(842253873376264222) role7 = member.guild.get_role(842254463309316136) role8 = member.guild.get_role(842260259417489448) role9 = member.guild.get_role(842260429044842572) role10 = member.guild.get_role(893308041699680337) role11 = member.guild.get_role(816838497159610369) role12 = member.guild.get_role(826636738306506794) role13 = member.guild.get_role(841144860966125568) roles = [role1, role2, role3, role4, role5, role6, role7, role8, role9, role10, role11, role12, role13] await member.add_roles(roles)
No documentation found for the requested symbol.
!d discord.InteractionResponse.defer put this inside the button if you aren't sending anything @cedar smelt
await defer(*, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
!d discord.Interaction.response use this to get the InteractionResponse class
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
@echo wasp
thank you
Or that, yea
why is that class in your function
!e
a = 1
def foo():
b = a
b = 2
foo()
print(a)
@visual island :white_check_mark: Your eval job has completed with return code 0.
1
!e
a = 1
def foo():
b = a
b += 2
foo()
print(a)
move it xd
Oh, nvm
Is there a way my bot can store discord member nickname in a variable who just use call the bot?
So when i was working on my bot i added a new command to the main file i am running it twice and neither of the welcome messages work without an error in the console the leave message is the expect same except it does on member remove instead of join so why is it happening and how do i fix it i never even messed with it and didn't mess with perms either.
Thats storing my username but i want to store the nickname
@commands.Cog.listener()
async def on_member_join(self, member: discord.member):
if member.guild.id == 902404450432483378 : return
channels = member.guild.channels
for channel in channels:
if ('welcome' in channel.name.lower()) or ('joins' in channel.name.lower()): #or ('testing' in channel.name)
await channel.send(f"A new soldier named, {member.mention} , has joined **Bro's SMP War!** Make sure to check out [#806264072454537267](/guild/267624335836053506/channel/806264072454537267/) and [#899440312223662121](/guild/267624335836053506/channel/899440312223662121/) first before doing anything else.")
@commands.Cog.listener()
async def on_member_remove(self, member: discord.member):
if member.guild.id == 902404450432483378 : return
channels = member.guild.channels
for channel in channels:
if ('leave' in channel.name.lower()) or ('goodbye' in channel.name.lower()) or ('graveyard' in channel.name.lower()):
if isinstance(channel, discord.TextChannel):
await channel.send(f"**{member}** left the server because they suck :+1:")
how to add a cooldown on a command
ctx.author.nick
Tnx man
Cooldown decorator, look docs
A dictionary representing the images and their hover text of an activity. It contains the following optional keys:
• large_image: A string representing the ID for the large image asset.
• large_text: A string representing the text when hovering over the large image asset.
• small_image: A string representing the ID for the small image asset.
• small_text: A string representing the text when hovering over the small image asset.
What to put on the large_image
can someone help with my issue?
I think it just returns dictionary and you meed to access the value with key: dict[key]
hmm
sorry I don't use cogs
im in mobile, but it looks like the indentation is wrong?
Run time error
no running event loop
The code is fine but i think something isn't right in backend
Try using
#import the package
import time
#cooldown or sleep command
time.sleep(time)
how to make it so that if the user does not have administrator perms, it sends a message
Are you using discord.py?
pycord
Fr?
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/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/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
@obsidian ledge ^ you can put this decorator on a command
how to make it so tht if a discord user does not have administrator perms, it messages you do not have permission to do thart
use the has_permissions decorator and handle the error it raises (MissingPermissions)
i dont understand
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
but it doesnt ctx.send wheter if they have the administrator perms or not
class Buttons(discord.ui.View):
def __init__(self, ctx, *args, **kwargs):
self.ctx = ctx
super().__init__(*args, **kwargs)
handle the error
just change the parameters of _init_ as per your needs
check the part about class instantiation
how to do it
use the on_error event and isinstance
Yes (assuming Reminders is a module)
use can also use @command_name.error if you want to have a particular handler for a specific command
super init more like tommyinnit
its just a joke chill
it’s a cringe joke
i know
add “super().init()”
call super in your __init__ method if you wanna access discord.ui.View's properties/methods/attributes

yes
Hi
but I prefer putting the attributes below super()
hey 👋
hey guys how can i restrict some specific word to a chennel. Except those words others words or sentence will be deleted by my bot?
!d discord.on_message use this event to check messages
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.
How to send video file?
!voeceverify
You are not allowed to use that command.
Check OOP tutorials/docs
hey how can i tell my bot to send message to a specific channel if a event occur
!d discord.ext.commands.bot.get_channel
No documentation found for the requested symbol.
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
How to check if current message is in nsfw channel?
how can I tell my bot to reply in a specific channel?
is_nsfw()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is NSFW.
ah not the ()
i think he wanna reply to specific message
i think using a message id is also good
i mean for channel you use <#> for user you use <@> but for message idk what to use 😭
do you have any idea how to
how do I check if a command has an is_nsfw check?
help?py @bot.event async def on_message(message): if 'wfl' in message.content: await message.add_reaction('🇼') await message.add_reaction('🇫') await message.add_reaction('🇱')it doesnt work.
Are the there any errors?
no
theres a red line under the code, and when i hover over the red line, it says "syntax error"
Try using the unicode value
the what value?
the unicode value of the emojis, 🇼 = \U0001f1fc etc
how to make it so that if the user does not have administrator perms and run a command, it sends a messgae
ohh
w
can u elp me
already answered you
i dont know how to handle the error
oh wait i dont get it
could u continue the f and l for me?
!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/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/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/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
oh
object will be your error object and classinfo in this case will be the error it raises (MissingPermissions)
ok
how to know the error object
!d discord.on_error
so i put that after every command?
no..
takes in error
f: \U0001f1eb
l: \U0001f1f
thank you
👍
@client.event
async def on_command_error(ctx):
if isinstance(object, MissingPermission):
like that?
add , error next to ctx since on_command_error takes 2 arguments
hey, im trying to make a bot that does certain actions based on the duration people have spent on certain activities using discord presence of users in a guild, how would i go about making it update the information regularly?
ok
error instead of object and what kayle said
wait, it errors at MissingPermission
how>
more specifically i want to kick people who play brawlhalla for more than 30 minutes if that helps lol, I've got most of the code done but im not sure what to put after async def ___ to make it give updated information about the activities
import MissingPemissions?
ok
ig u could use tasks? but im not sure if i understood your goal properly
@client.event
async def on_command_error(ctx, error):
if isinstance(object, MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
why did it not work
...
oh
essentially i want to get users' activity data in a loop, i was running it in an async def on_ready() block and that only updated with the information on startup, how do i setup up a loop so that it updates Client.guilds.member.activity data every loop
just a suggestion, add raise error outside your if statement because this error handler will eat up all errors u dont handle
ive seen tasks and cogs on a couple stackoverflow threads but im not really sure how to implement it
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
these examples right? im just not sure how to make my code work in these
yes these
not very good with python i can show you the garbage ive written if that would help
@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
its not not working
I've gotta go in a bit
@pine crown do this
and see if it errors
just put raise error?
should add the error param
outside if statement
this is what ive got, thing is client.guilds.members is only assigned at the start of the program, where would i paste the body of this code into that example?
outdated help smh
mad your a cat?
can go inside your task
@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
raise error
it dont owkr
so inside
from discord.ext import tasks
@tasks.loop(seconds=5.0)
async def task_name():
#here
task_name.start()
when i run the sample code i end up with no output, not even the print(waiting...) maybe thats why im confused
if its not that instance it will just raise and error btw
I need a code for the discord bot which after typing the command '! Cooldown <number>' will set the slowdown on the text channel where the message was sent for the number of seconds given in '<number>'. If it is set to '0' it will not slow down. If someone wants to write such a code for me, thank you in advance.
!e
a = 1
def function():
if a == 1:
print("yes")
raise "no"
function()
a = 2
function()
@slate swan :x: Your eval job has completed with return code 1.
001 | yes
002 | Traceback (most recent call last):
003 | File "<string>", line 6, in <module>
004 | File "<string>", line 5, in function
005 | TypeError: exceptions must derive from BaseException
raise error
do i? not sure
ok
in your case yes
how to fix my code
what is your code
@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
what about it?
why not make a special error handler for just that command?
on_command_error takes all errors from a command
you pasted your whole code on a syntax error?
Damn discord changed the colors
how to do that
just for mobile or ur device
Mobile
nice
The colors on PC sucks ngl
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
true i dont like the green
show tb
is this py syntax highlighting?
!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.
how is that js?
she is talking about the color being different
welp gtg
yeah that
I need a code for the discord bot which after typing the command '! Cooldown <number>' will set the slowdown on the text channel where the message was sent for the number of seconds given in '<number>'. If it is set to '0' it will not slow down. If someone wants to write such a code for me, thank you in advance.
likely you wont get spoonfed here
i want a code that prints the title of the embed whenever an embed is sent.plz help
!d discord.Embed.title
The title of the embed. This can be set during initialisation.
it has title attribute
try .edit_original_message
bot = interactions.Client(token=TOKEN)
File "C:\Users\anand\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\client.py", line 76, in __init__
self._http = HTTPClient(token=token)
File "C:\Users\anand\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\api\http.py", line 337, in __init__
self._req = Request(self.token)
File "C:\Users\anand\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\api\http.py", line 168, in __init__
self._loop = get_event_loop() if version_info < (3, 10) else get_running_loop()
RuntimeError: no running event loop```
Did you defer?
why are you even using the interactions library, its too slow with development and is kinda buggy
Someone reffered me and when i started i can't get pass this error tho the code is currect
There is nothing wrong with the code but i keep getting this error
And this is the only library used for slash commands
If I'm not wrong...
well they have the same code in their example
ill really suggest you to use some maintained library like disnake or nextcord
no. not at all
pycord ftw
there are like 10 better libraries
give me options
i hate u hunter
Ik
can anyone help me i want to print title of embed
async def on_message(ctx):
try:
print(ctx.embed.title())
except:
None```
I wasted my time on this one i won't go with this now
print(ctx.embeds[0].title)
thx
https://pypi.org/project/disnake
https://pypi.org/project/nextcord
https://pypi.org/project/py-cord
FORKS 🙃
https://pypi.org/project/hikari
written from scratch
i suggest disnake
3rd link..
yes, along with buttons, views etc
pycord is just hated too much
okay someone told me ab pycord
ik, tons of adverts
but if you really check into it, disnake is a better fork
I meant py-cord's pypi is https://pypi.org/project/py-cord and not pycord
What ab hikari?
ow yea,that sucks
its better and faster than discord.py, but hard to learn and use
if you wanna use hikari use lightbulb don't use tanjun pls it's too complex for me imo
yea, tanjun is fire lol
I'm a bit familiar with discord.py
so you may use disnake
okay
yes...
in case you wanted to know how hikari-lightbulb works py @info_plugin.command @add_cooldown(10, 2, bucket=UserBucket) @option(name="user",description="Targetted User",required=False,type=Optional[User]) @command( name="avatar",description="View user's avatar ",aliases=["av", "pfp"]) @implements(PrefixCommand, SlashCommand) async def av_cmd(context: Context) -> None:
everything works with decorators & you can implement slash and normal commands together
Just make your own API Wrapper Use hikari
U need to use interaction.response.send_message() first
???
Hmm
I don't remember the fix tbh
I made a Paginator for ephemeral message
how is support of this? do they have communities where i can ask questions?
you can ping me for hikari problems, and they have their support server too
i can send an invite if you need
sure
tysm
hello!
im facing a problem, or well, multiple, the first would be that im finding the discord.py documentation really hard to comprehend
2nd issue, probably given by the first, is that im trying to make a bot that send me a jpg from my pc in a channel whenever it detects movement from the camera. the camera part is set up, as is a 5 delay timer and writing the jpg. im not succeeding in making the discord bot send me the jpg, and im having trouble understanding how to use/what i should use instead of client.run since it stops all the code after it
frame_jpg = cv.imwrite('feed.jpg', frame2)
pn.send_text('prova')
delay = time.time()
channel = client.get_channel(ID)
with open('feed.jpg', 'rb') as f:
picture = discord.File(f)
async def send_file():
await channel.send(file=discord.File(frame_jpg))
client.run(TOKEN)
use .start() with asyncio.create_task()
@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
why not working
the run method should be outside the function
hi ahley
because the user isnt missing any permissions, easy
"ahley", hi grx
then?
its i dont had the permissions
huh?
i used a alt
oh
does it print anything in the terminal?
but the error coms in the console though(the missing permissions)
I see, then the event isnt getting triggered
are you in a cog?
no
hm
@client.event
async def on_command_error(ctx, error):
print("hello")
even this doesnt come
do u want to see my full code
!Paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
sorry i don't mean to be bothersome, but could you explain more
commands.MissingPermissions
note that commands.MissimgPermissons is raised only with the checks, heirarchy errors won't be recorded there
lol its oki
well, you're probably making a function and the run method on the Bot instance creates an infinite loop, so you always want it at the bottom of your code
any code after the run method would not be executed
hey does some1 know something bout discord buttons cause i tried discord_components but the buttons couldnt react
damnn.....dont use this-
.
any fork or hikari
?
^
there are many other api wrappers too ;-;
should i use nextcord?
none that I know of that are any good tho
same lol
yeah you can
yes i asked in the official server they said upgrade to 2.0 but that one doesnt work
either disnake or nextcord imo
is it just a pip?
im not making a function tho, like all the code is inside a while and a nested for loop pretty much, i tried putting it outside and it just blocks basically the whole code anyway q_q
yeah
so
pip install nextcord
personally I'd say at this point in time probably disnake > nextcord, but nextcord's doing some hot stuff for their 3.0 (iirc) release
is there a read the docs or smht
they're very similar syntax-wise
import disnake as discord 👀
i thought you wre using disnake
ew, no, thats a very bad practice
but what do u guys like more
yes, hence the eyes
but the difference between normal and disnake and nextcord
whats that
the difference
still doesnt work
discord.py got discontinued and doesnt support slash commands without 3rd party libs
others are maintained and support all components built in
why it not work
so thats how u make buttons
ok
but the way its setup isnt different
i dont have to rewrite
theres v2.0 tho
it still doesnt support slash commands and wont be maintained anymore (most probably) 
what I'd probably recommend is something like
import asyncio
import discord # /whatever you use
loop = asyncio.get_event_loop()
client = discord.Client(..., loop=loop)
async def check_cam():
await client.wait_until_first_connect() # ensure the bot is running before the function continues
while True:
... # do your image stuff here
await asyncio.sleep(5) # wait 5 seconds before trying again
loop.create_task(check_cam()) # start check_cam as a background task
bot.run(<token>)
ish
eh?
oh I see
smh
probably just that their cam movement detection code is all at module level (in the bot file)
which won't work with a bot
Do you want to change the ephemeral message after clicking the button.. or when?
am i allowed to share big snippets of code here?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
why this not working ..):
heavy processing too, probably gonna crash the bot
is rillrate dead?
there's a paste service for that methinks
yeah...
probably best off as two separate processes
this is not the appropriate channel, please ask in #python-discussion or claim a channel #❓|how-to-get-help
and interaction.response.edit_message() doesn't work? @cedar smelt
I think commands.MissingPermissions is wrapped in commands.CommandInvokeError
so i replace?
error = getattr(error, 'original', error)
``` you can add this to use the original exception
?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
error = getattr(error, 'original', error)
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
like this?
no
is there any way to ban a user automatically, without any input?
add it before the isinstances
With mind?
Your welcome, I was stuck there yesterday aswell :D
with mind? idk what that means but the bot would determine if the user is to be banned or not, and then bans automatically, no need for anyone to type any commands
..
Use an on_message event
Do your logic and then ban or don't ban them
py-cord, disnake, nextcord have easier syntaxes than lightbulb
^^
https://paste.pythondiscord.com/zulalidupi.py found the paste website! this is basically the main part of the code
what would be the code for the kick/ban?
@client.event
async def on_command_error(ctx, error):
error = getattr(error, 'original', error)
if isinstance(error, commands.MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
still doesnt work ):
do u want my full code so u can chec k if anything else is blocking it
Can you give a example? There usually must be some sort of condition, when bot bans
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
mine is a little stupid, if the player has been playing brawlhalla for more than 30 minutes
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
does it raise the exception?
Hahahah good one
Member object
oh okay thank you
dude, no
you use the kick method on the Member object
huh?
What?
Yeah it was my bad bro lmao
!d discord.Member.kick
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
HAHA
PexiBot is ready.
Ignoring exception in slash command 'ban':
Traceback (most recent call last):
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1346, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 574, in invoke
await self.prepare(inter)
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\base_core.py", line 205, in prepare
if not await self.can_run(inter):
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\base_core.py", line 524, in can_run
return await async_all(predicate(inter) for predicate in predicates) # type: ignore
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 561, in async_all
for elem in gen:
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\base_core.py", line 524, in <genexpr>
return await async_all(predicate(inter) for predicate in predicates) # type: ignore
File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 2068, in predicate
raise MissingPermissions(missing)
disnake.ext.commands.errors.MissingPermissions: You are missing Ban Members permission(s) to run this command.
says this
are you sure disnake doesn't have a seperate error handler for application commands?
They do
You dont have perms
!d disnake.ext.commands.Bot.on_slash_command_error
await on_slash_command_error(interaction, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default slash command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for slash command error.
It does I think
@pine crown ^ you'd use this instead of on_command_error since it seems you have an application command
ok
so i add this into the application command?
^
😼
Nova is a disnake contributor so he can tell you
ok
Yes
hi
Hi
help me
ok
await on_slash_command_error(interaction, exception)
i put this inside application command?
Idk try it and see
h
how do i import it
looks like a decorator
wat
idk
ok
you use it like on_command_error
ok
!d disnake.ext.commands.Bot.on_slash_command_error
await on_slash_command_error(interaction, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default slash command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for slash command error.
You're over riding the default on_slash_command_error
@client.event
async def on_slash_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)
ok
0 arg is interaction not ctx
ok
@client.event
async def on_slash_command_error(interaction, error):
if isinstance(error, commands.MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await interaction.send(embed=embed)
thank
you
Np, your charge is 2 dollars
😮
💸 $2 sent to Nova

i know a pythongus
shiki

Rin 
that's cute if anything
what is with that emoji and you
Hi all, just a quick query in regards to discord bots/python libraries... I want to restart my python learning, plenty of resources to do so but I am a bit confused around the libraries now..
As of august 2021 discord.py was discontinued, is this still safe to use or would you recommend using a different library such as nextcord or enhanced-discord.py?
disnake is like dpy use that
You could be a winner with your profile pic...
You can still use dpy if you plan having a private bot in your server without any intent of growing and if you won't use slash commands or /and buttons
inport discord as disnake
Import disnake as discord
it has bobs
you can go with a fork if you wanna continue the same format as dpy (i prefer disnake), otherwise use a different library like hikari which has a very different format than dpy (obviously)
buttons exist in discord.py already (discord.py@master)
Yeah but it's not an official release on PyPI though
still
yep
either use a fork or nextcord, enhanced-dpy
e-dpy pretty complete
Disnake is ur way to go
^^
go on I'm sold, too many anime fans recommening disnake, so how could I not 😛 thank you all ❤️
||(weebs)|| 👍
I didn't watched any anime for a year
idont even know what anime is
Questionable
If you're an anime fan, hikari exists 
have another one: use disnake
ok
i have coconut canister
In what sense is very weeb tho
Not the library, but the devs are
hikari is jp for light
most of their "official" extensions have jp names
most of their emotes are anime-related
among a couple other things
By most, you mean tanjun
It is really fun
Miru is not an official extension, it's just like discord-components in Discord.py
!pip hikari-miru
ah yeah fair
An alternative component handler for hikari, inspired by discord.py's views.
think I'll get around to making a bot in hikari sometime soon
have been meaning to do so for a while
yeah purely judging by source code I think it's the best python lib out there atm
as in discord api wrapper, that is
async def on_message(message): if wordfilter in message.content: await message.delete()
wordfilter = ['bad','bot']
Why it delete all message if i start !help arg1
Atleast someone realise.it lmao
Most of the people find it weird because it's not as easy as Discord.py
yes
You are checking if a list is in a string
!e if ['a','b'] in "ab":
print(1)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
see the error
What's the correct way of returning channel id of #discord-bots
for instance, I create command : .send #discord-bots "message"
how can i fix
Typehinting the channel argument as discord.TextChannel and use channel.id
Sorry I missed this message, you would have to use any function
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
I'd say 343944376055103488
Animated media
!pip keyboard
#bot-commands
anime is cool
im going to an animecon/gamingcon/comicon...? on saturday
tbh idk what it's even called LOL
beware Mina 
fuck she's gonna !mute @velvet tinsel 10m because he gamingcon me 😳
this is still ot
Calendar as in?
So like, this way, the user will be able to input important dates, events and stuff?
the calendar app exists
PoV: I spend more time on discord than on the phone itself
But yea, u correct
i mean I guess you can make a command...
but, it's less efficient than using a calendar app
I don't really think how that's gonna be possible tbh. It would look seriously ugly since codeblocks and those fuck up since the screen size if different for all the devices
Agreed
Also if u use PIL or smth, then also, u will be needing too much processing power/CPU Power to actually create those calendar images everytime someone runs a command, which is totally not fun
cache them? ^
Yea... but how I'm picturing it, a calendar command would be the same as a remind command, but just with a picture to show the events, right?
how do i edit a channel's topic
channel.edit() (just guessing)
Yups
do u need to import anything
!d discord.TextChannel.edit has a topic kwarg
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
@maiden fablei dont know what calendar he wants but i was just thinking if first time command is run for that date it will just take long time ofc processing, but he can then cache it for next one who checks that day
Yea
You know... people didn't care about a remind command too
But your idea is doable tbh
I would love to help u make this command if u want to make something like this (:
so tell me how this calander gonna contain and be used @cedar smelt
Source code: Lib/calendar.py
This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules.
i mean is it just going to display dates n dates of a selected month?
Uhhh nope
Actually @cedar smelt, I like this idea of yours!
This can just become more of an upgraded version of a simple remind command
@cedar smeltcan u explain how u vision it like what will it contain and show
I would love to help you implement something like this yourself since this is your idea (:
Haha well I got a raw idea of how the command would be looking/working
We can use something like .event set <date> <event>
We add it to the database
And we generate the calendar image and store it in a folder and the image name could be the Author's ID(?)
And whenever someone runs the set command, a new image with the updated calendar will be shown
image name should be unique like the messageID
Would be hard to keep track of those ngl
and u just add discordID as creator in row of db
We can simply use discord.File(f"{message.author.id}_{month}.png") and use a try except to check for any errors in case a file with that name isn't present
oh each users will have their own calendar
Yup
command and db would be easy n fast to create
And whenever a month ends, the photo of that month gets deleted
There are numerous ways to do the same thing
and clears his db of that month save HDD
i need help.
i wanna make so the bot takes all the commands from the folder general moderation and economy and adds it as commands
!d discord.ext.commands.Bot.add_command
add_command(command)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientException "discord.ClientException")
@maiden fableYou got experience with numpy?
Nope, sorry
Why would you want to do it without cogs?
js is harder, they do got more examples.
Compiled language 😔
!pypi discord.js
how to wait for reaction add and a message?
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
you're using disnake right?
Can i make that?
Token = [token1, token2, token3, ....]
bot.run(Token)
@cedar smeltmaybe this ```py
def cog_unload(self):
self.service.stop()
self.service.start() in ur class init
@tasks.loop(seconds=120)
async def service(self):
``` service = task
Why do you need multiple tokens?
For Host a few bot
but codes are the same lol
Yes i know codes will be same :/
so whats the point? 😄
uh
What if
no, it wont work
I think it'll run the first bot
the first bot will run
then wait until you close the first bot, then launch the next
What if you create multiple threads and on each thread you run client
etc.
yep, its blocking so the for loop would stay at the first element only
that sounds more like it
What about if i do a few bot.run() ??
lool
No
Smh
what about you just use a singular bot, lol
you can, use bot.start() to run multiple bots in the same file
what u can do is put token as argv and run script with tokens as argvs
and have a script that runs them bots
oh there u go
i was have an opinion .... When i remember, i will tell, then it will be easy
@arctic wraithhe had an opinion!
maybe i can use different bots in different servers
whats the point? u want diffrent avatars depend on server?
Not only avatars actually
(would be nice if discord allowed multi avatars that could be set by serverowners)
I mean sure... but why? you can have a singular bot in thousands of servers without much issue
Yes but can i create shards?
yes?
How?
what is shards?
e.g. disnake just has an AutoShardedBot iirc
@arctic wraithcan u give me brief explanation what shards are?
Eh well i will ask it to google :d
basically splitting the bot over multiple smaller sub-bots that each cache their own guilds and members and such
I think it's generally about 1k members per shard?
ah nice thanks
What's the right approach for creating a disnake button, which is functional after bot restart
persistent views, hunter sent a link. Let me find it
he uses disnake tho - probally same?
ofc
yeah the example is the exact same as the one on the disnake repo
yw
That's actually amazing
ye aint it like discord.py but changed all files with replace("discord, "disnake") 😄 and more features
~ish
there are very few minor changes but for the most part it's same
so discordpy has also buttons/slash commands built in?
I mean it's a fork after all
im still new to discord.py and i wanted to know if theres any way you can find a user from message context
!d discord.Message.author ?
not the author
