#discord-bots
1 messages ยท Page 1124 of 1
you can either
12456532 the ID
sarth#0460 the username#discriminator
sarth the username only
you sleep?
what if theres another sarth?
oof
then Ima use the full username isntead lol
can we trade
User ids are unique
And also name with tag
but usernames can be same
me? and trade what?
like if i'll change my username to okimii
a ban would choose a random one from us
Don't
if we use !ban okimii
no you'll only have my last name not my first?๐
Ye
๐ i can have your first name as my middle name
๐๐
sorry not tradeable
Discord addict
stop and go to sleep
๐ค
..
btw oki, do you use some ide for rust?
i use vsc
same but i wanna escape the vscode addiction
neovim
ew
vim๐๏ธ๐๏ธ
notepad better
no u
whats the difference between nvim and vim?
vsc is like you sarth, i cant get enough of it๐ฉ
bro they teaching me :quit command as the first topic
makes me already give up
bro quitting is so easy
me stuck in neovim: 
idk why people complain about it, atleast not in normal vim
veovim is based on vim with some extra extensions iirc
๐
better syntax highlighting?
yeah and linting
Hi
sarth lets do something, i keep learning rust without procrastination and you learn neovim without procrastination๐ณ
productivity go boom
I was going to learn neovim and then I realised I'm lazy af
does anyone know how discord webhooks work?
i've been doing the same for a year
Is it allowed to ask people to join their server? I need 1 person to test my bot
use an alt
nvim with emacs = โค๏ธ
Webhooks are a low-effort way to post messages to channels in Discord. They do not require a bot user or authentication to use.
Why rust?
alts are kinda essential for bot dev
ill spam your mail now, thx
yea i got that part, but i want to find a way to send information to them
lol
ive already set up the code
๐ฑ
I just dont know how to send info to it
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
dont have one
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
i like this better๐
i still dont have a project idea smh
i did it, thank you
welcome
oh so it sends data compiled autmatically?
Guys use snipping tool
same i have that same file open for the past 5 days
sublime better
imma write hikari in rust ๐ ๐
same๐
serenity is already awesome โค๏ธ
Wth is serenity
discord API for rust
Oh
what means buckettype default?
you forgot wrapper
discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)
????
** Application Programming Interface**
API stands for Application Programming Interface. In the context of APIs, the word Application refers to any software with a distinct function.
an API doesnt really need to be a website which gives you json
Gn everyone
I'm sleeping now enough
the type of cooldown, like is it a cooldown for the server, a user , a member or a channel
i slept at 4 and woke at 8
so you mean, instead of buckettype i could take member?
!d discord.BucketType.member
No documentation found for the requested symbol.
Pls I don't want any conversation now
oh
!d discord.ext.commands.BucketType.member
The member bucket operates on a per-member basis.
i know that, but but but but i still prefer wrapper as it wraps all endpoints in an api but yes it can be named an api as it makes it easier for a user to interaction with the api๐ฅบ
thank youu
yep
im just sharing my exp ๐
true
OK nice
i love tohru
guess i'll use IDEA for rs
in vsc i just open an intergrated terminal and then i just do cargo run
i use pycharm for python because its too good to leave and emacs for rs and c
vscode all the way
nextcord.ext.commands.BucketType.member(2,3)``` can i do it like that? i want that after 2 commands they get a 3 sec cooldown. does it work like that?
vsc๐
@commands.cooldown(2,3, commands.BucketType.member)
oh okay thanks
does it have to be over async def or under?
oh okay
@commands.cooldown(2,3, commands.BucketType.member)
async def alex(ctx):
await ctx.send("@rugged tulip ist sรผร ๐")``` it will work like that right?
yep!
thank you for your help :)
and sorry that iam asking dumb questions, i just want to go sure
def decorator(function):
# the decorator takes a function then we have an
# inner function which takes the params for the `function`.
def inner(*args, **kwargs):
# these *args **kwargs are the args that have to be passed in `function`
...
return function(*args, **kwargs)
return inner
@decorator
def foo():
...
# is the same as
def foo():
...
foo = decorator(foo)
# --------------------------
# when u call foo, what basically happens is
# decorator(foo)(...)
# because decorator return inner the function call is
# inner(...)
๐ฟ
not in case of discord.py commands tho
cause the callback is called directly, not with mentioning them inside a decorator
but the terminology is same
๐ i misread
@bot.command(name="ban-user")
async def ban_user(ctx, member):
await ctx.guild.ban(member)
Whats the correct way to ban someone?
@slate swan
@commands.cooldown(2,5, commands.BucketType.member)
async def alex(ctx):
await ctx.send("@rugged tulip ist sรผร ๐")
``` how can i make that if he still sends a command that my bot will say something like? stop?
I don't know why but.....that command seems too naked poorly handled
wdym?
that should be fine just type hint member with discord.Member like async def ban_user(ctx, member: discord.Member):
bruh
fr
I'll be quiet on this one
Yeah I havnt gotten to that yet
why discord crashes on me so much
windows?
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/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/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
?
guess he doesnt like you
make an error handler
i literally cannot click "jump to message" without it literally crashing. x_x
what
2mb of ram moment
guys how can i add a error message so if someone who doesnt have the correct perms it returns a inter.reply in a embed
phone?
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "discord.member" failed for parameter "member".
inter.reply?
which lib?
how are u calling the command?
yeah android.. and its one of the newer updates coz if i downgrade it is fine
discord.py v2.0 i just made it shorter
I try to do !ban-user @rich otter#1111
it raises a commands.CommandOnCooldown which you can handle using an error handler
so thinking of just running an out of date version ...
probably not the issue but have you cleared your cache?
oh okay, which error handler? i have 0 knowledge of error handlers, ive never used one in my life
just do !ban @paper sluice u dont need the discriminator
let me try, not as of yet
sometimes discord has breaking changes that can make your client crash if e.g a icon is in cache
doesn't work either
oh wait, u did discord.member instead of discord.Member
they have interaction: discord.Intraction, i mad mine inter: discord.Interaction , its fine
yeah that's completely a fine naming convention, I have an error handler example with an explanation following, so read it too
!d discord.ext.commands.Bot.on_command_error this event
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
Now it worked. Whats the difference between capital M and little m. And why do I need to type hint?
it doesnt show what i need
...?
so lets say the user doesnt have the permissions i want it to return a error
thank you
is interaction.message.author valid ? like ctx.message.author?
discord.Member calls the class on the member param and it tries to convert it to that object
basically it tries to the convert the str "Ryuga#1114" to @paper sluice
typehints are just a theory in python but they are used by dpy for conversion of types and capital words always should mean a class as they should follow pep8s class naming which is always UpperWord
Nice
But why does type hinting work? I thought type hinting just told the func what type the should be. Wouldn't it try to convert it anyways?
? i want to get message author.
typehints are just a theory in python but they are used by dpy for conversion of types
dont ignore me๐ก
To Python, typehints don't mean anything. They're essentially comments. Discord.py takes a different approach in that it leverages the typehints to actually do something
if u dont type hint, discord.py would think "Ryuga#1114" is a str and treat it like that
typehints in python are just a theory, not in rust tho๐ณ
good?
!e
def my_function(str_arg: str):
print(str_arg)
my_function(2)
@sick birch :white_check_mark: Your eval job has completed with return code 0.
2
oh I see. Ty all
Python has no problem with that
didnt I?
no?
wdym
of course I did?
She did
rust is statically typed so it would scream at you
has_permissions will raise a MissingAccess exception, handle that, and remove the if not client.has... and use the tree error I linked to
How can i get message author in discord.Interaction ? like ctx.message.author ?
yes....
!d discord.Interaction.user
The user or member that sent the interaction.
discord.Interaction.user
Thank you
im slow ๐
yes....
what's it say?
ask him
or maybe i'm too fast๐ฉ
what are u passing in that function?
nah im actually slow, im like 50wpm
i coudnt find anything
what more proof do you want ๐ญ
imagine
beats me
very sad
can u please just help me with that?
i dont need a error handler
dude
i just need it for the specific command
imma use that
hmmm InteractionResponded: This interaction has already been responded to before ?
oh that
do it like this (I'll add it to the gist thanks)
@command_name.error
async def command_name_error(inter: discord.Interaction, error: discord.app_commands.AppCommandError):
await inter.response.send_message("uwu you")
Code?
ยฏ_(ใ)_/ยฏ
Returns the follow up webhook for follow up interactions.
@bot.tree.command(name="mute", description="Mute a member !")
async def _mute(interaction: discord.Interaction, member: discord.member.Member, time: str):
if interaction.user.guild_permissions.administrator:
try:
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[0]) * time_convert[time[-1]]
role = get(member.guild.roles, name='Muted')
await member.add_roles(role)
embed=discord.Embed(title="User Muted!",description="**{0}** was muted by **{1}**!".format(member,interaction.user),color=discord.Color.blue())
await interaction.response.send_message(embed=embed)
await asyncio.sleep(tempmute)
await member.remove_roles(role)
except:
embed=discord.Embed(title="Error!", description="There is an error!", color=discord.Color.red())
await interaction.response.send_message(embed=embed)
empty except ๐ฉ
followup ?
oh damn , first time i heard u gotta make a error handler for each command before it was way different, cool
more like bare except
ya im dumb
What's probably happening is that an error is occurring in either of these 2 lines:
await asyncio.sleep(tempmute)await member.remove_roles(role)
You'll notice both of these lines come afterawait interaction.response.send_message(embed=embed), and you also haveawait interaction.response.send_message(embed=embed)inside your except. This means that you can respond to the interaction inside thetryblock, get an error, go into the except block, and respond to the interaction again
This is one of the reasons you should scope your try/catch blocks to be as specific as possible
its a whole different story when that happens irl ๐
ah ic
like this?
yes.
but better use the isinstance
to typically catch the required error
I'll update the gist too for that
thats what i need
so how do i fix it then
@slate swan question one, can I make multiple of these error functions? 2) how should I fix it then
try:
...
except discord.Forbidden:
...
you cant do that for a decorator check....
then see what exception it raises and catch that @warped mirage
Raises
HTTPException โ Sending the message failed.
Forbidden โ You do not have the proper permissions to send the message.
ValueError โ The files or embeds list is not of the appropriate size.
TypeError โ You specified both file and files, or you specified both embed and embeds, or the reference object is not a Message, MessageReference or PartialMessage.
Damm , in dpy 1.7.3 u didnโt have to make all of this lmao oh well stuff changed
why can't u catch Forbidden?
Ok let me make myself clear.
no that was not to u ๐
Lmfao
I donโt wanna have any error handlers for all the functions ,
I wanna make error handlers for certain commands so currently I just want it for the ban command, you get what I mean?
@discord.ui.button( emoji = f"{e_gems}", style=discord.ButtonStyle.primary, row=2, disabled=False)
async def b_profession(self, interaction: discord.Interaction, button: discord.ui.Button):
img = requests.get(i_background_organization, stream = True)
img = Image.open(io.BytesIO(img.content))
img = img.convert('RGBA')
imgF = requests.get(i_frameS_organization, stream = True)
imgF = Image.open(io.BytesIO(imgF.content))
imgF = imgF.convert('RGBA')
imgFM = requests.get(i_frameSM_organization, stream = True)
imgFM = Image.open(io.BytesIO(imgFM.content))
imgFM = imgFM.convert('L')
ava = interaction.user.display_avatar
ava = requests.get(ava, stream = True)
ava = Image.open(io.BytesIO(ava.content))
ava = ava.convert('RGBA')
ava = ava.resize((240, 240), Image.ANTIALIAS)
avaM = Image.new('L', ava.size, 0 )
avaMD = ImageDraw.Draw(avaM)
avaMD.ellipse((0, 0, 240, 240), fill=255)
img.paste(ava, (430, 195), avaM)
img.paste(imgF, (0, 0), imgFM)
img.save('./ImageS/profile_org.png')
file = discord.File("./ImageS/profile_org.png")
await interaction.response.edit_message(attachments = [file], view=self)
Dear tell me what is the problem?
I donโt wanna have any error handlers for all the functions ,
I wanna make error handlers for certain commands so currently I just want it for the ban command, you get what I mean?
I'm speed
the image conversion is blocking the whole bot and its probably taking too long so its being timedout,
when im using message.content it returns a blank value?
message = await new_channel.send(f"<@{str(author.id)}>", embed=embed)
await message.add_reaction("๐")
def check(reaction, user):
return user != self.bot.user and str(reaction.emoji) == "๐" and reaction.message == message
payload, user = await self.bot.wait_for('reaction_add', check=check)
message = await new_channel.history().flatten()
with open(f"./discord/data/{str(user.id)}{str(guild.id)}", 'w') as file:
for i in reversed(range(len(message))):
message = f"{str(message[i].author)}: {str(message[i].content)}\n"
file.write(message)
Hey, it looks like I need hosting.
message.content is None? do u have message_content intent enabled
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
oh
no, just forgot about that. i disabled it because it was returning an error
like this?
no u need to do something like isinstance(error, <The error ur trying to look for>)
isinstance(error, MissingPermissions)
@paper sluice like this?
no, u literally type MissingPermissions
u also need to import it
how?
Is the drop-down menu working on 1.7.3?
No, only on 2.0^
from discord.app_commands import MissingPermissions
Ok
ok last question, can i make multiple of these error functions?
why do u want multiple error functions?
like for each function it will catch the permission from the command itself right?
u can just do
@...error
async def ...(error, ...):
if isinstance(error, error-1): ....
elif isnstance(error, error-2): ...
and so on
how add to embed image from path
@bot.command(name="unban-user")
async def unban_user(ctx, member:discord.Member):
await ctx.guild.unban(member)
discord.ext.commands.errors.MemberNotFound: Member "Alfonsalt#2064" not found.
i dont need that atm
please answer my question lol
Why doesn't this work?
probably no
wt
im not sure, its not practical to make multiple functions
u can do everything in one
?
ok help me make a error function for kick and ban command. i need to use embed
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
this is the last thing i need please
@bot.command(name="unban-user")
async def unban_user(ctx, member:discord.Member):
await ctx.guild.unban(member)
discord.ext.commands.errors.MemberNotFound: Member "Alfonsalt#2064" not found.
How do I solve this? Ofc the member won't be found since its not in the server anymore
Oh I am totally going to use this, awesome.
im not sure whats going wrong with this, it was working before i enabled intents
message = await new_channel.history().flatten()
with open(f"./discord/data/{str(user.id)}{str(guild.id)}", 'w') as file:
for i in reversed(range(len(message))):
message = f"{str(message[i].author)}: {str(message[i].content)}\n"
file.write(message)
Traceback (most recent call last):
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 85, in on_raw_reaction_add
message = f"{str(message[i].user)}: {str(message[i].content)}\n"
AttributeError: 'Message' object has no attribute 'user'
discord.User is what you want
Why is that?
it has always been message.author
hi guys, can i have async checks for commands?
what type of check?
how would you unban a member?
!d disnake.ext.commands.check
@disnake.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command "disnake.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command.checks "disnake.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Context "disnake.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CommandError "disnake.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error").
i get the same issue with message[i].author
Traceback (most recent call last):
File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 85, in on_raw_reaction_add
message = f"{str(message[i].author)}: {str(message[i].content)}\n"
AttributeError: 'str' object has no attribute 'author'
i think u can, have u tried it?
i mean, how can i not have async checks, after all im accessing ctx, so i may need to send something to it
i havent tried it yet
code?
message = await new_channel.history().flatten()
with open(f"./discord/data/{str(user.id)}{str(guild.id)}", 'w') as file:
for i in reversed(range(len(message))):
message = f"{str(message[i].author)}: {str(message[i].content)}\n"
file.write(message)
em = discord.Embed(title="An error has occured", description="You cannot use this command", color=0xFF0000, ephemeral=True)
TypeError: Embed.__init__() got an unexpected keyword argument 'ephemeral'
``` how do i fix this
def my_check():
async def predicate(ctx):
return True or False
return commands.check(predicate)
like that?
ephemeral is a kwarg for interaction not Embed
have you tried printing out what message returns?
Whut:
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.
I literally pressed the copy button on that account to get the username
damn discord.py is weird, with discord.js u can have embeds with ephemeral
but thanks
you can have embeds in ephemeral messages lol
class Foo:
def check(...): ...
@commands.check(check)
...
should work considering how classes are loaded
not for discord.py
await Interaction.response.send_message(embed=embed, ephemeral=True)
omg bruh
im very sure on that
use the special cog_check method inside the cog, you dont have to call/decorate it anywhere,
class ExampleCog(Cog):
async def cog_check(ctx):
...```
yeah but
nvm, you're overriding your message variable
i want multiple ones
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found
multiple?
Is it tripping?
huh that might be my problem
!d asyncio.AbstractEventLoop.create_task
No documentation found for the requested symbol.
huh
!d asyncio.create_task
asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
๐คท
ofc its not documented
i want multiple checks for different commands inside the cog
i thought it could work for reply but its already doing it lol
def main_check(...):
return all(other - checks)
something like this
among the discord.py examples is this one, which calls client.loop.create_task(my_background_task()), which is where I got the idea.
no lol
await self.on_error(interaction, error) # type: ignore
File "C:\Users\Dom\Desktop\ZEEFUT UTILITIES\main.py", line 56, in ban_error
return await inter.send(embed=em, ephemeral=True)
AttributeError: 'Interaction' object has no attribute 'send'
``` any ideas
thats just making a task with the attribute Client.loop which is literal to an asyncio.AbstractEventLoop @restive urchin
they edited the message, check it again
@ban.error
async def ban_error(inter: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, MissingPermissions):
em = discord.Embed(title="An error has occured", description="You cannot use this command", color=0xFF0000)
return await inter.send(embed=em, ephemeral=True)``` code
ok cool thanks
@warped mirage
its not in docs btw
as in check_any?
no. wait
for all cmds in the cog?
Does anyone have a clue about this??
i have 2 commands, lets say in this simple example,
marry and divorce,
i want to have checks like
async def check_target_not_bot(ctx):
if any(u.bot in ctx.message.mentions):
await ctx.send("you cant marry a bot")
return False
return True
async def check_is_not_already_married(self, ctx):
# i will get the user here, dw about that part
target = ctx.message.mentions[0]
user = await self.client.db.users.get(ctx.author.id)
target = await self.client.db.users.get(target.id)
return not user.marriage_id or not target.marriage_id
i missed "s" off mssage. such a dumb mistake ahaha
What does a wildcard in parameters mean?
separates keyword only arguments
!e
def foo(*, a):
return a
print(foo(a=1))
print('-'*100)
print(foo(1))
it makes all the arguments after kwargs only
@paper sluice do u have a clue about this?
@paper sluice :x: Your eval job has completed with return code 1.
001 | 1
002 | ----------------------------------------------------------------------------------------------------
003 | Traceback (most recent call last):
004 | File "<string>", line 6, in <module>
005 | TypeError: foo() takes 0 positional arguments but 1 was given
not really
It doesn't make sense. They are literally the same??
what
oh nothing
ya i dont really make discord bots, im not the guy to ask :p
Oh I think I know where I am messing up, I need to make my function a coroutine.
I'll look that up.
apparently we can access ctx.bot inside checks yay this solved everything
did you check that the parameter isn't the discord ID?
from discord.ext import commands
bot = commands.Bot(command_prefix='esk')
@bot.command()
async def say(ctx,arg):
await ctx.send(arg)```
This code doesn't execute the command
well are you running the command and the bot?
yeah
user (abc.Snowflake) is what it wants
I thought the username worked for that
What is a snowflake object?
Btw @slate swan just curious, would interaction.reply be possible? Without embeds or ephemeral
ofc
Ok
do u get any errors?
No I don't, just the command doesn't execute
is the bot running?
yeah
if you're using discord.py, here's the documentation page:
https://discordpy.readthedocs.io/en/stable/api.html?highlight=snowflake#discord.abc.Snowflake
is the bot in the guild?
discord.abc.Snowflake is just a representation of the type of a unique int which discords api calls it such
have u ever seen irl Snowflakes?
@bot.command(name="ban-user")
async def ban_user(ctx, member:discord.Member):
await ctx.guild.ban(member)
@bot.command(name="unban-user")
async def unban_user(ctx, member:discord.User):
await ctx.guild.unban(member)
The ban works when I pass it a username but the unban doesn't and says it can't find the user. Both expect a User (abc.snowflake)
@paper sluice What is the guild?
server
yeah
User (abc.snowflake) is the class signature
discords api calls a server a guild its mainly just an alias lol
class User(abc.snowflake): ....
Wdym by that?
@paper sluice So why is my command not executing?
bot.run() ?
and do you have an on_message event by chance
ignore that, where do u get "Both expect a User (abc.snowflake)"??
The docs where they describe the parameters
huh? can u send the link
lol ok do this async def ...(ctx, user: discord.abc.Snowflake) then while calling the command, u enter the id of the person
like !unban 739847923473284792837
the member is gone, how do u ping them 
yeah but the username is still unique?. Like if I do unban Alfons#7577
ya u can, but its very ugly
if they dont share any other mutual guild, they are not in bot's cache anymore
u loop over the guild ban list, and check the name
Less ugly than the id? Also how does one even get the ID?
imo id is better
imo manual unbanning is better
If your server has like 50 members sure, but as soon as you want case logs and larger scale it becomes a pain
lucas ban/unban over everything
there is a search option, its better than trying to remember the whole name
Could I provide the alfons#7577 to the bot, have it loop through the ban list and find the user and then grab the ID and then give that to the ban func?
!d discord.Guild.bans sure.
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
Changed in version 2.0: Due to a breaking change in Discordโs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
you rarely need to remember the name, you'll just copy someone's id and paste into a command
at a certain point using search becomes uh... infeasible
ok ur on the id side too, nice, i thought u meant invoke with username and discriminator
Ok, I gotta be doing something wrong here, or working in the totally wrong direction.
I am trying to make a periodic save of some data to my database.
In my main file I am doing this:
asyncio.create_task(autosave.autosave(bot, logger, activitylog, db_conn))```
Which calls autosave, which looks like this:
```py
async def autosave(bot, logger, activitylog, db_conn):
await bot.wait_until_ready()
while not bot.is_closed:
await save(logger, activitylog, db_conn)
await asyncio.sleep(60) # saves every 60 seconds```
save() has a bunch of SQL, and I have no idea if that is working or not, but for debugging purposes I put in some logger code to check if things were working and it does not trigger at all, so something is wrong. The function, edited for brevity:
```py
async def save(logger, activitylog, db_conn, debug=True):
... # SQL stuff
try:
... # more SQL stuff
if debug: # show our work in the console
check = await db_conn.execute(f"SELECT * FROM activitylog")
rows = await check.fetchall()
logger.debug("Data in activitylog database:")
for row in rows:
logger.debug(f"ID: {row[0]} - Name: {row[1]} - Lastseen: {row[2]} "
f"- Firstseen: {row[3]} - Messagecount: {row[4]}")
except aiosqlite.Error as e:
logger.error(e)```
I am rather lost why my debugging code isn't working, and suspect the whole coroutine loop isn't firing.
Full code here: https://github.com/Volatar/ThuearleBot/tree/activitylog
oop
@slate swan ```python
import os
my_secret = os.environ['TOKEN']
import discord
import requests
import json
from discord.ext import commands
bot = commands.Bot(command_prefix='esk')
@bot.command()
async def say(ctx,arg):
await ctx.send(arg)
client = discord.Client()
def getquote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
@client.event
async def on_ready():
print("We have sucessfully logged in as {0.user}".format(client))
client.run(my_secret)```
what does this error mean?
await ....send(...)
you should use aiohttp
ty
@slate swan That's not the main problem, The command doesn't execute. (say command)
def getquote():
return (json_data:=json.loads((requests.get("https://zenquotes.io/api/random")).text)[0]['q'] + " -" + json_data[0]['a'])
```๐ณ
@deep osprey this was for u
dont ignore poor ryuga๐
and you should change to aiohttp so your bot responds to heartbeats when making a request
import os
my_secret = os.environ['TOKEN']
import discord
import requests
import json
from discord.ext import commands
bot = commands.Bot(command_prefix="esk")
@bot.command()
async def say(ctx,arg):
await ctx.send(arg)
def getquote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
@bot.event
async def on_ready():
print("We have sucessfully logged in as {0.user}".format(bot))
@bot.event
async def on_message(message):
if message.author == bot.user:
return
elif message.content.startswith('eskuseme'):
await message.channel.send('Did somebody call me?' and 'Yes?')
bot.run(my_secret)``` @paper sluice Still.
what version of dpy do you have
1.7.3
1.7.3
you only have 1 on message right?
Yes
nova no ones talking to you
Ok
1 what? okimii
go joke around somewhere else
the on_message events
pull await bot.process_command() at the end of ur on_message event
You are not my dad ok
no use listen
!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/latest/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.10)").
Example...
save a line and have repeated events๐ณ
ah yes
How can I do that?
just replace your event decos with listen
@bot.listen()
async def on_message (): ...
you need to call the deco
Dont teach me ok
for on_ready too?
atleast give examples that work
if you want sure
works now but I still don't get it, why @bot.listen made that work?
https://stackoverflow.com/questions/72777886/reddit-api-issue
May someone help me here connecting to the reddit api with my discord bot?
thank you โค๏ธ, you too @paper sluice
pleasure
@bot.command()
async def say(ctx, arg1, arg2):
await ctx.send(arg1, arg2)```
Traceback (most recent call last):
File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 12, in say
await ctx.send(arg1, arg2)
TypeError: send() takes from 1 to 2 positional arguments but 3 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: send() takes from 1 to 2 positional arguments but 3 were given```
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
how to make that work?
string formatting?
Evening all, I've been a lurker here for a while, but always managed to solve it myself, until now :/
Is there a way to have a multiselect, where more than 1 value is already selected?
context: I'm making a games list manager for my local gaming club. I've got a modal to add a brand new game, and a select that lists all the games (read from db) so someone else can select games from the master list that they already own. I'm open to suggestions for alternate ways of managing this using the tools we have available.
@fading marlin That works now but I have another question, how to make args depends on number of words that the user says? For example: "User: $say hi" "output: hi" "User: $say two words" "output: two words"
consume rest
@bot.command()
async def say(ctx, *, args):
...
.
Hey im struggling on making the invite link to add my bot to my server can anyone happily help?
you are so welcome dude! thanks for the shout out! โค๏ธ
by the way i wouldn't have minded if you had actually pinged ๐
Hey @slate swan how is your wrapper going?
I'm looking a example of Discord.py 2.0's discord.SelectOption in use as I want to see all of the attributes of discord.SelectOption in use. I think I understand how the label attribute will work but I'm not sure about the description.
When u open the select there can be a small description under a label
if the label u are showing the the user is not the value that need to use in ur code
so instead of converting the label to the value u need you can just use discord.SelectOption.value
Can anyone look at my discord bot project and tell me what improvements can be made from a structuring standpoint? Like if the bot should be split into multiple files, packaging conventions, etc?
so like a role or role ID, you click the option from the list as something like 'get the role' and the options value is a role or the role ID which the bot can check to assign the role of that ID?
yeah for example if you have a role object, you can just set the label to the roles name but set the value to the role object so you don't have to get the role again
that's really quite useful
I can take a look over the span of like a week and give you some feedback. I'm no python expert but I like to think I have a good understanding of bot structure (if giving feedbacks allowed - I'm not really sure)
That would be sweet, I can DM you. It's not a large project by any means
Sure.
open source bots are great examples
hey, how can I add reactions when someone uses a command
like I have a mute command, when someone uses it, I want it to add reaction to the person who used the command like a โ
Thank you! Seeing this made my day ๐
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
Oi
I think I can use smth like ctx.message.add_reaction right ?
correct
Alguรฉm aรญ sabe fazer o bot pegar uma coisas de uma planilha do exel em manda em um canal?
English please
@snow bloomyou can use a library called openpyxl to interact with excel workbooks and import the data to an object you can reference in your bot's code. link for docs here: (https://openpyxl.readthedocs.io/en/stable/)
thats a whole task in itself, can you be a bit more specific with the issue you are struggling with? @bright jetty
i know how to setup but uh do i need to install python?
where
im just starting to code with python
you can't even begin to install dpy without python installed. its a language specific library
ok
- Download the latest version of Python for the Operating system you use, be it windows or linux.
- Download the latest version of discord.py (I believe you need to use the git url for this)
- Find an editor you like, personally I use Atom (https://atom.io) and I find it amazing.
- Read through the documentation to get a feel for how everything is structured and start simple.
no thanks ima just install python and dpy
well you kind of need something to write your code with
i have vsc
vsc is a good tool too
it can be a bit tricky to get it setup due to differences between the built-in runtime environment and an actual deployment environment so take that in to account
make sure you check "Add to PATH"
thats super important
I strongly recommend not making dpy your first Python project, specially if you're just starting to learn Python. A lot of complicated concepts are used and you'll probably find them confusing as you go
ok
i want dpy too
cause im making discord bots
what next
install it
Lee was just letting you know again that d.py tends to have a steep learning curve and it can be challenging for a lot of people, especially those new to coding or OOP. After having experienced this learning curve for myself, I can agree with him.
there is an installation guide on the documentation
idk about python i just started
i got muted because i mentionned 7 ppl lmao
AAA AM SO HAPPY I DID ๐ญ โฅ๏ธ
u welcome and totally deserve ! showing love doesn't require any coding skill, and any skill at all, and it's the least thing i can do โฅ๏ธ
depends on the version of discord you want to install
Why doesn't this work?
@bot.command(name="unban-user")
async def unban(ctx, 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.channel.send(f"Unbanned: {user.mention}")
traceback?
No traceback, just doesn't do what its supposed to
also, that looks fairly familiar, did you copy that off of YouTube?
Nothing happens
some website
That's probably why
Copying random code from some random website is probably not worth the trouble
Also that looks like it's from Lucas's video
yeah lmao
Im debuggin it and it seems like it works fine until the if statement
anyway, type hint your member parameter with discord.User, and then use ctx.guild.unban and pass in your member param, see where that takes you
It gets the correct correct name and discriminator
Just use the discord.User typehint
No need to mess around with the splitting stuff
The whole function should only really be like 1 line
^ you'll also be able to pass in IDs
wait where?
And then I remove the splitting line?
then what about the if statement? What should be on the right
Not faled portuguรชs?
remove everything really, you just need the typehint and the unban method
Would you mind showing me?
show you what exactly?
Then I end up like this:
@bot.command(name="unban-user")
async def unban(ctx, member: discord.User):
await ctx.guild.unban(member)
await ctx.channel.send(f"Unbanned: {member.mention}")
ctx.send does the same as ctx.channel.send btw
and yeah, that'll work, you might need to do some error handling, but in theory it works
And I get this error:
discord.ext.commands.errors.UserNotFound: User "Alfonsalt#2064" not found.
But it is the correct user.
try using their ID?
also, your bot won't be able to "see" that account if there aren't any other servers it shares with the user
Then it works, but the point of it all was to be able to use the username
wdym?
Note the error says "Alfonsalt"
And the screenshot you showed shows Afonsalt
nvm, I don't think it applies here
yeah ik doesn't matter. Still doesn't work when i copy the username
My plan kinda was to get the list of all the banned accounts in that server, check where the username supplied by the one calling the command matches up in the list of banned accounts, and then get the id of that banned account
So you could always use the username and let the bot get the id for u
Is that possible?
sure, however type hinting discord.User will make it convert to a User object, which is far handier than just having the string. Could you send the full traceback?
of when it doesn't find the username?
Ignoring exception in command unban-user:
Traceback (most recent call last):
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 254, in convert
raise UserNotFound(argument)
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.
Looking at the source code, it'll do searches by name#discrim if given, there is really should be no reason that this errors
The possibility is, perhaps an old cache, or something like that but it's pretty much unlikely here
The only thing that really would be cause, would be the username, etc
But I literally press the username, it says copied and then I paste it into discord so it cant be wrong
hmm
In your command print bot.users
Just want to make sure the user is cached
But yea, again looking back at the source code of the wrapper, it'll do searches by name#discrim when given so
That just leads to the user not being cached
Actually, have you constructed your bot instance with member intents?
nope
That's the issue then
Without member intents, in discord.py you'll have no users
As user cache depends on the members intent
So the issue you are facing would be fixed by passing member intents to the bot
I don't think that'd be the case
Wouldn't it cause this to error aswell:
@bot.command(name="ban-user")
async def ban_user(ctx, member:discord.Member):
await ctx.guild.ban(member)
Does anyone know how to make the bot get things from an exel spreadsheet and send it to a channel?
no, because discord.Member represents a user inside a guild
discord.User and discord.Member aren't the same thing
It'll make a API request, so no
If it cannot be found in the cache that is
Wait so whats the solution then
Pass member intents to the bot
how do I do that
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I have no clue what intents to enable?
intents.members = True
Please read the second paragraph
Which intents is it that I need to enable to in portal? And they are not the same as the permissions right?
I mean, there is literally 3 intents on the website to pick, and one of them says SERVER MEMBERS INTENT, so. Maybe that one
And permissions are different from intents
Intents are just flags that you pass when connecting to the gateway, this'll tell the gateway which events to send
Permissions are well, permissions
import discord
from discord.ext import commands
from discord import Intents
import sqlite3
intents = Intents.default()
intents.members = True
activity = discord.Game("!help")
bot = commands.Bot("!", activity=activity, intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.author != bot.user:
pass
@bot.command(name="purge-channel")
async def purge_channel(ctx):
await ctx.channel.purge()
@bot.command(name="ban-user")
async def ban_user(ctx, member:discord.Member):
await ctx.guild.ban(member)
@bot.command(name="unban-user")
async def unban(ctx, member: discord.User):
await ctx.guild.unban(member)
await ctx.channel.send(f"Unbanned: {member.mention}")
with open("token.txt", "r") as f:
token = f.read()
bot.run(token)
This is the code, ive enabled literally every intent I can and saved changes.
And then this:
raceback (most recent call last):
File "c:\Users\Alfons\Programming\Python\Discord\Firstbot\main.py", line 42, in <module>
bot.run(token)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\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 0x000001AA29731FC0>
Traceback (most recent call last):
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed)
hi awesome people o/
I'm having some troubles hosting my bot on replit and i can't bind a credit card nor pay online for long reasons i'm lazy to explain, so i need a free plan no cards.
I know i can't have a free hosting that is good as Robin mentionned one day, but if u guys just knoww hy replit sometimes... idk crashes? or restarts? I'm pinging it every 5 minutes since i implemented a web server on it tho, so that works fine but sometimes (like, once a day sometimes twice?) replit restarts and i find out my bot is offline ><
"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."
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
The error is saying, you did not actually enable the member intents
Double check the portal, you probably did not save there
1 sec ill redo the entire thing
So then, back to this error:
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.
And this was how I instantiated it
intents = Intents.default()
intents.members = True
activity = discord.Game("!help")
bot = commands.Bot("!", activity=activity, intents=intents)
Atleast its not the intent error anymore, but intents wasn't the root of the problem
Can you print bot.users in the command
the command to unban?
Yes
New code:
@bot.command(name="unban-user")
async def unban(ctx, member: discord.User):
print(1)
print(bot.users)
print(2)
await ctx.guild.unban(member)
await ctx.channel.send(f"Unbanned: {member.mention}")
Traceback:
Logged in as Onyx#8510
Ignoring exception in command unban-user:
Traceback (most recent call last):
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 254, in convert
raise UserNotFound(argument)
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.
Really weird, it doesn't even print 1 or 2
It didn't print 1 or 2 but it still errored?
Are you sure you saved the file before running it??
Logged in as Onyx#8510
[<ClientUser id=991141705132814356 name='Onyx' discriminator='8510' bot=True verified=True mfa_enabled=False>, <User id=289649835823595520 name='Alfons' discriminator='7577' bot=False>]
yeah
Ok, uban via ID then have the alt rejoin the server
Then print bot.users again
By restarting
I just wanna check that the bot can actually see the alt
k 1 sec
bruh wtf
Now I can't even get the alt to rejoin
It says that its banned when its not? I've manually checked
Okay, I figured out why this issue is happening. When you enabled intents the alt account was still banned right? So when the bot started up it did not cache the user (caching requires member intents). So naturally, this current issue will fix itself when the alt account has rejoined the guild, afterwards you can ban the alt, then unban via the user#discrim format. So the original cause was intents
uh ive made a new server now let em try it
It works!!
You are amazing for taking the time for this
Thank you so much
Keep in mind, it'll only work with name#discrim if the user being unbanned was VISIBLE during the bot's current life-time
So, if a user was banned before the bot got turned on. You'll be forced to use the user's ID
So the bot has to at some point see the user to be able to unban them later?
So then I can just except the error and tell them they have to use the ID
Yes, the cache in discord.py is not persistent
And you cannot make an API request via name#discrim, so it'll be best to use the ID
You can intercept the error using an on_command_error
this is mainly discord.py right
As the error will be raised from the converter itself, which is called before the command callback is even fired
You cannot just smack a try-except block in the callback
If you're talking about the channel, you can get help on most wrappers
oh okay
So I have to use the on_command_error thing to be able to catch it? I looked in the docs and they didn't give an example of how it's implemented
on_command_error is just an event, it'll be dispatched by the wrapper when an error is raised in a command
It's just like your on_message, etc
You'll receive ctx and error as the parameters to the event
Just isinstance the error, check if it's user not found. Then send a message with ctx
hello discord.py devs.. i am very confused about this:
import discord
import random
from discord import guild
#Making a variable the bot will reply to
bot = discord.Client()
#Telling the program that these are variables
ownerRole = '<@&978492717220913222>'
botRole = '<@&978488109756977192>'
diceBattle_random = random.randint(1, 6)
members = guild.Member
#Making the bot tell me when its ready and online
@bot.event
async def on_ready():
print("GO, GO, GO!!")
#Telling the bot to listen for these messages and what to do if it finds them
@bot.event
async def on_message(text):
#Variables that need the (text) information
ID = text.author
verifyID = discord.utils.find(lambda role: guild.Role.name == 'Human')
#Hello command
if (text.content == "$hello"):
await text.channel.send(f' {text.author.mention} Hi!!')
#Verify command
if (text.content == "$verify"):
await ID.add_roles(verifyID)
await text.channel.send(f' {text.author.mention} was verified!')
#diceBattle commands
if text.content == "$diceBattle bot":
await text.channel.send(f' {text.author.mention} got a {diceBattle_random}! And I got a {diceBattle_random}!')
if text.content == "$diceBattle random":
print("PLACEHOLD")```
i have excluded the bot.run command altogether (for obvious reasons) and i keep running into this error:
```Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Bron\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Bron\OneDrive\Reuben\VS Code stuff\discord bots\python bots\myBot.py", line 21, in on_message
verifyID = discord.utils.find(lambda role: guild.Role.name == 'Human')
TypeError: find() missing 1 required positional argument: 'seq'```
help will be very much appreciated!
try discord.utils.find(lambda role: role.name == 'Human', text.guild.roles)
ok, thanks!!
!d discord.utils.find
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is โMightyโ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.10)") due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s.
it works! tysm!!
np :P
!d discord.utils.get --- does not do the same
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
ic
i stopped making it cuz im lazy, now im learning rust๐
ive fallen in love with rust ngl๐
make a wrapper in rust, best of both worlds
no
serenity is a thing
maybe ill make an api with rust and wrap it in py cuz why not
Ah- okay ๐
and too many lib abstractions i got tired
I am finally starting to make a big bot project with it, but I am finding it equally difficult lmao
make a team to maintain it
๐ง
is there any reason a bot would start printing random blank lines to a console???
i switched from my test bot to my main with the exact same code and it's randomly throwing random blank lines in command prompt
Gotta get people who are up for it ๐ซ
good luck with that๐
The worst part is doubting your own decisions. Like... have I made something stupid? Is this stupid? Should I know that this is stupid? Would anyone want to use this? 
an empty print() statement somewhere?
no, i've gone through every print statement
i only have two infinite loops in the code and tried commenting out both
try it out with a few beta testers๐
ive seen people use bots that only send cat memes ofc they would
wtf
watch discord make a new update with their api and then making all of your bots features useless
๐
that is indeed a think to look out for
ok i commented out every print and it fixed it 
maybe one of the print had a none object hence the empty line?
It's so bad it would be embarrassing for them to try

๐
give them a month
the message got pinged from one of my favorite mods, what an honor
would explain seeing as my test bot isn't in 1k server 
I haven't really seen other libraries where you can define a presence with the constructor, or equivalent tbh
I've mostly seen a call in any one of those wrappers on_ready equivalent
Starting to make me wonder if on_ready presence changing is just a discord.py ick
why not? if all forks have the same bot construction or am i wrong?
the status is passed to **options in the bot constructor
I'm not speaking of forks
I'm talking about other languages
Yay! It got pinnged
Yes, you are
I'll take a deeper read at both yours and Ashley's and suggest any fixes
I'd like them to be perfect ๐
go ahead i woud love for the gist to be better โค๏ธ
"PRESENCE gateway event payload" technically speaking, the official documentation refers PRESENCE here as a gateway command
The ratelimits should also be dicussed
ash suggested it like so, my original one was PRESENCE gateway event
As changing presence is a gateway command, it falls under 120/2s ratelimiting
But the main thing is. sure discord.py handles the ratelimit here to stop you from instantly disconnecting
But it still uses resources on your end and on discord's end
a ratelimit tab would be nice i will think about it orrrr maybe you can fork it and ill add the changes๐ณ
Hence why in the official discord api server they actively tell you not to change presence in a loop
E.g your changing presence example at the bottom
Hey @slate swan and @slate swan, would you guys mind making a PR on python-discord/site for both of your respective gists? We can make improvements there via code reviews
sure!
is there a way to stop dpy commands when they are executing?
return
wait no hold on sys.exit(0)
no i want to use one command to stop another
oh idk
Yes'nt
sed
Let me write an example real quick
mhm ok thx
from __future__ import annotations
import asyncio
async def main() -> None:
event = asyncio.Event() # Event used to wait.
event.clear() # Turn OFF
async def command(number: int) -> int:
await event.wait()
return await asyncio.sleep(1, number)
loop = asyncio.get_running_loop()
loop.create_task(command(123)) # Pretend this is you executing the command
# Since event.clear() was called earlier, the command will wait for it to be set first.
event.set() # Now event is set, the code after await event.wait() will now run
asyncio.run(main())
``` of course, here I'm doing the opposite of what you want, but it can be easily done the other way around too
Sad :(
Does someone know how i could create a command which will randomly disconnect a random member from a voice channel? I just started bot coding. Any help is appreciated
!d discord.VoiceChannel.members
property members```
Returns all members that are currently inside this voice channel.
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have the [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
Thank you
And to pass in the specific Channel would I need the ID, or could I just specify the channel name
As a parameter^
sure robin
you can pass those 2 objects or pass None to kick the user as shown above
Thanks for the help!
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
@slate swan You might want to search for Paramaters in your bot repository and replace with Parameters. Using Search and replace will make it easier.
Also instead of forcing installing uvloop, since you are using poetry you can just do ```toml
uvloop = {version = "^0.16.0", markers = "sys_platform == 'linux'"}
my bad, i misspelt it everywhere, thanks for pointing it out <3
No problemo
oh I'll look into that, thanks!
guys is there a way to make replit sqlite database sync with an external database somewhere? because what I do is I edit code on vs code then push on github then pull on replit XD
so i lose the database data each time unless I remember to download the db from replit, then push changes, then upload it again
You'll need try-except for importing
or a way for it not to get touched by github when i push/pull? :o
https://github.com/sarthhh/anya/blob/main/__main__.py#L8-L11
im importing that only if the os is linux or mac, will that still be required?
__main__.py lines 8 to 11
if os.name != "nt":
import uvloop
uvloop.install()```
Oh if you got that, then it'll work
create a .gitignore file, and enter the database file name for example database.db/sqlite3 or you can even ignore all the database files using *db/*sqlite3
wait, no syntax needed for that file? just write db.sqlite and then save?
where should i create it? in .git?
in your current working directory
aaaa this is so scary I'm so scared i make a mistake and lose something
it doesn't delete any data or files, that file is just used to tell git that the files mentioned are not to be pushed
In that case make a copy of your folder before and save it somewhere
does anyone know how to make global chat in discord bot python?
create a channel?
a channel in multiple servers that are all connected
wdym by connected?
just guilds that use webhooks to send messages like a network
assume there are two servers -> server A and server B
both the servers have channels named as -> global-chat
when a message is sent in global-chat from server A, it should send the same message to global-chat in server B
over explanation๐ตโ๐ซ
no
I'm just sleepy
lmao
it's 6 am ๐ okimii motivate me to sleep
i got you, remember you have to make a pr to the pythondiscord site so forget it and go to sleep
I already did
oh you did but the same issue like my pr
yup
linting check failed for me too ๐
if i read it right
https://github.com/python-discord/site/pull/701 this one has the same issue as well
sad
smh
So i have to use a webhook to do it?
in simple terms u have to broadcast a message from one server channel to another
not necessarily use a webhook to do it simplest method would just be an on_message event and add a check for channel
that would be a such a mess
ratelimits โจ
even if you use webhooks, creating webhooks for each user would be pain
they do iirc
battle of iircs, lets see who remembers correctly
I remember making post requests to webhooks using ifttt
Prob was 30/60s then
A channel has a 30 msg/60 sec limit for webhooks yeah
how many people can i role every minute?
the ratelimit is dynamic
really messy
unless you apply certain conditions to the channel
69 messages per 420 mins ๐
approximately 6.1 messages per minute
which is not that bad tbh

an bot.event error handler will always show one error right? like i mean it doesnt show the wrong error right?
how would i make a bot give a specific role after you message it a command
wait thats not literally the rate cap is it
i think it was more like 60 transactions per second or something
but varies depending what you are doing
you are doing like this?
@bot.event
async def foo(...): ...
@foo.error
async def foo_error(...): ...```
from nextcord.ext import commands
from nextcord import Interaction, SlashOption
import os
import nextcord
intents = nextcord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.slash_command(
name="Hell",
description="Will send a \"Welcome to Hell \"response",
guild_ids=[...],
)
async def Hell(inter: nextcord.Interaction) -> None:
await inter.response.send_message("Welcome to Hell")
TOKEN = os.environ['TOKEN']
client.run(TOKEN)
Been at it since yesterday but I just couldn't find the problem. The bot's slash command which is /Hell just won't show up. The code runs fine and so does the bot but the /Hell command won't send the text. I even followed the links that some helpful guys sent me yesterday and tried figuring it out by doing lots of googling
I'm new to Python so go easy on me when explaining 
do u have application commands selected in the dev portal?
the command names should be lowercase too

Oh... Let me try that
Nope, didn't work
sad
Also, yes. I tried giving it Administrator
the command doesnt show up or what?
not admin, im talking about that check box
is dpy even broken or what, my message commands aint even working
and u also need to make it lowercase inside the decorator like name='hell instead of 'Hell'
It doesn't show up, yeah. But the bot goes online fine.
Was following this tutorial https://tutorial.vcokltfre.dev/tutorial/beginner/03-hello/
But then since slash cmds didn't function, I had to enable intents and what not
A tutorial to help you make better Discord bots.
Let me try
have all of em
show code
nvm it worked, was testing about custom prefixes
Nah, still not working
sigh
slash commands are not just commands with / prefix
I mean
can u show ur code again?
It just don't show up
you have to wait for the slash command menu to appear
It's this
Yeah, the problem is, it's not really appearing
nextcord and other forks autosync don't they
the updated one i mean
Wym?
show the current code for ur command
I didn't change anything. It's the one I wrote above
Couldn't figure it out myself so I figured I'd ask
then how do u expect to see any results ๐

@client.slash_command(
name="hell",
description="Will send a \"Welcome to Hell \"response",
guild_ids=[...],
)
async def hell(inter: nextcord.Interaction) -> None:
await inter.response.send_message("Welcome to Hell")
do this
and if it still doesn't work, enable the application.command thing i said before, kick ur bot and reinvite
Oh wait. If I change stuff from the developer portal I'd have to reinvite?
Yes
you dont have to kick the bot ๐
How would I make it so if a channel name starts with a specific string it does what I say
guild = get_guild(...)
channel = [channel for channel in guild.text_channels if channel.name.startswith("uwu")]
if not channel: "no channel found"
...
?
ty
I'm sure you can use utils.find or smth but not quite sure
How would i get the name of the channel i sent the message in tho
channel = ctx.channel?
wait no
channel[0]
right, im just dumb
And it wont delete any others that start with it?
ryuga, I'm having a stroke in #databases help
ofc?
Yeah, it doesn't work still
At this point, I might need to switch from nextcord to disnake
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'channel' referenced before assignment
sad
wahts wrong
where did u define channel outside the function?
Yeah, i might need to switch to Disnake
!e
a = [1, 2, 3]
def foo():
a = a[0]
return a
foo()
print(a)
@paper sluice :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | File "<string>", line 3, in foo
004 | UnboundLocalError: local variable 'a' referenced before assignment
change the name to something other than channel, ur trying to reassign the same name in different scopes
๐ ๐
This code, it scares me.
Do i remove chnnel from the loop and the thing at the bottom u highlighted
no u just change channel to something else
which one
send ur code here as text
gedit

