#discord-bots
1 messages Β· Page 522 of 1
but you can check it if you want lol
Are you currently working on a project
kind of
Oh whats it about
bot for a discord server
What kind of bot
MEE6 + Dank Memer
But the name is not like exactly that
Whats its name
Manana Bot
its for my server
btw do yuo want me to do something rad @umbral carbon ?
@ashen notch What is the max int limit in python expressed like this (1e+1)
kind of like this 1.346778e+34575
I need help I have already asked question
Wdym by rad exactly idk what it means π
pinging an admin
(though he didn't respond ;-;)
Do you earn through your bots
no
but ngl its fun
and its a learning exp
and the skill sometimes pay off for some projects
Hmm Im new with bots and its fun but my laptop broke 2 days ago
Waiting for a response from the support
lmao what's the issue
So when i try yo turn it on with adapter connected its power button blinks and it doesnt turn on
I'm not an electrician I'm a programmer
ππ
π
why do people ask programmers to fix their electronics tho π€
like its literally on the name its electronics for electricians
what's with people's brains these days
@client.command()
@commands.has_permissions(administrator=True)
async def munban(ctx):
banned_users = await ctx.guild.bans()
for user in banned_users:
await ctx.guild.unban(user.id)
await ctx.send("Unbanned everyone.")
Thats my code ^
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BanEntry' object has no attribute 'id'
Thats my error^
I am trying to unban everyone
I think it is because alot of programmers being smart with computer
but it doesn't nececarilly mean that they're also smart with everything
hmm
is it in rewrite
Is it possible to have a bot interaction response without a button clicked?
I think so?
async def on_message(self, message):
msg = message.content.lower()
localdate = datetime.date.today()
obgend = datetime.date(2021, 11, 13)
surgeryend = datetime.date(2022, 1, 12)
medicineend = datetime.date(2022, 3, 13)
cmend = datetime.date(2022, 5, 12)
electivesend = datetime.date(2022, 5, 27)
casualtyend = datetime.date(2022, 6, 11)
ophthalend = datetime.date(2022, 6, 26)
entend = datetime.date(2022, 7, 11)
orthoend =datetime.date(2022, 8, 10)
pediatricsend = datetime.date(2022, 9, 14)
if msg == "posting":
if localdate < obgend:
def obg(localdate, obgend):
return (localdate - obgend).days
days = f"{obg(obgend, localdate)}"
print(days)
if days == 1:
await message.reply("Your Next posting `Surgery`, starts tomorrow.")
else:
await message.reply(f"Current Posting: `OBG`, {days} days to go.")```
Yesterday too it was showing 38days to go and today as well. Is something wrong?
for user in banned_users:
await client.unban(user)
^^
Oh
ahh
but you can use discord.utils.get to get the member object with just the id
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'unban'
hm
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BanEntry' object has no attribute 'unban'

what
@client.command()
@commands.has_permissions(administrator=True)
async def munban(ctx):
banned_users = await ctx.guild.bans()
for user in banned_users:
await user.unban()
await ctx.send("Unbanned everyone.")
hmm........................................
I think its in rewrite so maybe await ctx.guild.unban(user)?
I just removed the id
I tried that too
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BanEntry' object has no attribute 'id'
its a ban entry object
not a user/member object

I found a way to get all banned members
I need help. Someone help me
banned_users = await client.get_bans(ctx.guild)
what
I have already asked my question
where
I got it to work, I did
for entry in banned_users:
await ctx.guild.unban(entry.user)
nice
Here @ionic path
where is the code to the aki command
Scroll below that I have sent a link of hastebin
what the...
Then I get attribute error
Why is this happening?
@commands.command()
async def akinator(self,ctx):
await ctx.send(embed=discord.Embed(title="Akinator is here to guess!",description="'Y' is Yes, 'N' is No, 'P' is Probably, 'B' is Back",color=discord.Color.random()))
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ["y", "n","p","b"]
try:
aki = akinator.Akinator()
q = aki.start_game()
while aki.progression <= 80:
await ctx.send(embed=discord.Embed(title=q,description="Your answer:(y/n/p/b)",color=discord.Color.random()))
msg = await self.bot.wait_for("message", check=check)
if msg.content.lower() == "b":
try:
q=aki.back()
except akinator.CantGoBackAnyFurther:
await ctx.send(discord.embed(title=e,color=discord.Color.random()))
continue
else:
try:
q = aki.answer(msg.content.lower())
except akinator.InvalidAnswerError as e:
await ctx.send(discord.embed(title=e,color=discord.Color.random()))
continue
aki.win()
await ctx.send(embed=discord.Embed(title=f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?(y/n)\n{aki.first_guess['absolute_picture_path']}\n\t",color=discord.Color.random()))
correct = await self.bot.wait_for("message", check=check)
if correct.content.lower() == "y":
await ctx.send(embed=discord.Embed(title="Yay\n",color=discord.Color.random()))
else:
await ctx.send(embed=discord.Embed(title="OOF\n",color=discord.Color.random()))
except Exception as e:
await ctx.send(e)```
have you tried it?
Yes
Shall I send ss
How do I make a random colored embed have the same random color as another embed like this?
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
put the random color value to a botvar
guys
why does my discord bot keep saying this interaction failed in buttons even tho it works
How could I create temp roles
datetime.date.today() gets the date from what timezone by default?
UTC
how do i print the username without mentioning them?
lemme try
That might also add the #7373
i got this error: Unresolved reference 'user'
Show code
Show the command your using it in
import discord
from discord.ext import commands
import base64
def read_token():
with open("token.txt", "r") as f:
lines = f.readlines()
return lines[0].strip()
token = read_token()
bot = discord.ext.commands.Bot(command_prefix = '.')
@bot.command()
async def b64(ctx, task, string):
if task == 'encode':
stringBytes = string.encode("ascii")
b64Bytes = base64.b64encode(stringBytes)
b64String = b64Bytes.decode("ascii")
embed = discord.Embed(title = f"Encoded string for {user.name}")
bot.run(token)```
lemme try'
thanks works now
Ctx.author
Also I wouldn't use discord import
Bit late
But he already got the answer
Cool
I'll check out your bot
hey how do i print the nickname for a user?
instead of username with the # tag
@slate swan @waxen granite
I mean the last code prints the nickname only
nah it printed my username with the # tag
Use the .nick
ctx.author.nick
Np
i have a command that takes 2 arguments
in case someone enters a third argument by mistake/accidentally enters a space, how do i print a error message for that?
Since it's not an error, you can't. And you don't need to either. It won't affect anything.
ok cool
i got a huge error
my command takes 2 arguments: .b64 encode/decode string
now i want to print a list of commands when the user types '.b64 help'
but i get an error that says 'string' argument is missing
how do is solve this?
Can we see the command def
yeah sure
how do i turn the circled part to green color?
there's a thick black line right...
can i turn that to green?
The colour code of the embed. Aliased to color as well. This can be set during initialisation.
color or colour?
colour
aight
where do i add it in the code?
i typed it inside the embed def, and i got like 5 errors
Embed(colour=...)
Try it and see
You can also do discord.Colour.green()
!d discord.Colour.green
classmethod green()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour") with a value of `0x2ecc71`.
hey thanks, works
(:
thanks #discord-bots , i finally finished coding my bot
and it's my first ever Python project!! π
i am getting this error. please help me
@client.command()
@commands.has_role('βοΈ»γgiveawaysΦβββδΈ')
async def gcreate(ctx, time = None, *, prize = None):
if time == None:
return await ctx.send('Please include a time!')
elif prize == None:
return await ctx.send('Please include a prize!')
embed = discord.Embed(
title = 'Giveaway!',
description = f'{ctx.author.mention} is giving away **{prize}**!'
)
time_convert = {'s':1, 'm':60, 'h':3600, 'd':86400}
gawtime = int(time[0]) * time_convert[time[-1]]
embed.set_footer(text = f'Giveaway ends in {time}')
gaw_msg = await ctx.send(embed = embed)
await gaw_msg.add_reaction("π")
await asyncio.sleep(gawtime)
new_gaw_msg = await ctx.channel.fetch_message(gaw_msg.id)
users = await new_gaw_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await ctx.send(f'Congratulations! {winner.mention} won {prize}!')
here is my code
pls help
hey, i'm on Heroku trying to run my bot
pls help me
i'm getting this error
so in the 'requirements.txt' file, what do i type in? 'install discord.py' or just 'discord.py'
this is my code
ok np
everyone can get better
what do i do?
@ocean leaf
so no 'install'?
only discord.py
aight tysm
no need of pip install
np my pleasure
someone pls help me
Alright ill try my best
ok pls
which ide are u using?
pycharm
oh
do pip freeze so you'll get all requirements
but his way of installing discord.py Rewrite didn't work for me
i highly recomend u to write ur own code
where? in the PyCharm console?
idk abt pycharm much u try that
u can use cmd
I agree with you, helps you learn a lot more.
yes
aah someone pls help me
better do in cmd prompt and copy that and paste in requirements.txt
im really sry i dont know whats wrong
do i have to do anything after that?
like unfreeze or anything lol
nah no
aight cool
just copy that and paste and u r good to go
Hey @errant abyss!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
bruh i'm getting a huge set of text
https://paste.pythondiscord.com/ paste here
save and send the link
coz thats all the requirements u have downloaded through pip
oh ok
cmd
hm ok
i went to the dir where i had my bot files and did cmd
i just did this and i got everything, i just opened the cmd prompt and typed pip freeze
ok
i did too
still i don't see 'discord.py' there
maybe its cuz i used anaconda for this
oh
see this, so do i type 'discord' or 'discord.py'
??
both are good ig
What event happens when someone boosts the server?
Plz help me
member update
Hmm
check if the member before doesnt have the booster role and the member after does
Hmm.. C- c- can you send me any sample code?
Umm... If you don't want to you don't have to.
@bot.listen()
async def on_member_update(before, after):
if before.guild.premium_subscriber_role not in before.roles and before.guild.premium_subscriber_role in after.roles:
# The member just boosted
You are really good helper Ale!
this works too right?
@bot.listen()
async def on_member_update(before, after):
if {before.guild.premium_subscriber_role,} == (set(after.roles) - set(before.roles)):
# do the stuff
How do I set premium subscriber role???
yea
nope
you don't need to
hello
Ok%%
it defaults to server booster role
Kk thanks
@sweet pilot
Hello!
Hey?
@unkempt canyon
Stop ping
wanna get banned?
my name is @elfin quest
Hello, do you need moderation assistance?
!ot
Off-topic channels
There are three off-topic channels:
β’ #ot0-psvmβs-eternal-disapproval
β’ #ot1-perplexing-regexing
β’ #ot2-never-nesterβs-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
He don't need to I guess
@elfin quest Do you?
Why you pinged mods?
yes
What do you need?
Kinde mods
he's new to discord I think
It's possible.
Haha I also see his profile
for me personally, I didn't knew it was bad to ping when I first came to discord
I mean unnessary pings
@elfin quest Only ping moderators if you need help with someone breaking the rules or code of conduct of the server. If you need help with Python, you can ask in #python-discussion or one of the topical channels, or you can check out #βο½how-to-get-help.
haha me too. I evan didn't know what mod is!
Pinging moderators is fine if you actually need a moderator. That's why the role is pingable.
let's go to #ot2-never-nesterβs-nightmare and talk @sweet pilot
But we have a lot to do, so we prefer if you don't waste our time unnecessarily.
Kind mods
users = await new_gaw_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send(f'Congratulations! {winner.mention} won {prize}!')
```how do i use this in cogs?
i mean i m using cogs but i got this error
self.bot.user
ok
I should use cogs too
ok
yes
π
hey is there any way to make my repo public and only my token file private?
use gitignore
Pluralsight Guides
ahhh man made a bot now it says it's offline
i don't have an 'on_ready()' function in my code. is that the problem?
no
then why's it offline?
yall got any common error fixes?
client.login() maybe? i don't have that either
no
It's client.run() and yes you need that to be able to make the bot online
i got that
lemme check with my tokens and stuff
Yes, client.run("YOUR_TOKEN")
i fixed my token issue. now the bot's online but my commands ain't working ππ
now it's back offline
follow the tutorial properly, cba to get into this
Both are bad tho
oh
imma try turning on automatic deploys on Heroku
oh, ok, now it works
i had to change my token in my repo
hi if my bot is running from one place and i re-generate a token will my bot be stopped from there? if yes then amazing else F
yes or no
It will stop
alright thanks
can tasks.loop have parameters?
no
just use loop.create_task if you want some parameters to be passed
hm
if I created the task like that would it automatically run the task or no
due to the fact that with every request you send, you must send your token, it will stop working right away
it would, assuming your loop is running, which it is
hm
keep in mind just use an infinite loop if you want it to persist
make your async function a while True or similar
why
does the lib support cog support for that yet?
hello,
so I am using github repo to host my bot
and i have a bot which plays sound files the thing is that the sound files are just on the repo and I was them to be in a folder named sound but when I put the files in sound its showing out of directory so how do I add the directory in my codes of sound folder these are the codes
@bot.command()
async def test(ctx: commands.Context):
voice_channel: discord.VoiceChannel = ctx.author.voice.channel
print(voice_channel.name)
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio("sound.mp3"))
while vc.is_playing():
time.sleep(.1)
await vc.disconnect()```
Have you tried putting its full path
that is the thing how do I know the path
like even if I get it know where to enter
its like bot/main.py
Uhh just copy the path and paste it in FFmpegPCMAudio?
like bot/sounds/sound.mp3?
Sure ig
alr
How do you host a bot on github?
can you?
no
^
not hosting i am using github for the hosting services to get the coding file and requirements
oh ok
you can use replit, or local host
like?
You should not use Repl.it to host your bot.
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
-
The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
-
You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
-
Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
-
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
- This means any file you saved via your bot will be overwritten when you next launch.
what type of file
Also , they Didn't updated their Python version for a long time , it's still 3.8
yes, 3.8.12
I tried Sqlite and it gets reset everytime
how do I login into my discord bot?
using my token in discord bot client website? the website isnt loading idk why
That's not allowed though
i know
Then it's still probably the websites fault
Why is it required tho?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
not working
an api wrapper like discord.py would do all the things it can do
to see in how many major servers is my bot is
- They use a shared IP for everything running on the service. This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
You mean on a single pc?
just use client guilds to get a list of servers and check the member count or anything else you want to
No just on the same ip
*client.guilds
so I atleast can show the other discord server mods that "look my bot is int server with 5k members" so they can take my bot in
ohh
so if anyones bot gets banned then mine gets banned too?
- This means your bot will lag a lot as it gets bigger.
I doubt any big bots use replit
They will remove your bot instead if they see you logging into it with that web~
they use paid hosting like apex and stuff
It's a privacy breach
yes
Yes because of this exact reason
you can do self hosting and stuff
or open a hosting service by yourself
raspberry Pi , or there are many reliable services who provide web servers
You can just buy a raspberry pi if you're planning on hosting a medium sized bot
yeh
i have a bot which is in 100 servers and codes worth of 700 lines is it medium? or low
repl is more of a ide then hosting service
idk heroku is working ok for my bot hosting
None of them are meant for bot hosting , so nah for both of them
yeah heroku is mostly use for web hosting and stuffs
o h
If you want free hosting you can try something like trial of google cloud or AWS
aws is paid right?
they give some trial period
how do people run code in Visual Studio then?
you can do it ofcourse , but it won't make your bot run 24*7 like they do in web servers
use pycharm
I have no idea
hmmm
then how long does it run
You literally just press the run button
o k
what you can do is take a cheap mini laptop and than install pycharm or any other code editor and paste the codes and click run
and also install packages and path
As long as you have internet connection , and you don't close vsc or use the pause button
and BOOM you are doing a self-hosting for free
o
;- ;
mini?
I self-hosted a bot for a week on my pc
with some downtimes ofc
how do I add space after the command like
@bot.command()
async def help <words>(ctx):
await ctx.send('commands')
so the thing is suppose i have 2 help commands of different category
1 help show image commands and 2nd video help commands so how do I make the help command use space
!help videos or !help image
when I put space after help and type something it shows syntax error
is there a way to make my discord bot look like its on phone
use another input variable
no , not without monkey patching it it's not suggested to do so since it may break stuff
and do an if command
how to ignore @ everyone and @ here in user.mentioned_in(message) ?
i have afk commands
which also reply user when mentioned @ here or @ everyone
:/
!d discord.ext.commands.Bot.group
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
Use a command group
me ? :/
It was for panda
ok I will try that
Well it returns true by default , you can probably try py if user in message.mentions
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
??
it also worksbut the prblm is it react in @ everyone and @ here also
I don't think you can change it , user.mentioned_in does not check if a particular user obiect is mentioned
It can be roles and everyone/here roles as well
can i check if message.content have everyone or here?
or just tell pls that can i check if someone reply a user
if the ping is a reply?
.
but i don't want everyone and here
i have a option to use <@!userid>
but if i will use it it will not react in replies :/
how to show a part of a webpage ? like for in you tubes case a video
iirc its html metadata
ok got it
Get the role oject > edit it
also anyone else having problems creating folders on the webclient
role = role
role.edit(name=name)
which params do i need?
https://discordpy.readthedocs.io/en/latest/api.html#discord.Role.edit > Editing the role
https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_role > Getting the role
like i wanna input the current role name thn input i name i want it to change to
=Edit_role HI BYE
like this
Add an arg beside ctx I guess?
can u type it for me?
maybe learn more python
hmm
functions helped me learn more about arguments
!e
def function(role, new_name):
print(f"Role: {role}\nRenamed To: {new_name}")
print(function("Member", "Cool Kid"))
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
001 | Role: Member
002 | Renamed To: Cool Kid
003 | None
like that
ctx: commands.Context, role: discord.Role, *, name:str) lol
then how is the video playable in discord ?
anyone know how to send dms using dislash.py
maybe because discord made it that way? idrk lol
!d discord.Member.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
or do we have to stick to the old fashioned way
i am talking about dislash
so?
its the same lol
nothing changes about discord.Member.send in discord.py and dislash
is there anyway to send a dm only using dislash not discord
@fair axle most things dont change
k thanks bye
just support for slash commands and stuff lol
No problem helping you solve your question
π
just use pycord
no
hi, is it possible to trigger a link in an embed to perform a function instead of it being an url link?
Like actually change the content inside the embed? What are you getting at.
no edit the embed
change the content = edit, so i guess were on the same page.
like...i do a search of my sql database...it returns 20 matches in an embed..i'dlike to be able to click on the one i want and have it trigger a function
like having it a url link...but not a link, have it trigger foo function instead
Why not just use a paginator. You can do your idea but you'd always need to open the webpage.
example...enbed has 3 choices(links)..clicking on one would send 'you clicked this one' to chat
no buttons, emoji reactions, but clicking the actual content in the embed
Like i said you can do that but then a webpage would always open, not to mention the amount of effort it would take to create such a thing.
I can't see a method without overengineering the crap out of an embed.
because youre missing access for what youre trying to do
Hey how can I make like if someone votes my bot then the bot will dm them automatically whenever they vote
Disnake
Alec could you maby help out over at #help-cheese ?
yeah top.gg has a library for that
@bot.command()
async def challenge(ctx, member: Member):
if str(member.status).lower() == discord.Status.online:
return
if str(member.status).lower() == discord.Status.dnd:
await ctx.send("Hmm, it appears they don't wish to be disturbed.")
if str(member.status).lower() == discord.Status.idle:
await ctx.send("Hmm, The person you have challenged is idle")
if str(member.status).lower() == discord.Status.offline:
await ctx.send("Hmm, it appears they'r offline.")
do you have presence intents enabled?
no matter the status it will send Hmm, it appears they'r offline.
Ok, where can I get that?
no idts
anyone know how to implement buttons? I looked in the docs and I dont think they have it there yet
https://discord.com/api/v9/channels/{gcID}/call/ring
why does a post request to this not work
bots cant interact with groupchats
if i was to use a user token to send that request would it count as selfbotting
yes
can u tell me how to ddo so??
!d discord.ui.Button
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.
F
k ty
the buttons are available in dpy v2.0
ty
and how would these objects be sent with a message
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
some examples can be found in the master branch's examples folder
ah alr ty
Would it be okay if I move all my bot events to a separate file, and then later make my code run that file? I have too many events and just wanted to tidy my main bot file up
Yes
ideally you want as little as possible in your main.py file. The less you have in there the less you need to restart your bot when you change something (Important once it's big enough/you start caching things, etc)
in cogs you just use @commands.Cog.listener() instead of @bot.event/@client.event
Thanks!
I wanna make a music bot, I currently use youtube-dl, is there a better alternative?
!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)
wavelink was a better alternative, but its not maintained anymore. There a small "forks" or librarys which are based off wavelink, for example https://github.com/cloudwithax/pomice . But in the moment youtube-dl is the way to go I think.
Ok
How can i add currency system to my bot
you should do some research into databases
How
Well research different types of databases and find one that you like best, i'd recommend postgresql
then look at how it's implemented in python and then a basic economy system just consists of storing currency data about individual users
For some reason I have 2 warnings and I can't seem to get why because I didn't have it yesterday and I haven't changed the code.
https://retard.work/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
why it gives an error
File "main.py", line 111
@nsfw.error(ctx, error):
^
IndentationError: unexpected indent````
@cleint.command()
@commands.is_nsfw()
async def nsfw(ctx):
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
@nsfw.error(ctx, error):
if isinstance(error, NSFWChannelRequired):
await ctx.send(f"Hey! {ctx.author.mention}, sorry but i can't submit nsfw content without nsfw category.")````
@cleint.command()
because your error handler is inside of your command, and you have wong indentation for async with aiohttp.ClientSession() as cs:
Mention if you know
A good example for a free vps?
maybe try renaming the lambda inter to like lambda i, i'm sure i've had this issue before i forgot how i sorted it
since you have a variable called inter
Bro, thanks LOL
none really, if you want solid hosting you need to pay
Worked like a charm
sweet π
i dony want a solid one
solid being anything that's actually viable for discord bots
Nevermind, still got the same thing, PyCharm was just tripping for a second
pahaha, does it give you any suggestions?
Nope, still the same thing
Also tried the suggestion thing but then it just gives me this https://retard.work/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I have an idea on why it's doing it, but if I don't have that part in the code the rest doesn't work
i'm not sure, that's just pycharm being pycharm. it's probably a super simple fix
no error but command would not respond
@client.command()
async def nsfw(ctx):
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)```
Yeah but I can't seem to figure it out and it's annoying because it's my shitty messy code to test a kind of working Ticket system 
And I need it for my server
does the code still work though? it's only a warning
Well the only command in it works, but the @command.Cog.listener() doesn't, which is all the code to make the buttons work etc
every warning shouldnt block the code, but if the warning was right, the problem is in your code and itll block the execution of your bot
So people can use it to open/close a ticket
yeah i know this, and I do know what the problem is but without it the bot wouldn't work and I have no idea on how else I could do it since it requires me to use ComponentsBot
And I can't like put it in my main file because that would block out the rest of my bot
It's not like it's working right now tho
if your bot needs it and it blocks your bots execution, theres no other way than finding a workaround or just using another library for it, the easiest thing to do is to just delete the feature if its necessarily required for your bot but is blocking the execution of your bot without any fix
I haven't found a workaround yet, but maybe you have an idea
i have never worked with componentsbot
Neither have I, this is my first time too
so perhaps there should be someone to assist you otehr than me
I hope so
you can try asking in #python-discussion
or making a help channel
hello
how to create dashboard for my bot.
With login and communication from web to bot
what do these errors mean
you'd need to use auth for discord and ipc
auth??
well you'll need to use auth to let users login
idk how to do it
you'll need to research then
what should i search
ok thanks
from discord.ext import commands, tasks
from itertools import cycle
status = cycle(['status 1', 'playing under construction'])
class Example(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
chnage_status.start()
print('Bot is online.')
@tasks.loop(seconds=10)
async def change_status():
await client.change_presense(activity=discord.Game(next(status)))
@commands.command()
async def ping(self, ctx):
await ctx.send(f'Pong! {round(self.client.latency * 1000)}ms')
def setup(client):
client.add_cog(Example(client))```
y do u have self in an on_ready event?
can someone explain to me why this code does not work?
(The bot does not detect that I pressed the button)
@commands.command()
async def button(self, ctx):
await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
interaction = await self.bot.wait_for(
"button_click", check=lambda inter: inter.custom_id == "button1"
)
await interaction.send(content="Button Clicked")
if i dont put self this error comes
@commands.command()
async def ban(self,ctx, member: discord.Member, *, reason=None):
if reason == None:
embed = discord.Embed(
description=f"You have been banned in {ctx.guild} reason:None", color=0xFF0000)
await member.send(embed=embed)
await member.ban(reason=reason)
else:
embed = discord.Embed(
description=f"You have been banned in reason:{reason}", color=0xFF0000)
await member.send(embed=embed)
await member.ban(reason=reason)
embed = discord.Embed(
description=f"Successfully banned {member}", color=0x3FFF00)
await ctx.send(embed=embed)```
why doesn't this work?
huh
yessir
so uhm how to make a music bot? using replit
π
you have Context somewhere and it's not defined
wtf
dunno
i can code some parts
^^
this isnt where Context is located tho
wym
What do I mean?
I'm saying that ur error has nothing to do with that command I guess
the problem isnt in your ban command
oh
you have Context somewhere and it's not defined
Do CTRL + F and search Context
my friend added a file π mb sryy
@dapper rain We don't allow links through URL shorteners.
kewl
!warn 827793666172780604 Please don't advertise your bot here. We aren't an adboard, as per our #rules and #code-of-conduct.
:x: The user doesn't appear to be on the server.
@client.event
async def on_message(message):
if message.author == client.user.mention:
return
if message.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)
if any(word in message.content for word in sad_word):
await message.channel.send(random.choice(encouragements))
client.run('')
in this code i want to add mention atribute so that it mentions the user typing the command
if you want to mention the member, just use message.author.mention
how to display the body of a website in discord embeds ? like youtube links ?: https://www.youtube.com/watch?v=dQw4w9WgXcQ
The official video for βNever Gonna Give You Upβ by Rick Astley
βNever Gonna Give You Upβ was a global smash on its release in July 1987, topping the charts in 25 countries including Rickβs native UK and the US Billboard Hot 100. It also won the Brit Award for Best single in 1988. Stock Aitken and Waterman wrote and produced the track which w...
ctx = client.get_user(663398794204938255)
await ctx.send("mini test")```
nonetype has no attr send
hi
the user can't be found then
@client.event
async def on_message(message):
if message.author == client.user.mention:
return
if message.author.mention.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)
if any(word in message.content for word in sad_word):
await message.channel.send(random.choice(encouragements))
client.run('')
showing an error
if message.author.mention.content.startswith('$inspire'):
AttributeError: 'str' object has no attribute 'content'
me id is 663398794204938255
um
in @client.event on_ready
whenever bot goes online it messages me (i host bot on repl.it so it reboots every 9 hour or so)
temporarily hosting there, ill buy a hosting service once discord verifies my bot (verf unlocked tho)
its a weird error i rarely get
guys why does this not show anything?
client = commands.Bot(command_prefix="!", help_command=None, intents=discord.Intents.all(), activity=discord.Activity(type=discord.ActivityType.watching, name='English Podcasts'))
@client.command(name="mean", aliases=["def"])
async def mean(ctx, *, word):
async with ctx.typing():
try:
url = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
try:
content = url.json()[0]
embed = discord.Embed(title=word, color=ctx.message.author.color)
except:
await ctx.send("Word Not Found")
return
try:
info = content["meanings"][0]["definitions"][0]["definition"]
except:
info = "Not Defined"
try:
synonym = content["meanings"][0]["definitions"][0]["synonyms"][0]
except:
synonym = "No Synonym"
try:
antonym = content["meanings"][0]["definitions"][0]["antonyms"][0]
except:
antonym = "No Antonym"
except Exception as e:
print(e)
embed.add_field(name="Meaning", value=info)
embed.add_field(name="Synonym", value=synonym)
embed.add_field(name="Antonym", value=antonym)
await ctx.message.send(content=None, embed=embed)
no errors and no message
it will be await ctx.send or await ctx.reply if u wanna reply
i tried that too
nothing happens
it isnt giving me CommandNotFound error
you could use appinfo py bot.appinfo = await bot.application_info() await bot.appinfo.owner.send("x")
yep
alright ty
anyone can help π₯²
with this
how can I check if the message has a text?
like?
sure, wait
message will always have text, what do you mean
attachment only messages
try this
if len(message.attachments)==0:
#do stuff
wait
this will check if the message doesnt has text
no it won't, that will check if the message has no attachments
attachments and message content aren't the same
π
it was fine
works when if len(message.content)!=0:
sure
thank you
welcome sire
ah one more thing
you could probably do py if len(message.attachments) > 0 and not message.content:
why tho if the shorter works
you said you want to check if a message has no text?
if it does
it should be ==
not !=
you can have messages with attachments and no message content
!= is right
idk
checking just for attachments doesn't check for text lol but okay
i need help too π₯²
client = commands.Bot(command_prefix=".", help_command=None, intents=discord.Intents.all(), activity=discord.Activity(type=discord.ActivityType.watching, name='English Podcasts'))
@client.command(name="mean", aliases=["def"])
async def mean(ctx, word):
try:
url = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
try:
content = url.json()[0]
embed = discord.Embed(title=word, color=ctx.message.author.color)
except:
await ctx.send("Word Not Found")
try:
info = content["meanings"][0]["definitions"][0]["definition"]
except:
info = "Not Defined"
try:
synonym = content["meanings"][0]["definitions"][0]["synonyms"][0]
except:
synonym = "No Synonym"
try:
antonym = content["meanings"][0]["definitions"][0]["antonyms"][0]
except:
antonym = "No Antonym"
embed.add_field(name="Meaning", value=info)
embed.add_field(name="Synonym", value=synonym)
embed.add_field(name="Antonym", value=antonym)
await ctx.send(embed=embed)
except Exception as e:
print(e)
no error and no response
but can I send all the attachments at once using webhooks?
requests is blocking, use aiohttp
it was working fine when it was a normal program
now i changed it to bot code
yes but requests is still blocking, use aiohttp
how do i use that lol, i need to check
look at aiohttp.ClientSession
well for one, pretty sure you have to convert e to str
ah okay
except Exception as e:
print(e)
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
logger.addHandler(handler)
``` how do i send this in a webhook?
well last time I tried printing an error without converting it to a string first it gave me an error so
ah
okee thank you XD
hey can anyone tell me abt discord rate limit for messages per minute
ah well...it worked when I removed the try and exception statemnets lol
its 10 per second ig
otherwise ask someone who knows exactly
hmm k
Me dumb
yeh it's bad to use plain except Exception because it will catch any error, it's better practise to only block errors which you expect
Ye bro, thank you for your time
no error but command would not respond
@client.command()
async def nsfw(ctx):
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)```
can somone explain me why my discord bot can't join a voice channel?
put a print at the top of the command to see if it's actually being registered
Well not copying code is a start.
?
pass_context has been deprecated for like 4 years.
mate I tried 5 differents things and nothing is working
lol
its await ctx.author.voice.channel.connect()
still not working
what dpy version ?
3.9.7
huh ?
thats your python version isnt it
^^
yeah?
await ctx.author.voice.channel.connect() works for me
i asked dpy version
print(discord.__version__)
it is 1.7.3
wym
weird
its even in the docs
What does it say?
nothing it just doesn't join
debug it
i mean its in the examples https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py
but I know that the code is right and I've setted the permissions for the bot also right
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!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)
ok i was just talking about the join and leave part
which is there in that
i didnt tell them to use it
like a year or 5
i think its unlimited time
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
logger.addHandler(handler)
``` how do i send this in a webhook?
open the file and read it
Don't copy old code
It wont work most of the time
z = 10
y = 15
input('which is bigger z or y guess?')
if input = ('z'):
print('wrong')
else:
print ('correct')
im trying to get the bot to play a guessing game i have much more of the script but this is where the focused problem is
not discord.py related but you need to assign the input to a variable so user_input = int(input('which is bigger z or y guess?'))
then if user_input == z:
File 'main.py', line 17
if user_input == z:
IndentationError
you need to indent it properly
You can't get user input like that
input will block the script, you are going to want wait_for
hi, so i have a while loop, gathering information from an API. and once its running no one else can run commands or myself. any fixes?
could you show us the code
because requests is blocking, look at aiohttp.ClientSession for your requests
ok
Soz I got a loop that reads reaction to a post that I am using to store statistics. This works great; however, I want to capture replies to my bot's posts and use them as feedback. I can't seem to locate any documentation on how to achieve that.
I do seem message.channel.last_message.reference.message_id but this would mean I have to read the entire channel history and pick out the matching reference IDs... Hoping there is a better way.
Maybe on message coupled with an if that checks if itβs a reply
someone help me pls
await channel.send (f'Welcome to the Server ' {ctx.author.name} ' to ' {ctx.guild.name} ' Have fun!')```
Try this
Give me a sec
okay
Burh
@slate swan You don't even have ctx there
So just do:
await channel.send (f'Welcome to the Server ' {member.mention} ' to ' {member.guild.name} ' Have fun!')
This should work
if I have a link as an example, how do you do it that the last 10 characters are automatically removed?
What do you mean by that @runic jackal?
for example under this link:
https://cdn.discordapp.com/avatars/706884094856003655/dde97c79831663846a623fa220947b86.webp?size=1024
the last 10 characters are removed
So you want to remove the "?size=1024"
Can you hover over it with your mouse and show what it says?
yes
Huh, maybe
@runic jackal You have to give me your context. Does the bot has to do that?
Iβll look into that thanks
Like the user sends a link and the bot just removes the last 10 letters?
bei einem bestimmten command soll die avatar url auf diese weise gekΓΌrzt werden
nvm
Just try this:
await channel.send (f'Welcome to the Server {member.mention} to {member.guild.name} Have fun!')
Also als Beispiel
Jemand macht !avatar
Dann schickt der Bot den Link des Avatares rein, aber die letzten 10 Buchstaben sollen gelΓΆscht werden?
ausversehen auf deutsch geschrieben xD
ja
passt schon
Wieso machst du's nicht einfach mit embeds? Dann brauchst du den Link garnicht und das Bild wird sofort angezeigt @runic jackal
Schau, wie hier
weil ich den link noch fΓΌr eine api verwenden mΓΆchte, und die api akzeptiert nur links ohne die letzten 10 zeichen
also ohne das "?size=1024"
ja
i think its correct
Dann kΓΆnntest du folgendes versuchen:
av_link = https://blablabla
print(av_link[:-10])```
Das wΓ€re jetzt zum printen. Ich weiΓ jz nicht genau was du damit vor hast
Allerdings bin ich mir ehrlich gesagt nicht ganz sicher ob das nur mit Strings geht. Und auch nicht, ob links als Strings gelten...
Im Prinzip denke ich schon. Das mΓΌsstest du dann testen. Wenn's nicht geht musst du den Link in einen String umwandeln und dann die 10 Characters wie oben gezeigt lΓΆschen
@runic jackal
perfect
Danke, Funktioniert ^^
Kein Ding^^ Mache ich gerne
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
YH I'm sorry but this would take forever in english...
Event loop is closed
im need help
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash.utils.manage_commands import create_option
import config
client = commands.Bot(command_prefix = '.', intents = discord.Intents.all())
slash = SlashCommand(client, sync_commands = True)
@slash.slash(name = 'hi', description = 'ΠΏΠΎΠΏΡΠΈΠ²Π΅ΡΡΡΠ²ΠΎΠ²Π°ΡΡ', options = [{"name": "member", "description": "ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ", "type": 6, "requied": False}], guild_ids = [680754330022051890])
@client.command(aliase = ['hi'])
async def hi(ctx, member: discord.Member = None):
await ctx.send(f"ΠΠ΅ΡΠ΅Π΄Π°Ρ ΠΏΡΠΈΠ²Π΅Ρ, {member}!")
client.run(config.TOKEN)```
Full traceback?
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000015731E3D040>
Traceback (most recent call last):
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed```
So the code does not work?
yes
yes
Well I can not help then
Traceback (most recent call last):
File "C:\Users\marva\Desktop\python bot\main.py", line 19, in <module>
client.run(config.TOKEN)
File "C:\Users\marva\python\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\marva\python\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\marva\python\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\marva\python\lib\site-packages\discord\client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000015731E3D040>
Traceback (most recent call last):
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000015731E3D040>
Traceback (most recent call last):
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\marva\python\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\marva\python\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed```
oh how about you read the error you got
Intents?
I read
it tells you exactly what to do
You did not read the message?
Np, glad you found it
Rip
is there a way i can add a pause to a command output? without freezing the entire bot? what id like to do is make something like py await ctx.send(f'message 1') time.sleep(5) await ctx.send(f'message 2') but without freezing the whole bot, just delaying the second output. i can provide more detail if needed
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatβs New in 3.10βs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
thanks
How can i add reaction?
It says Unknown emoji
i tried :white_check_mark.: too (without the dot)
You need to use this format <:emoji_name:emoji_id>
and <a:emoji_name:emoji_id> if the emoji is animated
and where can i find emoji id?
also you can get the emoji and use its string
copy the emoji link and there should be an id in the url iirc
wait
There is a much simpler way
just use \ before the emoji and send it
It'll give you the format i told you
!this
no i meant for getting the id
Was seeing what you guys thought the best method for this would be. I'm trying to check posts in a certain channel for a list of emojis on a post..
For example. I have people add π¨ πΊ π² to posts sometimes. I want to check if those letter are there and if they are delete them
!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**...
Use this to get what reaction is someone adding and do further execution according to it
so it's not just one reaction but multiple
if they just add π¨ for example then do nothing
can you give me an example please?
You asked how to get the id of an emoji.
So there is a way you can get it quickly.
Like you send \
and you will get the name and id of that emoji (!this) in that text after you send it in a channel
\
- !thinkmon
Can I have events within commands? Or is that bad practice?
the id is always different
I want my bot to accept input from the user
Maybe I just do not understand
Thanks tho
Oh that is possible
You need to use bot.wait_for
How?
!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**...
Thank you
If the emoji is an unicode emoji then you need to use unicode string of that emoji
"\U00002705"
where did you find that?
im testing my error handler, this is what i currently have.
#role
@bot.command('role')
@commands.has_permissions(administrator=True) #permissions
async def role(ctx, user : discord.Member, role : discord.Role):
if role.position > ctx.author.top_role.position:
embed = discord.Embed(title=f'Error', description=f' This role is above your highest role!', color=0x2f3136)
return await ctx.send(embed=embed)
if role in user.roles:
await user.remove_roles(role)
await ctx.send(f"Removed `{role}` from {user.mention}")
else:
await user.add_roles(role)
await ctx.send(f"Added `{role}` to {user.mention}")
@role.error
async def role_error(error, ctx):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(title=f'Error', description=f' ^role [Member] [Role]')
await ctx.reply(embed=embed)
if isinstance(error, MissingPermissions):
embed = discord.Embed(title=f'Error', description=f' I do not have permission to manage this role', color=0x2f3136)
await ctx.reply(embed=embed)```
but when i test it, i get no output
for any of the errors (missing args and missing perms)
how can i get the creator of a channel in audit logs
!d discord.AuditLogAction

