#discord-bots
1 messages · Page 863 of 1
multiple inheritance 😳
Hey Robin, wondering if you can do me a favor. Could you ask a mod to check if someone has been permanently banned or temp banned because if they were permanently banned I have proof that they're ban evading?
Or should I just make the report and see?
you could search their user id in message search
yeah, but if they were banned they probably got banned by a command
@final iron I've let em know but regardless send @novel apex a message and they'll help you sort things out
He says to the helper 😂


Not that hard
@sick birch what's the right kwarg to edit the channel news
!d discord.TextChannel.edit
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.
Click the link to see
looks like type=
ik but its a cool topic
type=ChannelType.news?
method* 
No?
it's discord.ChannelType.news
A guild news channel.
yes
ah alr
why is the message cooldown so long here
they keep raising and lowering it
.
i didn't notice bruh
is 6 am im slow lol
lol
but how can i set it to True/false
does it take bool?
wdym 'true/false'
Like if the before is false and after is true ban the member and set it back to false
or if before is true and after is false ban the member and set it back to true
Aight I sent in the report
^
Huh? That sentence was extremely unclear @slate swan please use commas
Commas are so useful tbh
prefer JSON tbh
Any lol
I prefer bot_token incase I need other tokens and I need to find them
BOT_TOKEN
thanks you've influnced a pr
@slate swan what a name 👀

Mind changing your nick?
actually pfp is nsfw
Meh as if someone gonna change the PFP
do you think people are gonna listen if you tell them to do that without you questioning, "are you mod?" 
"minimod"
Bruh why y'all talking about ToS all of a sudden
Okay
lol
Meh, nickname policy exists in #rules
I can just direct them there and ping the mods ¯_(ツ)_/¯
Rip that was removed
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
wont work
There smh
Bet?
no, wrong ping
yeahhhhh, it didn't ping
f it, lemme just ask here UwU
Robin, why u lurking here?
thinking of the best way to remove references to tokens
if channel.permissions_for(guild.me).send_messages:
Come here and help others 👀
Very tempting
**Your BOT is also a MEMBER ** 
Actually it's not, technically
Help and I'll give your hood back
oh no🗿
@slate swan Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
You want me to help you help someone else?
member_count
something about
- how to best store token
- how to best load token
Help Lodi 👀
What...
sir robin 
A what?
strategy
No what do you mean by "seperate file for the examples"
oh
U do know that emoji is cringe right?
what isnt cringe to you
Wait, did the bot steal yr name or yr stole it's?
I'm a disnake developer, and I'm working on the examples folder-- https://git.disnake.dev/disnake/tree/master/examples @sick birch
Meh
on?
like subfolder
rn i'm thinking of the best way to remove references to putting tokens directly in bot code
examples/basic_bot.py line 79
bot.run("token")```
Thanks for calling me that
both, both is good
Bro, it's different. It's used for OAuth, not bots lol
I see
Lmaoo
I didn't call you anything 
what
Auth token
?
I'd much rather have something which either does
from config import TOKEN, and tell the user to import thatos.environ.get('BOT_TOKEN')but that would require explaining this is what env is- perhaps just add a disclaimer above every bot.run that mentions the other techniques and links to a page on why tokens need to be secure
- other option, very open to suggestions
Yeah the way I've always done it is how it's done in sir-robin
Nvm
I do uh
- config.py file that's commited
- env file that the config file loads
bot/constants.py line 14
token = environ.get("BOT_TOKEN")```
who uses the get method-
ikr
Run Python code and get the results.
hope it helps you a bit
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
inb4 everyone suggests a different lib
Don't use pycord
😭
No way, how'd you know?!
arl called it😔
Save yourself a lot of trouble and use disnake
I'm biased
lemme guess, you use edpy and disnake
nah i use discord.py and implement the features myself
One of the worst forks
Imagine using edpy

Virgin fork user vs chad feature implementer
We should make a strict disnake only policy 🗿
Inform instead of persuade
I swear man. People shill disnake like it’s Jesus or something.
Disnake is better than jesus
in reality it’s just like every other fork
🗿
i mean, if you don't mind
- broken code
- lots of broken code
- minimal testing
- approvals by their own developers of some who don't even know python
then its fine to use
¯\_(ツ)_/¯
py-cord*
!pypi rin
Because when it’s in production the user isn’t supposed to care about broken code.
!pypi py-cord
!pypi pycord
Lol
that's an ffmpeg wrapper lol
Yea
@sick birch so do you actually still use raw dpy or was that a joke...?
fairly sure he uses disnake
Robin seems like the person to implement the disnake features himself
I did do it a bit
But I don't do bot dev that much anymore
no
I recently implemented modals myself using d.js if that counts
robin is a chad he uses d.js
i used it like twice
nah they're still active development
Honestly slash commands aren't that hard to listen to using discord.py
why decos?
The data's a bit messy/raw but you can clean that up yourself if you want
Bro Robin what is this
Before you say anything that wasn't me
You have a whole cog dedicated to one command.
👁️ 👁️
why not ¯_(ツ)_/¯
And you manually log inside the command
🗿
imagine not having a standard logger/eval/ping/meta/etc commands smh
how can i make it so it's like
if member has muted role:
remove all roles except muted role```
if role in member.roles:
await member.remove_roles([i for i in member.roles if i != role])
``` assuming role is the muted role
Filter out the mute role from the list so you don’t remove that obviously
You can do that list comp
U do know that remove_roles() can take a list of roles, right?
if role in member.roles:
member.remove_roles(member.roles)
Oh crazy
Better than doing API calls repeatedly lol
My bad then
That's why it's named remove_roles
First time boys. I’m new here.
Nah it's good
Yea yea
@maiden fable better?
forgot the await smh
oops

too much javascript 🙁
i want the whole message but this only picks the first word of the meg
Traceback (most recent call last):
File "/home/runner/Proton-7/venv/lib/python3.8/site-packages/jishaku/features/python.py", line 145, in jsk_python
async for send, result in AsyncSender(executor):
File "/home/runner/Proton-7/venv/lib/python3.8/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/home/runner/Proton-7/venv/lib/python3.8/site-packages/jishaku/repl/compilation.py", line 143, in traverse
yield await func(*self.args)
File "<repl>", line 3, in _repl_coroutine
role = discord.utils_get(ctx.guild.roles, name="quarantine")
AttributeError: module 'discord' has no attribute 'utils_get'
utils.get
discord.utils.get
yeah i got it tysm
Yay
Error
you did utils**_**get
hello I am running a discord bot on repl.it with a flask server and uptime robot pinging it, i have done this with another bot in the past and that bot has been running for months, but this new bot I made goes down every hour and I keep getting this in the console(I'm assuming from every ping i get from uptimerobot):
[27/Feb/2022 04:39:00] "GET / HTTP/1.1" 200 -
Any ideas as to why this is happening?
perhaps from discord import DiscordException?
200 is an OK no content, what's wrong with it?
The bot doesn't run 24/7 it goes offline
That's replit for ya
Heavily recommend you switch off replit and find an actual host
yeah that's not right
yeah, pycord screwed that up
im trying to use motor, and im wonder if this code would work for motor or if something is missing? ```py
motor.motor_asyncio.MotorClient(key)
async def open_account(user: discord.Member):
try:
post = {"_id": str(user.id), "Balance": 0}
await cluster.Botswag.Accounts.insert_one(post)
except:
pass
@client.command(aliases=["bal"])
async def balance(ctx):
await open_account(ctx.author)
embed = discord.Embed(title=f"{ctx.author.name.title()}'s Balance",
description=await cluster.Botswag.Accounts.find_one({"_id": str(ctx.author.id)})['Balance'],
color=discord.Color.green())
await ctx.send(embed=embed)```
its shadowed and importing discord.errors imports discord.commands.errors
discord.commands.errors should work
im not sure if this should be here or in databases
@languid wagon u installed py-cord?
There u go
It uses the discord namespace
So there are these folders made for each module
disnake modules makes a folder named disnake
discord.py makes a folder named discord
But py-cord uses the discord folder only
So that can result in errors if u had discord.py installed
Uninstall dpy, py-cord then reinstall py-cord
Weird... try doing pip show py-cord
Just use disnake 🗿
Returns True if a user can perform limited moderation actions (timeout).
New in version 2.3.
They haven't implemented it
I wonder if its one of their broken pushes 
@slate swan i used motor and im still getting this result
hows your internet speed and do yu have something blocking
U do know Python is easier, right? 👀
my internet is kind of slow, and as for blocking, not to my knowledge
motor.motor_asyncio.MotorClient(key)
async def open_account(user: discord.Member):
try:
post = {"_id": str(user.id), "Balance": 0}
await cluster.Botswag.Accounts.insert_one(post)
except:
pass
@client.command(aliases=["bal"])
async def balance(ctx):
await open_account(ctx.author)
embed = discord.Embed(title=f"{ctx.author.name.title()}'s Balance",
description=await cluster.Botswag.Accounts.find_one({"_id": str(ctx.author.id)})['Balance'],
color=discord.Color.green())
await ctx.send(embed=embed)
What's the issue?
the bot is lagging
Not a code issue, it's an internet issue
Host the same code on a VPS and u gonna get about a 100 MS ping more or less, depending on the region the VPS is hosted in
dont vps cost money tho?
Yea they do
Hahaha well there are free services too, but they suck
one of my friends has a vps, ill see if i can ask for access or smth
Well, it will be easier if he installs pterodactyl panel/puffer panel on it
ic
Smh typos go brrr
oracle gets you that ping?
I'm getting 97 MS rn
Sure! What's up
how i do multiple commands at the same time
Wait, u ain't getting that?
VPSs usually let you pick the region where it's hosted, so you can get really good ping, like < 10 if you tried
when the bot in this loop everything stop working
constant at around 500
let me check
sleep() blocks the entire event loop
Yea use asyncio.sleep
i get 0.19962728797690943
ill try
Robin, do u hate me? Cz I do this:
import asyncio as time
async def smth(...):
await time.sleep(10)
That's 200 MS
wait wth
please cease all contact with me
let me check my ping command
👀
why
What about yr hood which is with me-
why would you do that
I just wanted to code differently 🥺
i dont want it anymore considering the kind of person who has it
it's kind of like import disnake as discord
Or... import disnake as pycord
=D
that's like a wolf dressed as a sheep
very scary
Imagine
@sick birch let's just use raw aiohttp module instead of all this wrapper shit, what say?
that's what i've been doing lmao
this is my ping command
@bot.command(brief=['Ping', None, 'Displays the bot ping', '=ping', None])
@trial_moderator_only()
async def ping(ctx):
start = time.time()
message = await ctx.send("Ping!")
end = time.time()
duration = (end - start) * 1000
await message.edit(content='Pong! `{:.2f}` ms'.format(duration))
Oh
Why...
why not ctx.bot.latency
"import asyncio as tornado"
import asyncio as totallynotyoursussyasyncio
hello
hello
hello
i tried it doesnt work
oh no
what
What
i regret everything
I regret joining discord
why is that so?
brb deleting github
💀
i have 2 def ok and i want the bot do the 2 tasks
Because it has made my life heller hell
at the same time
just send code bro 💀
i uh may have looked at source of a library and find some of the decisions quite questionable at best
Meh, I can't get off it since I got better friends in here than irl
Which lib? 👀
Don't tell me it's hikari 👀
anyone seen random library questionable variable names?
?
@client.command()
#Getting the input from the user on discord text chat
async def set_timer(ctx, arg):
am = discord.AllowedMentions(
users=True
)
arg = str(arg)
await ctx.send(f"timer set to {arg}")
#This to get your real time
while True:
now = datetime.now()
final = now.strftime('%I:%M') #12-Hour Format
#Final = now.strftime(%H:%M') #24-hour format
asyncio.sleep(1)
if final == arg:
await ctx.send(ctx.author.mention, allowed_mentions=am)
break
the code is working fine
!code thanks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
to note: this is a widely used library, and the problem I find with the code being questionable concerns me for all of the efforts people in this community make to try and help people have good practices
but the bot stuck on the loop till it finish
I mean that's a common word bruv
yeah idk i haven't paid much attention to that not sure what i even had as my command but what's so bad about this? i did change to bot latency but still want to know
If u don't take it the other way
ic
It's used as an alternative for and in English (at least for me)
Don't think it's accurate
Because... the latency is different with that command. The bot takes 200 MS to send the request to send that message to discord, so that's mostly wrong
.latency is the time between HEARTBEAT and HEARTBEAT_ACK which accurately says the latency time of the websocket
Yea
timing a await ctx.send() includes overhead
would it be much of a rewrite of my code if i switched from discord.py to interactions.py?
lol

Not until voice receive becomes a thing in disnake (arl 👀)
but also yes, they aren't a fork
@sick birch voice receive implement when in your custom wrapper?
man i haven't even looked at that part of it yet
why do you wanna switch?
The problem is, the endpoint is undocumented ;-;
interactions
Best of luck scrolling through discord.js's source
discord.py has no interactions
It does have interactions
buttons?
wouldn't it come through websocket
ye
!d discord.ui.Button exists
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
i dont see any documentation for it anywhere
Yea, ig
master branch
Yea
ahh
pip install git+https://github.com/Rapptz/discord.py
Just run this in yr command prompt (:
???? yo wtf 💀
questionable naming practices but that's okay
useletters so you would save some bytes🗿
we dont talk abt random lib
come on it's not 1995 where we use floppy drives that have 14 megabytes of storage
slightly off
prolly 27
my point is i don't think it's worth sacrificing readbility for that little bit of saved storage
100 pennies is a dollar 1000bytes is a kb 1024bytes is a kb in windows know your value🗿
but if you wanted to nothing stopping you
!e py print(1995 + 27)
@wary zenith :white_check_mark: Your eval job has completed with return code 0.
2022
ahhh
this man really needed to do the math in python😭
its 12:46 ok 😭
1am here lol
!ot stop going off topic
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
ok
ok
ok
hello
hello
heeeeeeeellllllllllllllp!!!!!!!!!!!!!!!!!!!
with?
see i have 2 def ok and i want to run them at the same time
#Mention Bot:
@client.command()
async def set_timer(ctx, arg):
am = discord.AllowedMentions(
users=True
)
arg = str(arg)
await ctx.send(f"timer set to {arg}")
while True:
now = datetime.now()
final = now.strftime('%I:%M') #12-Hour Format
#Final = now.strftime(%H:%M') #24-hour format
asyncio.sleep(1)
if final == arg:
await ctx.send(ctx.author.mention, allowed_mentions=am)
break
see
the bot stuck on while loop
when the bot doing this while true everything stop working
you should use a loop for a timer lol
Loops can be blocking sometimes
it's not blocking
Why are you even using a while loop?
it's working fine
You just said it was blocking
the is another way!
ahhhhhhhhhh!
use a db and store the time and just check the time each minute
if you want to make a timer
yessssssssssssss
if the timer is work everything in the bot stop working till the bot finish
use my method
ill try
how
you store a timestamp
like i have to split the code in 2 def right?
in 2 methods? i doubt it
¯\_(ツ)_/¯
btw you didnt await the asyncio.sleep so it doesnt actually yield execution back to the event loop
i think no one understand the issue
idk about that infinite loop
And what @hushed galleon said, await your asyncio.sleep
when the bot in the while loop the other loops stop working
besides the missing await, their infinite loop is mostly alright
Mind showing code?
ofc
we replied to their code twice
It's fine, lemme see
Hey @halcyon onyx! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
skull
🗿
😂😂😂😂
?
token = "--"
@client.event
#Message send with bot startup
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#Mention Bot:
@client.command()
async def set_timer(ctx, arg):
am = discord.AllowedMentions(
users=True
)
arg = str(arg)
await ctx.send(f"timer set to {arg}")
while True:
now = datetime.now()
final = now.strftime('%I:%M') #12-Hour Format
#Final = now.strftime(%H:%M') #24-hour format
sleep(1)
if final == arg:
await ctx.send(ctx.author.mention, allowed_mentions=am)
break
#Ban / Kick / UnBan:
@client.command()
@commands.has_permissions(administrator=True)
#Kick
async def kick(ctx, member : discord.Member, *, reason = None):
if ctx.message.author != member:
await member.kick(reason = reason)
await ctx.send (f"User {member} got Kicked")
@client.command()
@commands.has_permissions(administrator=True)
#Ban
async def ban(ctx, member : discord.Member, *, reason = None):
if ctx.message.author != member:
await member.ban(reason = reason)
await ctx.send (f"User {member} got Banned")
@client.command()
@commands.has_permissions(administrator=True)
#UnBan
async def unban(ctx, *, member):
if ctx.message.author != member:
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"User {user.name}#{user.discriminator} got Unbanned")
#clear
@client.command()
@commands.has_permissions(administrator=True)
async def clear(ctx, amount = 5):
await ctx.channel.purge(limit = amount)
#add and delete channels
client.run(token)
bro go refresh ur token 💀
please just await the asyncio.sleep
i remove it
💀 the unban command...
I smell Lucas
im working on it
I know of a simpler way
f strings and format😔
give me it
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
🗿
user = discord.Object(id-of-the-person)
await ctx.guild.unban(user)
Ezzz
make it a one liner bozo
Stop it. Then code it yourself
yeah yeah make it a one liner or else🗿
but there is hope to fix main issue 😥😥
What's the issue tho
Qulx be like: Read the message history dude. I'm tired of explaining repeatedly ffs
when the bot on the loop everything stop working
You can just asyncio.sleep(arg)
instead of looping every second
im done
Uhhh, just use tasks?
and make sure the arg is an integer
yes
Would require a database :0
dmas
Or cache atleast
Meh, my brain isn't working rn anyways so ig ignore me lmao
👁️ 👁️
Okimii's smart
ill try
I'm using optimised mode theme
you can cache it with a dict but if the bot restarts bye bye timer
eww lmao
my search history explain it?
you dont want to see my history😳
at least when you type p you see python 💀
nah
🗿
😂😂😂😂
my history is ok i think
Lmao same
Hmm, if u open my brave browser... u'll see ||godot||'s website
100 emoji meaning💀
i wanted to get the unicode version for my status 💀
bro just use ctrl + shift + n
you know you can do this right
\emoji
\🗿
win + . for emojis for windows
uhhhhhhhhhhhhhhh
\🗿
I have gnome characters application tho
win + v to see all copy history
:moyai
moyai😔
\🗿
think that useful
Love how this channel talks about everything other then discord bots.
😂😂🤣🤣
I mean this is the most active topical channel
moyai :))
its the only channel that actually responds
Agreed
this is the third time #databases has aired me
🎩
🗿
👔
i think english is easy
and the most annoying one too
yall like my art:))
you are always here tho...
this one is better
:D
That's why I hang out in #ot0-psvm’s-eternal-disapproval more
do any one here learned arabic?
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
the channel name🐒
I read that so wrong 
what are these channel names
They are off topic channels and the name changes after some.time
kinda 
each day
every 24h
okimii knows his maths 
Ping me if y'all shift to some ot channel
do u know on arabic the table is female and the chair is male 😂😂
and he's gonna run the ot command now
big bren🧠

🗿
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
!rule 7 we dont do that here, ily2 
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
only bug is the obj endpoint urls😡
Does Twitter have a ratelimit?
big bread 🍞
No thanks I don't love anyone
yes 3 seconds
yes mostly is 50/900s
ic
there is any anime like boku no hero?
good to see this channel in its original state 
Meh pokeapi doesn't have a ratelimit so I don't need to care about that , gotta make it optional
lmao
that's what happens late at night unfortunately
i have ratelimits in akeno lol
12 noon here
anime in discord bots 💀
yeah
early morning for me too
for most of the US, its like 11pm+
its 9:30 am 😂😂
Cause Twitter implements it
Pokeapi does not have a strict limit , but they request users to not put too much pressure on the servers 🤣
Well that makes sense since it's a RESTapi
time zones exist 
👁️ 👁️
request 
imagine requesting requesters to not request too much to not overload the server 
not US but close enough
say request one more time
on middle east its soo cold 95f, how u live on USA
💀
and? 
so the api is just used to access a db?
yea ofcourse
just the Pokemon database
i mean, that's what i do for most of my projects
lol
tooling for databases and APIs are rich in javascript so many people do do that
bro is there a js server
javascript is the best
yes
so i can bother them about making a discord bot in ts
🗿
ive been trying to do for hrs

!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
glad to see the good old hunter 
🗿
are you?
idk eno
Imagine a bot being humourous
what does discord expect
bot says nevermind 💀
Dudes can u take this talk to an OT channel?
one time i got told i wasnt a human by a bot😔
!rule 7 exists for a reason
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
nah you go there
you're really annoying lol
I'm already in #ot0-psvm’s-eternal-disapproval
well stay there
Thanks, that's what I want to be (:
no
when the robot says you arent human 🗿
how do I make a rest bot with discord.py 🏃
its early in the morning, time to sleep has already passed away
no sleep ow
😔
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
you handle endpoints yourself
🧠
no need for dpy

😳



when you realize the guy passed😔 😞
dunno who that is...... 
his eyebags have eyebags 💀
the emoji you used 🗿
💀

el risitas es muerte
😔
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
🗿

😔

@client.command()
@commands.has_role(848230687508922430)
async def test(ctx):
await ctx.send('Done!')
How to make the bot send error message if user doesnt have role
uh
!d discord.ext.commands.CheckFailure
exception discord.ext.commands.CheckFailure(message=None, *args)```
Exception raised when the predicates in [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") have failed.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
Use this
try getting both of them broken, its F.U.N.
anyways, back to topic 
Wasn't expected from u
yo i got a discord bot rn, and its got this at the end
await ctx.send(embed=e)
``` after an embed, can this somehow make it so it replies to the user initating the cmd
@client.command()
@commands.has_role(848230687508922430)
exception discord.ext.commands.CheckFailure(message="You must have \<@&848230687508922430> to use this command.", *args)
async def test(ctx):
await ctx.send('Done!')
this?
no
how can i make it so the bot will reply to the user that initiated the command?
ctx.reply
like this: py @test.error async def test_error(ctx, error): if isinstance(error, discord.ext.commands.CheckFailure): await ctx.reply("You must have \<@&848230687508922430> to use this command.")
lmao i was guessing that ty
oh
Is correct, but commands.MissingRole would be more accurate
Since CheckFailure means any kind of check failures
e = discord.Embed(title=f'**Profile Link**',url=f'https://roblox.com/users/{userid}',color=0x00ff80)
``` so i have that up here but wanna make it look like this, how can i do that?
Can I make my bot edit a message that someone sent?
in the code i showed, Profile Link comes just as blue with url
!d discord.Embed.add_field use hyperlinks
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
Bot can only edit its own message
It's a field ( kayle sent the method) , you can do the hyperlink thing like this [text to appear](url to redirect to)
Thanks
can u type what u mean pls im dumb
Click Here is how you make the hyperlink
Is it possible to do same but instead of role,keep manage_server permissions
!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").
how can i refer to the person who sent the command in an embed ?
yes
manage_guild*
but you need commands.has_permissions decorator
!d discord.ext.commands.Context check attributes of this class
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
Context/Message.author
@client.command()
async def test(ctx, error):
if isinstance(error, discord.ext.commands.has_permissions(manage_guild=True)):
await ctx.reply("You do not have permissions to use this command.")
like,
requested = discord.ext.commands.Context.author
e.set_footer(text='Requested by {requested}')
``` ????
The what
e being the embed
May I ask what's your py knowledge
not alot im just tryna make a simple bot
is this correct?
How are you going to provide an error to your command
idk
Oh your nitro ended, sad
im trying make cmd which requires manage guild perms
you need the discord.ext.commands.Context instance, not the class
@client.command()
async def test(ctx, error):
if isinstance(error, discord.ext.commands.has_permissions(manage_guild=True)):
await ctx.reply("You do not have permissions to use this command.")
else:
await ctx.reply('done')
maybe like this?
Yes the fun thing is it was gifted by discord
Wait what
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: error is a required argument that is missing.

Ok and you need an error handler for that which you can implement with usage of bot.listen or commands.Cog.listener depending on do you use cogs or not
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
@bot.listen()
async def test(ctx, error):
if isinstance(error, discord.ext.commands.has_permissions(manage_guild=True)):
but how to set it req for cmd
😅
@bot.command()
@bot.has_permission('ADMINISTRATOR')
async def ban(ctx, member : nextcord.Member, *, reason):
await member.ban(reason=reason)
embed = nextcord.Embed(title="Ban", description="mentioned user banned.")
await ctx.send(embed=embed)```
Is that correct?
Oh, thanks
Huh?
im confused
im trying to make command which requires manage_guild perms and sends a message if user doesnt have it
Did u enabled intent in ur bot app?
yes i did
Oh
getting the user of the person who sent the cmd rn,
author = commands.Context.author
e.set_footer(text='Requested by ' + str({author}))
``` is what im using at the end of my embed and im getting this:
```txt
Requested by {<discord.utils.cached_property object at 0x0000019928A9FDC0>}
i didnt try this yet
Just watch tutorial
is this code complete?
Maybe that help xd
:/ ok
U want make error handler, right?
I can help
@bot.event
async def on_command_error(ctx, error):
send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError)
if isinstance(error, commands.CommandNotFound): # fails silently
pass
elif isinstance(error, send_help):
_help = await send_cmd_help(ctx)
await ctx.send(embed=_help)
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the permissions to use this command.')
# If any other error occurs, prints to console.
else:
print(''.join(traceback.format_exception(type(error), error, error.__traceback__)))
Is this error handler??
@client.command(name='eval', hidden=True)
@commands.is_owner()
async def _eval(ctx, *, body):
"""Evaluates python code"""
env = {
'ctx': ctx,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'_': client._last_result,
'source': inspect.getsource,
'session': client.session
}
env.update(globals())
body = utils.cleanup_code(body)
stdout = io.StringIO()
err = out = None
to_compile = f'async def func(): \n{textwrap.indent(body, " ")}'
try:
exec(to_compile, env)
except Exception as e:
err = await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```')
return await ctx.message.add_reaction('\u2049')
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
err = await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```')
else:
value = stdout.getvalue()
if ret is None:
if value:
try:
out = await ctx.send(f'```py\n{value}\n```')
except:
paginated_text = utils.paginate(value)
for page in paginated_text:
if page == paginated_text[-1]:
out = await ctx.send(f'```py\n{page}\n```')
break
await ctx.send(f'```py\n{page}\n```')
else:
bot._last_result = ret
try:
out = await ctx.send(f'```py\n{value}{ret}\n```')
except:
paginated_text = utils.paginate(f"{value}{ret}")
for page in paginated_text:
if page == paginated_text[-1]:
out = await ctx.send(f'```py\n{page}\n```')
break
await ctx.send(f'```py\n{page}\n```')
if out:
await ctx.message.add_reaction('\u2705') # tick
elif err:
await ctx.message.add_reaction('\u2049') # x
else:
await ctx.message.add_reaction('\u2705')
Got error raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute '_last_result'
in discord.py
Don't copy R. Danny's eval plz
exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
hi guys
which is the best hosting service for bot?
That's the main thing which is used, yes
U ready to spend?
no free pls
Just run it in a new terminal
what about heroku?
XD my computer is literally a celeron at 1.6 ghz and 2 gb ram
why though?
Literally heroku machines are 4x worse
And repl.it too
thats trash
Because it’s a pain to just put it on there and get it running
Not to mention you don’t even get a full month of free hours
really?
Yes
hmm
Why not just host it on your computer
so any other
You don’t need vscode to run python, just run it in a new terminal
AWS/google cloud hosting/microsoft services
Shift click in explorer + open powershell
Then you can type in python and it works
i used to use epikhost but they stopped free service
ok ill see about it
electronjs what did you expect
?
vscode runs on electron.js which can be slow
hmm
Don't use PowerShell
all you need is a terminal to run python
alacritty 💪
But you only need to run python in it so it doesn’t make any difference. Might have to change your execution policy to activate your venv, but whatever
why may i ask?
I’ve never customized my Linux machines 
Everything is default
actually ive heard that powershell is trash too
If someone gains access to yr bot, he will be able to run shell commands on yr command and powershell has admin access
What about Docker Containers?
?
very good idea
hmm ok
containerize your applications so you don't have to deal with window's garbage command prompt or powershell
How exactly
Idk, some eval command?
- docker is always good to know
You’re still going to be running docker run in powershell to actually start your bot
@cosmic agate maybe u should try docker
Lol
better than managing venvs, python versions, files, etc in powershell
u can use other pc
you know what, imma build a new pc
sure, that’s not the issue here either way ¯_(ツ)_/¯
It’s literally one command to start your bot @cosmic agate
if you're just gonna run python file.py then sure
ive been saving up so hopefully it will run on that
you said you had 4gb of ram atm?
you should be fine if you're just running a bot then
i am GONNA build a new pc
my friend gifted me a rx 550 but i dont know ill runn on that
I’m running a discord bot in a docker container on a trash vps, thing takes 20mb ram according to docker stats
You’re fine
including docker overhead?
?
Yep, if docker stats includes that
wow
so i suppose you all are giving a positive review on docker
It’s pretty cool actually
why would we not?
I see
XD ig yeah
hey
docker is awesome
hi
I have two other backend services and it communicates through grpc, though, so the bot just formats responses from those and doesn’t actually do much lifting itself
Ah, bot as a front end?
Seperation of concerns we call it
i have a while true if the bot on the while loop everything stop working till the bot finish any fix?
Yepp
Backend heavy lifting on one thing, frontend prettying up on another
as long as you're awaiting inside the while True
you yield control back to the event loop
Yep and I can just expose an api for analytics stuff or for users to view
get username of the person who initiated the command? im having trouble
Might be a good graphql learning opportunity
i have control of the loop i break when i finish
very cool, i'm doing basically the same thing
code?
ctx.author or ctx.user if it’s an interaction object
@client.command()
async def set_timer(ctx, arg):
am = discord.AllowedMentions(
users=True
)
arg = str(arg)
await ctx.send(f"timer set to {arg}")
while True:
now = datetime.now()
final = now.strftime('%I:%M') #12-Hour Format
#Final = now.strftime(%H:%M') #24-hour format
sleep(1)
if final == arg:
await ctx.send(ctx.author.mention, allowed_mentions=am)
break
Check your library’s docs
it's not the code working fine
yes but it's still blocking
Ohh that’s sick
ok
@client.event
async def on_command_error(ctx, error):
send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError)
if isinstance(error, commands.CommandNotFound): # fails silently
await ctx.send(f'{error}.')
elif isinstance(error, send_help):
_help = await send_cmd_help(ctx)
await ctx.send(embed=_help)
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s.')
elif isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the permissions to use this command.')
# If any other error occurs, prints to console.
else:
print(''.join(traceback.format_exception(type(error), error, error.__traceback__)))
NameError: name 'traceback' is not defined
do u have fix for main issue
what's the main issue?
how to fix
the bot stopping everything until loop's done?
the bot can do one job only
yesssssssssssssss
i will remove it
replace it with asyncio.sleep()
i tryid that
using .author i get stuff like
{<User id=580891703133732917 name='carterfr' discriminator='0001' bot=False>}
anyway i could do sm like
name = author['name']
disc = author['discriminator']
total = '{name}#{disc}'
``` idk 😂

That’s a User object.. you would need to check the docs to see all of its fields
However for your case you could do str(ctx.author)
ok lemme try rq
it returns
{<User id=580891703133732917 name='carterfr' discriminator='0001' bot=False>}
``` when i str it
Is that in a set or something
Seems like, well, traceback isn’t defined, so import traceback
oh
ok i did this but it returned: ```py
{'carterfr#0001'}
@client.command()
async def set_timer(ctx, arg):
am = discord.AllowedMentions(
users=True
)
arg = str(arg)
await ctx.send(f"timer set to {arg}")
while True:
now = datetime.now()
final = now.strftime('%I:%M') #12-Hour Format
#Final = now.strftime(%H:%M') #24-hour format
if final == arg:
await ctx.send(ctx.author.mention, allowed_mentions=am)
break
there is something blocking where it's?
on while loop
Seems like you’re adding it to a collection of some sort
What are you printing exactly
its the footer of an embed,
Requested by str(ctx.author)
im not sure how to diagnose my problem. im working with interactions in nextcord and mentions. Im printing out the mentions and its None even though the contents show it has some .. and it works fine in two other servers my bots in, just not a new third server
i fixed it easily i put an f after text=
any one can help please?
ask?
there is something blocking async
@client.command()
async def set_timer(ctx, arg):
am = discord.AllowedMentions(
users=True
)
arg = str(arg)
await ctx.send(f"timer set to {arg}")
while True:
now = datetime.now()
final = now.strftime('%I:%M') #12-Hour Format
#Final = now.strftime(%H:%M') #24-hour format
if final == arg:
await ctx.send(ctx.author.mention, allowed_mentions=am)
break
where
my guess is the "if final == arg:" is never set as true
there might be a better way to do that with tasks
can u give me it please









