#discord-bots
1 messages · Page 106 of 1
pretty sure when u clean the chat ur deleting the interaction so there is no interaction to respond to
Correct, you can send a message in the channel though - without responding to an interaction
do what snipy said and defer the interaction before you start purging messages
after deferring the interaction you can use the .followup webhook that lasts for 15 minutes, a way longer window than 3 seconds
cna you show the code of the "cleaning chat"
I know exactly on what line the command freezes but I can't figure out why.
@app_commands.command()
@app_commands.guild_only()
# pylint: disable=too-many-arguments
async def reminder(self, inter: discord.Interaction, note: str,
seconds: int):
"""
(Instable) You can set a reminder that will send you a message in a given time.
"""
await inter.response.defer(ephemeral=True, thinking=True)
timestamp = numpy.datetime64(datetime.now())
added_time = numpy.timedelta64(seconds, "s")
if added_time <= 0:
await inter.response.send_message("There is no time given for the reminder.", ephemeral=True) # Here is an alternative freeze
return
trigger_time = timestamp + added_time
rem = sqldata.Reminder(note, inter.user.id, inter.guild_id,
inter.channel_id, True, timestamp, trigger_time)
await inter.response.send_message(f"Reminder scheduled for ", ephemeral=True) # I is freezing here.
Funny thing is that the exact same function is working on menu interactions...
@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", description="Limpa uma quantidade de mensagens") async def clear(inter:discord.Interaction,amount:int=100): if inter.user.guild_permissions.ban_members: await inter.channel.purge(limit=amount) msg = discord.Embed( description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^', colour = 3844214 ) await inter.channel.send(embed=msg, ephemeral=False) else: falta = 'Você não tem permissão para usar o comando!' embed = discord.Embed(title=f"{falta}") await inter.channel.send(embed=embed, ephemeral=True)
chances are that the command errored rather than simply "froze", but if you didnt see an error message in the terminal then you might have an error handler that ate the error
yea just .defer like snipy said then use edit_original_response() or followup
@rancid raptor interactions can only be responded to once, so after your defer() you need to use the .followup webhook instead
exemple?
dpy things smh
await interaction.response.defer()
# do some work in between...
await interaction.followup.send('my actual message')```
Actually it's a much better solution.
its not a dpy specific thing
Thank you very much.
True everything is a fork anyways 
now i will continue writing on my reminder system
That's a tough one.
not being able to edit the ORIGINAL response on a defer is a dpy thing lol. disnake you can
wait
Logs:
Traceback (most recent call last): File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\tree.py", line 1242, in _call await command._invoke_with_namespace(interaction, namespace) File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 887, in _invoke_with_namespace return await self._do_call(interaction, transformed_values) File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 876, in _do_call raise CommandInvokeError(self, e) from e discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: TypeError: InteractionResponse.defer() got an unexpected keyword argument 'embed'
code:
@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", description="Limpa uma quantidade de mensagens") async def clear(inter:discord.Interaction,amount:int=100): if inter.user.guild_permissions.ban_members: await inter.channel.purge(limit=amount) msg = discord.Embed( description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^', colour = 3844214 ) await inter.response.defer(embed=msg, ephemeral=False) else: falta = 'Você não tem permissão para usar o comando!' embed = discord.Embed(title=f"{falta}") await inter.response.defer(embed=embed, ephemeral=True)
await inter.response.defer()
......
await inter.edit_original_message() #changed to response recently i believe
you can ALSO use followup if u prefer
the .defer(ephemeral=True)
the .followup.send(embed=embed)
!d discord.InteractionResponse.defer You can't just do something and expect it to work.
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
I didn't understand 😦
i know you can do that for message interactions just fine, but what is it meant to do for a slash command?
async def clear(inter:discord.Interaction,amount:int=100):
if inter.user.guild_permissions.ban_members:
await inter.channel.purge(limit=amount)
msg = discord.Embed(
description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
colour = 3844214
)
await inter.response.defer(embed=msg, ephemeral=False)
else:
falta = 'Você não tem permissão para usar o comando!'
embed = discord.Embed(title=f"{falta}")
await inter.response.defer(embed=embed, ephemeral=True)```
I don't understand what's wrong, it erases but doesn't send the embed
you send the actual content in the followup
the defer goes at the beginning of the interaction
before any code
this works for slash as well
await inter.response.defer()
......
await inter.edit_original_message() #changed to response recently i believe
no i mean, what does it actually do? defer doesnt send a message, so what is the original response meant to be?
the code:
async def clear(inter:discord.Interaction,amount:int=100):
if inter.user.guild_permissions.ban_members:
await inter.channel.purge(limit=amount)
msg = discord.Embed(
description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
colour = 3844214
)
await inter.response.defer(embed=msg, ephemeral=False)
else:
falta = 'Você não tem permissão para usar o comando!'
embed = discord.Embed(title=f"{falta}")
await inter.edit_original_message(embed=embed, ephemeral=True)```
its correct?
.defer(with_message=True)
@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", description="Limpa uma quantidade de mensagens")
async def clear(inter:discord.Interaction,amount:int=100):
await inter.response.defer(ephemeral=True)
if inter.user.guild_permissions.ban_members:
await inter.channel.purge(limit=amount)
msg = discord.Embed(
description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
colour = 3844214
)
else:
falta = 'Você não tem permissão para usar o comando!'
embed = discord.Embed(title=f"{falta}")
await inter.followup.send(embed=embed)
await inter.response.defer(with_message=True)
Defer just makes it so the bot says it's thinking right?
if you pass true to thinking yes
I think... that's all I've done with it lol
huh, sure enough it looks the same as sending a message after deferring
thats weird
@app_commands.command(name='test')
async def app_test(self, interaction: discord.Interaction):
await interaction.response.defer(thinking=True)
await asyncio.sleep(1)
await interaction.edit_original_response(content='test')```
wait is that dpy?
yes
they should fix their docs lmao
and let ppl know thats a viable solution alongside .follow.send
what did it say that misled you
the fact that is only says .followup
It is your responsibility to eventually send a followup message via Interaction.followup to make this thinking state go away.
async def clear(inter:discord.Interaction,amount=100):
if inter.user.guild_permissions.ban_members:
await inter.channel.purge(limit=amount)
msg = discord.Embed(
description = f'Ola **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
colour = 3844214
)
await inter.response.send_message(embed=msg, ephemeral=True)
else:
falta = 'você não tem permissão para usar o comando! '
embed = discord.Embed(title=f"{falta}")
await inter.response.send_message(embed=embed, ephemeral=True)```
Traceback (most recent call last): File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\comandos.py", line 88, in <module> async def clear(inter:discord.Interaction,amount=100): File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\tree.py", line 889, in decorator command = Command( File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 685, in __init__ self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__) File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 390, in _extract_parameters_from_callback raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}') TypeError: parameter 'amount' is missing a type annotation in callback 'clear
i find it odd that edit_original_response would work at all, but i guess it makes sense since defer() for a slash command actually creates a message with the loading flag i believe
yes
hm if anything followup.send() after defer(thinking=True) would be the odd one
also found out dpy automatically sets thinking=True for app commands but doesnt mention it in documentation
i was just about to say. i believe follow up is for when no thinking is used then .edit_original_response for when thinking param is passed
dpy things lmfao.
parameter 'amount' is missing a type annotation in callback 'clear'``` its saying that `amount=100` needs a typehint, like `amount: int`
I just saw this but it doesn't send the embed after cleaning
discord/interactions.py lines 647 to 648
elif parent.type is InteractionType.application_command:
defer_type = InteractionResponseType.deferred_channel_message.value```
`disnake/interactions/base.py` lines 744 to 745
```py
if parent.type is InteractionType.application_command:
defer_type = InteractionResponseType.deferred_channel_message```
`nextcord/interactions.py` lines 690 to 691
```py
if parent.type is InteractionType.application_command or with_message:
defer_type = InteractionResponseType.deferred_channel_message.value```
disnake documents it
with_message (bool) –
Whether the response will be a separate message with thinking state (bot is thinking…). This only applies to interactions of type InteractionType.component (default False) and InteractionType.modal_submit (default True).
True corresponds to a deferred_channel_message response type, while False corresponds to deferred_message_update.
oh yeah at least they say something about it
pycord
This parameter does not apply to interactions of type
InteractionType.application_command.
nextcord
This is always True for interactions of typeInteractionType.application_command.
i guess its more of a nitpick since discord.py mentions it, but doesnt really imply that it forces thinking=True rather than erroring or something
Application commands (AKA Slash commands) cannot use
InteractionResponseType.deferred_message_update.
How can I add indexes to my snipe command so I can also see previous deleted messages?
store a list of messages per channel instead of one message?
hello everyone, I had an issue with discord form. Everything is working correctly until I click on send form. Method callback of class MyModal, which is the child of discord.ui.Modal, just doesn't work. And I dont know why. Please, help me
Modals have to use an on_submit method rather than callback
!d discord.ui.Modal.on_submit
await on_submit(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Called when the modal is submitted.
default_time = datetime.datetime.utcnow().replace(hour=12,minute=0,second=0,microsecond=0)
future_time = default_time.replace(hour=abs(set_hour),minute=45,second=0,microsecond=0)
formatted_time = disnake.utils.format_dt(future_time,style='F')
await ctx.send(f"Guid refresh loop will start at: {formatted_time}.")
await disnake.utils.sleep_until(future_time,result=self.guild_refresh_reminder.start())
im trying to start this loop at a certain time, but whenever i use this command it sends the message its supposed to send when the loop starts right after
you should check out timedelta when you're working with future_time =>
you can do stuff like
datetime.datetime.now() + datetime.timedelta(hours=8)
Because, chances are, your future_time is something in the past, since you're replacing instead of adding up
good point, ill try timedelta
ok so i changed it to this
future_time = datetime.datetime.utcnow() + datetime.timedelta(hours=hour,minutes=minute)
formatted_time = disnake.utils.format_dt(future_time,style='F')
await ctx.send(f"Guid refresh loop will start at: {formatted_time}.")
await disnake.utils.sleep_until(future_time,result=self.guild_refresh_reminder.start())
``` but it still sends the message
dont set the result kwarg in sleep_until you are calling start so it starts the loop. Instead start it on the next line
ok, yea it worked, thanks
can someone help me idk what code to send man im confused
add_cog is a coro in versions 2.0 and up
so you need to await it
await bot.add_cog(...)
Guys how can i make a !d command like @unkempt canyon
It's very hard to understand code in its GitHub repo
!src d
Look up documentation for Python symbols.
That code goes off from my head
That's very hard
Ye but i just wana ask that do that uses any api to get documentation?
pretty sure it's all local
Ok
based on @unkempt canyon's code it specifically reads documentation sites generated by Sphinx, which is fairly easier to handle since they come with a secret "objects.inv" file that stores all the objects described in their documentation and the corresponding URIs
https://github.com/python-discord/bot/blob/main/bot/exts/info/doc/_inventory_parser.py#L108-L114
https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html
bot/exts/info/doc/_inventory_parser.py lines 108 to 114
async def fetch_inventory(url: str) -> Optional[InventoryDict]:
"""
Get an inventory dict from `url`, retrying `FAILED_REQUEST_ATTEMPTS` times on errors.
`url` should point at a valid sphinx objects.inv inventory file, which will be parsed into the
inventory dict in the format of {"domain:role": [("symbol_name", "relative_url_to_symbol"), ...], ...}
"""```
e.g. if you GET https://discordpy.readthedocs.io/en/stable/objects.inv you'll receive a zlib-compressed file containing data in a format as described above
ctx.author.display_avatar.url
why'd they change it?
ctx.author.avatar_url returned an Asset which is misleading, you would expect it to return a str
oh
makes sense
and yet it can convert to a url string, which dpy does for most methods
there are now also different avatars like default_avatar, avatar, and guild_avatar, hence why display_avatar exists to give you the one that you would expect to see
oh yeah they explain the changes to assets in more detail here
https://discordpy.readthedocs.io/en/stable/migrating.html#asset-redesign-and-changes
the old api was quite everywhere
Not any pinned post for heroku alternatives?
see the pinned message in the #965291480992321536 thread
I can't use a paid service as I don't own a credit card
Does anyone know a good replit bot template that I can use?
it doesnt have to be a VPS if you have spare hardware, but ultimately someone has to pay for hosting
We don't usually recommend replit for hosting discord bots, so not really, no
OK
I've create a hikari bot but the bot ain't responding
import hikari
bot = hikari.GatewayBot(token="...")
bot.listen()
async def ping(event: hikari.GuildMessageCreateEvent) -> None:
if event.content.startswith("hk.ping"):
await event.message.respond("Pong!")
bot.run()
it's online
sir this is a python discord server
what were they saying
get_user or fetch_user
I amuse fetch_user is better in most case's
because get_user does not return sometimes due to odd cahceing etc
guys
how do i make my discord bot only make commands work for a person with a specific role
Use a Decorator
@commands.has_role
use the documents if your not sure on how to use it
whats a decent way to delete any message that gets sent in a channel after a certain delay?
i had a piece is js code and i wanted to implement in python thats what i was asking
you need to enable MESSAGE_CONTENT intents
im using py-cord, i want to have options but the user must chose only one option like how we chose in radio button where there are multiple options and the user can only choose only one
how long is the delay?
in slash commands
lets say 30
what lib are u using?
then you can use a on_message listener, asyncio.sleep for 30 seconds and use Message.delete()
ah-
well imma have to rework everything probably then xd..
why do you have to rework everything
Creating bots for bitcoin. 
i may or may not have all my commands in an on_message()
!d
bruhhhhhhhhhhh
hm
how do i use @commands.has_role
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
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 invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...

like this
@command.has_role("Admin", 2298398498958)```
Nothing?
Like no one can help with a simple question
so you can whitelist a role only to use that command by name of ID.
or*
ok so
what's even ur question

like this
so i put the command.has_roles right above the code
above @client.command()
ooo above it
Change "Admin" to the role name you want or use the role ID.
yes ur correct get_user might return None if the object was not cached, you should use fetch when get returns None
a proper way of doing it would be ```py
user = bot.get_user(id) or await bot.fetch_user(id)
don't have to use both
ik dont worry
thanks, im not sure why the user inst getting cached.
these can be reasons
- you don't have members intents
- the user doesn't share a guild with bot
- your system is unable to store more into cache

Intents are good, cache is fine.
But the user does currently share a server with the client.

does that happen for a specific user or all users?
all users

Seems like a caching problem
mind showing your intents code and the bot class?
you already know i got that custom client class

class client(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc = ipc.Server(self, secret_key="LevelMe")
async def on_ipc_error(self, endpoint, error):
print(f"IPC Error: {endpoint} raised {error}")
Client = client(command_prefix=commands.when_mentioned_or(config['Prefix']), intents=discord.Intents.all(), case_insensitive=True)
hm weird issue
Ikr.
anyways just use the get_user or await fetch,_user thing
mk
thanks,

Doesn't nextcord have Interaction.send shortcut that automatically handles response and followups
!d nextcord.Interaction.send
await send(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, delete_after=None, allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to, [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is sent via [`Interaction.followup`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.followup "nextcord.Interaction.followup") using [`Webhook.send`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Webhook.send "nextcord.Webhook.send") instead.
Yeah just use this why'd you need that response and followups grass
Hello people, im looking to build a discord bot that will delete messages after a certain time. Can you help?
👋 can you explain a bit more?
Say someone shares there twitch link, im looking to build a bot that will delete the link qnd message after say 5hours.
ok, so you can use an on_message event, check if message.content contains a twitch link, and if it does, delete it after 5 hours (using asyncio.sleep or such)
So would that be the full code?
pretty much
on_message -> if message.content has a twitch link (using regex or whatever) -> asyncio.sleep for 5 hours -> message.delete
So would that work on replit?
how to get a specific guild in a button interaction
I got this @vocal snow
...thats just pseudocode
you're supposed to write the actual python code yourself... lol
can someone help me?
via ID?
Ohh haha, what is the code? As i dont know it lmao
yup something like client.get_guild but in a button class
bro 💀
well you know python right?
you need to know python in order to program a discord bot in python
✅
any idea on this tho?
anyone?
you can use interaction.client.get_guild
!d discord.Interaction.client
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
thanks man!
Can you push me in the right direction then dude? As im new to all this. Ive only just learnt how to get the bot to respond to a message, so im completely new
if you're new to python, I would suggest learning the basics first before using discord.py; https://www.py4e.com/lessons is a free course, there are many more available (see !resources)
If you know python basics, this should be easy to implement based on the pseudocode. You already have an on_message event, the next step is to check if the twitch link is in the message content
Okays, so that link will explain pretty mu h everything i need to know? @vocal snow
yes
Thankyou!! And thankyou for giving me the auto delete code bro!
if you have any questions about those videos, you can ask in help channels here: #❓|how-to-get-help
@vocal snow can you help me with one more thing?
sure
class menu(ui.View):
def __init__(self):
super().__init__()
self.value = None
@ui.button(label='Bugs', style=discord.ButtonStyle.green)
async def Bugs(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = Embed(title="Creating a ticket for Bug report")
await interaction.response.send_message(embed=embed,ephemeral=True)
guild = interaction.client.get_channel(guildid)
print("test")
#category = discord.utils.get(guild.categories, name="TICKETS")
print("test")
channeel = await guild.create_text_channel(f"ticket-{interaction.user.name}")
print("test")``` i am trying to create a ticket system, it should work when someone presses the button but idk why it's not creating the text channel, guild id is correct
any idea?
are you getting an error?
my bot scripts never throw any error 😦 it leaves me with finding the bug myself
it's in a cog
do you have an on_command_error event
apparently i don't
any error handlers for the command?
nope
Search on_command_error and on_error in your whole project
I highly doubt that you overrided on_error method but check it anyway
i'll add that later but any idea why it's not working tho?
If you are using slash commands the event is different afaik
So use regex search on_.*error
@vale wing can you help me with my interaction?
First fix the error handlers
Because the errors don't appear ONLY because of that and nothing else can be eating them
Do this
there used to be a default error handler in discord.py 1.7.3
how can i get that to work
i just wanted a little help with my interaction 🥲
Error handlers have been kept the same in 2.0 iirc
Correct except I think there were events added for app commands
the old ones don't work for me
Other than using this log thingy now
the old ones work fine for me 
i just wanted to know why it's not creating channel
Ah yeah wait
What do you use to start the bot
py main.py
In code
in cmd
How do you start the bot in code
In your code, you start/connect the bot
Most likely at the end of your file
client.run()
Yeah then you have an error handler eating your errors
And without error(s) we can't help as we're not seers that can guess your error(s)
i don't have any error handler in my code
something is eating your errors, we should pinpoint that first
have you set up logging?
Though when using bot.run() there's a default one, which doesn't need to be setup
I've never setup logging and works fine with default logging when I tested the 2.0 changes
Was the most basic script to just get the bot online
how do i make that a command would work only in one channel?
if ctx.channel.id is not the id:
return
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
this works too
oh thanksss
how do i make buttons work anytime
like if i stop the bot and run it again it doesnt work
You probably need to setup a unique ID to the button and listen to events
listen to events?
Reading/taking a look at the documentation helps
also they do have an id
class system(discord.ui.View):
def __init__(self, user):
super().__init__(timeout=None)
self.value = None
self.timeout = None
self.user= user
@discord.ui.button( label="Other Games", style=discord.ButtonStyle.blurple, custom_id="other_games:blurple")
async def system(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(view=TicketView(interaction.user), ephemeral=True)
class TicketView(discord.ui.View):
def __init__(self, user):
self.user= user
super().__init__(timeout=None)
@discord.ui.select(placeholder="Choose a role!", options=[
discord.SelectOption(
emoji="", label="Counter Strike", description="Choose me if you want to be updated when someone wants to play CS!"
),
discord.SelectOption(
emoji="", label="Valorant", description="Choose me if you want to be updated when someone wants to play Valorant!"
),
discord.SelectOption(
emoji="", label="Haxball", description="Choose me if you want to be updated when someone wants to play Haxball!"
)
])
async def help_callback(self, interaction: discord.Interaction, select):
select.placeholder = f"Reason: {select.values[0]}"
reason=select.values[0]
if reason == 'Counter Strike':
role=get(interaction.guild.roles, id=1030085444534292560)
if role in interaction.user.roles:
await interaction.user.remove_roles(role)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Chooses Counter Strike Succssesfully!", ephemeral=True)
if reason == 'Valorant':
role=get(interaction.guild.roles, id=1008808500744441876)
if role in interaction.user.roles:
await interaction.user.remove_roles(role)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Chooses Valorant Succssesfully!", ephemeral=True)
if reason == 'Haxball':
role=get(interaction.guild.roles, id=1030085098600669195)
if role in interaction.user.roles:
await interaction.user.remove_roles(role)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Chooses Haxball Succssesfully!", ephemeral=True)
@bot.command()
async def sys(ctx):
view = system(ctx.author)
embed=discord.Embed(title="**רוצים לדעת ראשונים כשמישהו רוצה לשחק?**", description="מוזמנים לבחור אחד מהרולים המופיעים כאשר אתם לוחצים על הכפתור! \n תהנו!")
embed.set_footer(text=f"Requested by {ctx.author}")
await ctx.send(embed=embed, view=view)```
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
@slate swan
i did that
and it doesnt work in any channel now
show code
@bot.command(aliases=["Amongus"])
@discord.ext.commands.guild_only()
@commands.cooldown(1,940,commands.BucketType.guild)
async def amongus(ctx):
if ctx.channel.id is not 1005776398507581490:
await ctx.reply("Please use that command in [#1005776398507581490](/guild/267624335836053506/channel/1005776398507581490/)!")
return
check = ctx.author.voice
if check is None:
voice = f'לא מחובר לחדר'
else:
voice = ctx.author.voice.channel.mention
emibed = discord.Embed(title="מחפש שחקן למשחק אמונג אס", description=f'{ctx.author.mention} Among us מחפש מישהו לשחק! ',color=0x6c97c5)
emibed.add_field(name="המשתמש נמצא בוויס:", value=voice, inline = False)
await ctx.send(f" {ctx.author.mention} מזמין אתכם לשחק איתו! <@&890044017776136202>", embed=emibed)```
you sure that the ID is correct?
yes
use != instead of is not then
tho is not should have worked
okay
'
remove the not
why I'm unable to have embed's color 0x000000?
I get an error console In data.embeds.0.fields.5.value: This field is required
0x000000 is equal to 0
!e
print(0x000000)
@glad cradle :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
there's one None color on discord
idk it's hex code
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").
There is an alias for this called Color...
if you're speaking about embed it's the default color, you don't have to set it
you're right
color is not the issue you didn't add a value to the 6th field
I got the issue
thanks! it's also the empty color which I forgot to manage
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.```
how to fix this?
enable intents from dev page
this?
Yes, try it and see 
nothing happens
Because you need to enable all the ones you've enabled in your code
If you enabled message_content, enable it in portal
If you enabled members, enable it in portal
its not because of the embed color, the embed fields need a value
it works thanks
how to import youtube.dl?
!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)
In addition to that, Discord doesn't verify such bots anymore and start to unverify those who are doing it 
Is there any way to send embed rules in a rules channel without using a specific command.
You can use a webhook
Any documentation for it?
Discord's built in Webhooks function as an easy way to get automated messages and data updates sent to a text channel in your server.
Think of them as one of those fancy pneumatic tube things you u...
Then just send a message via that webhook - https://discord.com/developers/docs/resources/webhook#execute-webhook
Thanks!
Just like sending a message in a channel but use the webhook url instead
So I finally found the autodelete restapi.go file, so do i just copy all that into repl.it go file?
To my knowledge this is a Python server
Oh shit yea 😅🤣 sorry haha
Thankyou 😀

Hopefully they can help, the auto delete bot keeps going down and its annoying 🤣😅
Someone most likely can 
like how reply to a message or send when it boots or you are new so you need an example
What's wrong with it?```py
await msg.create_thread(f"{customid} | Let us know you voted!")
TypeError: create_thread() takes 1 positional argument but 2 were given
does it makes a difference if you do this?
await msg.create_thread(name=f"{customid} | Let us know you voted!")
No one really replied so I'll post again.
I enjoy helping people in the help channels, but I know my area of expertise (numpy, matplotlib, etc.)
I'm sure it is possible to set up a bot to monitor the help channels and notify me when keywords show up, but i'm not sure the admins here welcome outside bots
Anyone have any thoughts on this?
They most likely won't invite random third party bots.
@pastel basin, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
Specifically when it has only one use case, and mostly used by you (only)
You can always post suggestions in #community-meta though
i cant get my image to go inside the embed it currently just posts separately
with this code
embeds = GetEmbed.act_triangle(endpoint.player, [data,season], response, self.bot)
await interaction.followup.send(file = embeds[1], embed=embeds[0],view=view)
result = TriangleGen.generator_triangle(data[0],player)
if result:
embed=discord.Embed(title=f"{player}", description="")
x = discord.File(f".//{player}.png", filename=f"{player}.png")
embed.set_image(url = f"attachment://{player}.png")
#embed.set_footer(text=f"""Last updated: {jsonplayer["data"]["last_update"]}""")
#print("made")
return [embed,x]
else:
print("ERROR")
how can i fix it?
It was just a test webhook... mate.
from discord import Webhook
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('', session=session)
await webhook.send('Hello World', username='Foo')
It's not working..
I copied the code from documenation.
documentation*
Also, my url is correct.
I think I need to set the username to my webhook username?
thanks, will do
Well, with just that code it will never call the function foo()
Oh..
So the code will never get executed 
Though I'd guess that if it gets considered, it'll probably be implemented within @unkempt canyon but not a third party bot
How to call functions, I don't know async programming much..
Your way of doing it is correct
I know, other way is easier tho.
Literally like any other function
await foo()
No async.
Got error.
asyncio.run(foo())
ok
how to get all messages in a channel?
TypeError: object async_generator can't be used in 'await' expression```
its an async generator, so you have to iterate over it like
async for var in async_generator: ...
async for msg in interaction.channel.history(...)
thanks!
There is even an example in the documentation, if people would take the time to read it...
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
Even more than one example, actually two of them
Lazy people not looking at the documentation 
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'```
how to fix this?
Enter this argument
intents=discord.Intents.all()
In my webhook embed.
client = commands.Bot(command_prefix = '!')intents=discord.Intents.all()
like this?
@pseudo jungle Learn the basics of python first.
No
Make discord bots after you are familiar with data structures...
Also don't use .all() but .default()
Or maybe after leaning OOP
How come?
Actaully I will enter it manually
commands.Bot(command_prefix="...", intents=discord.Intents.default())
Because you don't need privileged intents.
oh yes
As well as you won't be given access to them if when verifying your bot if you don't have a valid use case. So yes, it matters
but... doesnt reall ymatter you know
I have a question
Do embeds update automatically with webhooks?
Like if the embed has my guild name
Will the name change if i change the guild name
No, the message/text won't be edited automatically
No point on asking that.
Learn basics first mate
Bruv
Criticism like that is pointless and leads to nothing.
He's new to coding... and making bots
It's rather offensive and not friendly at all.
So I'd recommend keeping such comments for yourself
This is still relevant btw
Thanks 
i cant get my image to go inside the embed it currently just posts separately
with this code
embeds = GetEmbed.act_triangle(endpoint.player, [data,season], response, self.bot)
await interaction.followup.send(file = embeds[1], embed=embeds[0],view=view)
result = TriangleGen.generator_triangle(data[0],player)
if result:
embed=discord.Embed(title=f"{player}", description="")
x = discord.File(f".//{player}.png", filename=f"{player}.png")
embed.set_image(url = f"attachment://{player}.png")
#embed.set_footer(text=f"""Last updated: {jsonplayer["data"]["last_update"]}""")
#print("made")
return [embed,x]
else:
print("ERROR")
how can i fix it?
That's general python you can ask in the respective channel
oh. alright
didn't really want to occupy a help channel for a question little as that one
You can ask in #python-discussion
huh
It's not offensive!!! maybe you are thinking like that.
I asked him everything polite.
You are just being p..... .
Please finish that word
Pedantic?
I wonder if pydantic has anything to do with that 🤔🤔
That sounds to fit better when asked in the appropriate channel. Not a single thing related to Discord bots, even if used in a Discord bot that has nothing to do with any python Discord library.
You're right, I'll delete and ask there :)
Yo @sick birch have u ever used the HTTP Based events?
Ah I need help with something
Shit
!e
print("\n Hello")
@pastel basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | Hello
Discord trims spaces and new line chars before and after the message
maybe ****\n....
K I will try this
abusing bugs is the way of life
I find using a list with “\n”.join to be a lot cleaner than having a large string with \n scattered about
or just use multiline strings
Never used \n and list
!e
print('\n'.join(['a', 'b', 'c']))
@paper sluice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | b
003 | c
Hey @slate swan!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
or you can do
a = """a
b
c"""
print(a)
Using sep=“\n” is better for print
yea
Ryuga have u worked with HTTP Interactions?
has anyone even worked with those
!e print("line 1", "line 2", "line 3", sep="\n")
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | line 1
002 | line 2
003 | line 3
haven't worked with anything related to discord bots in over 3-4 months
Same
shame
🔫
I actually am making something that passes http interaction to discord.py
Nice, but my friend do be using nextcord and I am too lazy to rewrite the bot 😭
I don’t see the point of http interactions tho
You can host bot on websites like replit with HTTP Interactions since u don't get ratelimited if any other bot spams (ig lol)
just change import discord to nextcord and you are good 😎
It is written in nextcord and I don't wanna figure out the bot tree shit
just try it and break code
Might instead just ditch him
friendship++
mission passed successfully
there is nothing too complicated with migrating to nextcord tho, you can read their docs on how to migrate to nextcord https://docs.nextcord.dev/en/stable/migrating_to_nextcord.html
and if you want the v2 migration docs for more info on what has changed and stuff, you can check it out here https://docs.nextcord.dev/en/stable/migrating_2.html
The bot is already written in nextcord
intimidating/encouraging a user to break the rules, not saying he was, i'm saying it in general, isnt something friendly or professional, personally i think referring a user to the rules of the guild and the Code of conduct and TOS is more friendlier way over intimidating a user which then other users will make fun of which you dont really mention to stop with the criticism and unnecessary comments, i'm saying this because it has happened to me and it gives a vision to the use that all mods can be condescending and at the end of the day the action done is inappropriate, why didnt i mentioned it to modmail? well, because i just didnt really felt like it
With all due respect i'm saying you should work on your approach to users that can be breaking the rules
holy shit
Thanks for the feedback. They never did finish spelling that word I had a question about
Maybe marking the sentence with a question mark would be better and less intimidating, also finishing a discussion that isnt on topic and is inappropriate is better over causing more attention, as you can see there was a joke about it which I'm not going to say the users name but it was just totally unnecessary and can fall into the meaning of criticism
I just wanted to know what they were trying to say, to determine if it was something that broke our server rules. Given the context of discouraging other users by saying " go learn python first", I felt like it was worth asking in a direct way.
Any ways, as you have already pointed out lets finish the discussion which is off topic, and already over.
Well, wouldnt stopping the discussion there been a better option? As from past history of this channel i can see moderators always like being on topic
Yes, i would like that.
Clarifying what they meant to type directly leads to stopping the discussion
I wouldnt say it stopped the discussion at all but did the opposite of stopping it
I don't want to mingle but I think this was better suited for Modmail. If you reacted instantly fine, but this was 3 hours ago, the chat is interrupted again.
The only discussion here was off topic. i wanted to tell my view to the user directly, but i will do next time if there's a question
is there a way to grab the guild info inside ui.view?
or even a way to grab guild info outside any sort of interaction? trying to set button names according to a table thats different per guild
Callbacks have an interaction.
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
but dont they need to push the button for that? i need the name displayed on the button they press
yes
It's a class so you can pass variables trough the init.
hmm i think i see what youre saying. i can grab the guild info from the event triggering my message
...("Message", view=View(interaction))
class View(discord.ui.View):
def __init__(self, original_inter: Interaction) -> None:
...
oooo ok ill play around with that
Just note that you can't do any respond things but you can still get info from it.
thats fine i just need guild info to use to recall a role name from mysql
Role name from a database?
Why not the ID?
putting role name as button name to press
What if the role changes name?
command to update db
Wouldn't it be easier to insert the id then fetch the role get the name then display it? Auto updates unless the role is deleted ofc. But on_guild_role_delete could check for that.
Yep
If you make it as easy as possible people will likely use it more.
this is true
if I use commands.AutoShardedBot, does it automatically manage sharding for me? Or do I have to do some stuff with it?
When using this client, you will be able to use it as-if it was a regular Client with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.
It is recommended to use this client only if you have surpassed at least 1000 guilds.
tldr no
Okay, thanks.
Details if you are a nerd -> https://discord.com/developers/docs/topics/gateway#sharding
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
im getting invalid syntax at the original_inter:
tb?
tb...?
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Well, you don't give the parameter type when calling a function
What are you doing there though 
Using pycord I have this source code, but it doesn't create the minesweeper command am I doing anything wrong? https://paste.pythondiscord.com/com/rujunapazu
i have role IDs stored in a database to recall later, im trying to pull the id from a database, in order to do that i need the guild id (name of the table) then using the ID, pull the name of the role, and use the name of the role in a button
Well what's wrong is that you call __init__ and specify the parameter type when calling it, that's not allowed
You also use -> None: - that's also only for defining functions
Someone trying non existing commands
was just going off this suggestion
Well there's a small difference between that
oh the super instead of the def
Or is there a better way to do this?
No you can't, the bot will just not do anything so don't need to care
help to make a message counter, that is, it will show how many messages the user has written for the entire time while there is a bot on the server. I know that this requires a database. But I want to do just a message counter for now.
Have you even tried anything?
If not
- Try something
- Come back with issues or uncertainties you're facing
I just don't know where to start a little bit
Well as you said, you need a database at some point
Other than that you can listen to the on_message event to know who sends a message, then you can increase their personal counter
well, the database will only be needed so that it is saved after the bot is disconnected or restarted
When using a command like, for example, /messages the bot will give that personal counter back
Correct
and first of all I want to at least understand how to do it
Ok fixed that issue but now it cant be clicked, im stumped first time getting into this
I mean, without database it's just about increasing a counter variable
traceback?
Sure one sec
Maybe use a dictionary to store like that
{
user_id_one: counter,
user_id_two: counter,
...
}
No errors
And when there is a message sent, you can use the on_message event
Increase, or create if it's not existing yet, the counter for the user ID
Oh, I just checked your code, and your RowButton class doesn't appear to have any callback @fluid shadow
Oh, welp that just slipped by me. Ill go make that thanks!
Yeah was about to say that
now how do i get btn1 to carry over to the button name?
You cannot access a variable that is inside a function, within a different function
Python scopes basics
whelp. sorry i suck lol
!e
def a():
x = "hello"
def b():
print(x)
a()
b()
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | File "<string>", line 5, in b
004 | NameError: name 'x' is not defined
x is only available in the scope of the function a
if i saw it right, you can put self.btn1 as a variable instead of just btn1
then the function inside can access it too
discord.ui.button is a decorator that returns a Button class. Decorators "convert" the given function to whatever they return. So basically, Role1 will be a Button class instead of a function. Knowing this, you can set the label of the class in your __init__:
class A:
def __init__(self, ...):
self.button_callback.label = "label"
@discord.ui.button(...)
async def button_callback(self, ...):
...
Well, the issue is not in the function
It's in the decorator
So no, that won't help
What Lee said though, is correct
oh so i can define the label in the init instead of in the button itself. that makes it a whole lot easier. thanks guys
No problem!
Exactly, that way you can access the variable you need
how i can change percent ram to int number?
{int(psutil.virtual_memory().percent)}%`/`8 RAM```
That's basic maths
So how to do it?
Use the maths you've learned in first class
8 * 0.84?
| 100% | 84% |
|------|------|
| 8 GB | X GB |
Yah
Probably want to use MBs though
So i can do:
{int(psutil.virtual_memory().percent * 8)}GB`/`8 RAM
I can't try it rn
i'm on mobile

Okay
That's the rule of three....
So i alway have percents
Among the first thing you learn
In mathematics, specifically in elementary arithmetic and elementary algebra, given an equation between two fractions or rational expressions, one can cross-multiply to simplify the equation or determine the value of a variable.
The method is also occasionally known as the "cross your heart" method because lines resembling a heart outline can be...
8*84/100
just use psutil.virtual_memory().used?
been messing with get() for a while and cant get it to return anything but None. should i be using an api call with fetch_roles instead?
id kwarg should be an int, not a string
tried roleid instead of f'{}' and still nothing
is roleid an integer?
you can see in the back window i printed roleid and what get returns
numbers, and None
Hello, i need some help creating a transcript function, so when a user does !close it will save the chat history and send it to a channel
integers and strings can't be differentiated by simply printing their value, you gotta check their type
is there a way to change their type?
use sorry, I read something else. Cast the value to typeint to change it to an integer
how can I make it so that when you click on the bot there is a tab to try out slash commands that you can click on and they will work. How can this be done ?
you can't. That is something Discord does
GOT IT WORKING thanks again!
dude, I saw this from the bot in the discord and I ask about what I saw myself
what?
It's done automatically by Discord
You can't control it or write/change them manually
When your bot has slash commands that are used, it will show the most used (if I remember correctly) slash commands there
I know. I just saw that one bot in his profile has the ability to use commands by clicking. I can even tell the name of the bot!
You mean that right
yes yes yes
Yeah as already said, that is done automatically there is nothing you need to do
It's done automatically by Discord
You can't control it or write/change them manually
Oh, I see. I just thought it could be done separately somehow
Nope, not in that section
it's just that I already have slash commands
What you can do though
Then they need to be used and they will appear there
Though you can use </command name:command id> and write that down in the "About me" section of the bot
they appear only in verified Bots
It then looks like </command name:0> for example
And to copy a command ID, you just need to write the command and then right click on it
that is , command id ?
?
thanks man
So I'm trying to make a mini database with a json file that stores some info about discord users for a bot. I've watched multiple tutorials but all of them just create them not the way I need it. I would need something like this:
{
"IDV":{
"userId":562699506253168640,
"channelUrl":"https://www.youtube.com/channel/UCiUQbWlzRDO-WOr7Ld2z6Kg",
"latest video":"https://www.youtube.com/watch?v=UaB80cqQm7c"
},
"Ety60":{
"userId":721412435378176047,
"channelUrl":"https://www.youtube.com/channel/UCiUQbWlzRDO-WOr7Ld2z6Kg",
"latest video":"https://www.youtube.com/watch?v=4HA00LGtlTk"
}
I need to be able to search thru all usernames (In ex: IDV & Ety60) and get info when needed.
- I need to be able to add a new "user" with its data to the database
- I need to be able to get data when a username is given
- I need to be able to change specific data of a specific user
I just need help to get started...
please just use an actual database instead of JSON

maybe read this first
Ye I already read something like it
Thats its going to corrupt etc
Then what database should I use? sqlite?
sure
sqlite is as simple as databases can get lol. SQLite is file-based, so no worries about credentials and all of that other hassle. Learning some basic SQL is basically all you need to know
Indeed
there are some great resources to learn SQL such as https://sqlbolt.com, and to actually use sqlite you can check out the documentation on it: https://docs.python.org/3/library/sqlite3.html (though you probably want an async wrapper if you're gonna be using it with discord bots)
wait I need wrappers
nope thats not happening
I want it to be simple
I just need to store some data, like I already said
No need for big complicated data base sql ...
It's as simple as
pip install <name>
import <name>
jeez, you'd probably need an async io wrapper if you're gonna be using JSON too
why tho
sqlite is simple, the integration for async is likely drop in
I'm not stupid
So use an async wrapper instead of an awful json wrapper
I didn't mean installing it ofc thats simple.
I don't want to go thru the docs for hours just to store some yt channel id's
cause file operations are blocking
You said
I want it to be simple
Installing the correct async wrapper for sqlite is simple.
You will also need a wrapper for JSON either way, so directly go for the sqlite one.
ok sure
You'll need to read the documentation of JSON wrapper as well either way, so just read the one of sqlite
And if you need help with sqlite there's a #databases channel made for it
aiosqlite is fine
ok thnx
no problem and happy coding!
You mean happy reading docs 😉
Not that complex you'll see, most likely also have some examples. Otherwise yeah ask in #databases 
aioqlites docs are quite easy to read, very simple and straight forward
- reading documentations is part of being a developer

what if you make them? does that make you a pro😎
And the best way to never enter tutorial hell
documenting code 
I hate it
I actually love making documentations
🤨
Just not documenting code itself, that's horrible
i hate both, documenting the code and working with front end
But documenting your project or an API for example, that's nice
just not a nice experience
Depends honestly
i hate it when i document my code and the docs fail to build, i hate reading the readthedocs logs
they're huge
you write a wiki about the project?
nice
Or something that is used and needs documentation on how to use it
"Just try to figure out what I'm trying to accomplish by reading my function names, argument names, and my non-existent comments" 
But yeah not everyone likes it the same way 
Well good code doesn't need comments
The code itself is your comments
what the hell
only type: ignores 
ive actually never used that comment
Pretty useful (type checking-wise) when you wanna reverse-engineer something (like interaction objects)
Hmm just saw this
I hope you enjoy this video!
If you have any questions Don't hesitate to ask me
Thats an async bot with none async json
Welcome to the side of bad YouTube tutorials you should not be following
the code isnt good at all and look when the video was uploaded
- Using JSON is bad
- Not doing it async is bad
- It's 2 years old
Simply don't follow YouTube tutorials
Haven't seen any that is anywhere close to good
Lucas🥹
yes
knew it
i wish i never watched them
Good thing I never watch any YouTube tutorials
Documentation + articles are so much better for everything
Well the docs for discord.py are unreadable
His tutorials made me fall into tutorial hell and his code wasnt even good
They're if you have the knowledge of the paradigms the libraries uses
most python docs use the OOP paradigm
They all look the same so yeah
theyre mostly mapped the same also
no examples = unreadable
You read all that bs takes you an hour to understand and if they just put a fking example it would take 2 seconds to understand that shit
Even when I first read the documentation it wasn't hard to understand it
No?
You don't know how I understand and read documentations. You're not me.
No but I know that exaples are better
So don't say it's bullshit if you're the one not being able to read documentations properly.
waaaayyy easyer to understand
There are examples, the ones that are needed.
aka none
So you've never opened the documentation
I have
https://github.com/Rapptz/discord.py/tree/master/examples , there's examples for days on end
That explains everything now
A lot of times
I know but why are they not IN the documentions
Everything else that is not explicitly written is self explaining for someone that has the knowledge that is highly recommended before starting a bot.
?
Have you actually read the documentation?
You definitely have never read the documentation in that case.
I have
No you haven't
There is a quick start, lots of examples, as well as explanations for using commands etc.
I'm not saying you havent read the documentation but your opinions are just incorrect
Bruh not the quick start
So either you haven't read or you just don't want to take the time to read and navigate through the documentation properly.
!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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
No examples you say huh

I wonder what "Examples" means
2 of them
My bot keeps getting rate limited 😔
are you using replit?
where tho?
And those are just some among lots of examples
Ye
Nahh not lots
Your point is still incorrect
Because those don't need a goddamn example
Opinions are never incorrect @primal token
They're just attributes to use
To my definition of opinion yes and opinion can be incorrect but thats just my definition
You for real want something like
discord.Member
id - Attribute
Example
print(member.id)
name - Attribute
Example
print(member.name)
That's just not knowing that the library recommends you to know before starting.
You can have an opinion but not non sense
tfak is this for sentence
In that case you'll need to change, Replit is known for that as they share IPs among lots of projects. See the pinned messages to read why Replit is a bad solution.
To me an opinion should of course have based info to have that opinion and if it's incorrect i would say that opinion is wrong
Well I have been reading the docs to get things working and I did not have any examples for the things I was using so my opinion is that the docs are bad
Now happy?
That's from personal experience but do you have the knowledge needed to read the documentation? That's like doing a surgery without the knowledge of basic anatomy
An opinion is what you believe. If it is factually wrong then fair enough.
SO what there first going to let you do a course before you can start to use there documentions, thats bs
Discord.py is an advanced library after all
Any suggestions
What error are you getting?
That error is somewhere else entirely
full error
Also please paste the traceback as text, it's hard to read
Traceback (most recent call last):
File "F:\IT\Discord Bots\Neka\main.py", line 49, in <module>
asyncio.run(Neka().main())
File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "F:\IT\Discord Bots\Neka\main.py", line 24, in main
await self.custom_load_extension(path='commands')
File "F:\IT\Discord Bots\Neka\main.py", line 20, in custom_load_extension
await self.load_extension(f'{path}.{cog[:-3]}')
File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 937, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.play' raised an error: TypeError: callback 'PlayCommand.play' must have more than 1 parameter(s)
what's the code for your play command?
you forgot self as the first parameter
Traceback (most recent call last):
File "F:\IT\Discord Bots\Neka\main.py", line 49, in <module>
asyncio.run(Neka().main())
File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "F:\IT\Discord Bots\Neka\main.py", line 24, in main
await self.custom_load_extension(path='commands')
File "F:\IT\Discord Bots\Neka\main.py", line 20, in custom_load_extension
await self.load_extension(f'{path}.{cog[:-3]}')
File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.play' raised an error: TypeError: object NoneType can't be used in 'await' expression
add_cog needs to be awaited
yeeeeee, thanks you so much. I used to post on disnake, but now I have to switch to discord.py and it's very painful...
What's the best way to implement a command with pagination? @sick birch
how do i get the guild id
The guild’s ID.
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
why am i getting this error when the token is correct
Is the token hard coded or coming from an env or a config file or similar?
it is from .env file
make sure the env is being read properly
You can try printing out the token to see if it's None or your actual token
when i put the token in the main file it is working and when i get the token from env file its showing the error
thanks i did it now its working
can i make a dropdown menu of members?
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
This error occurs when I try to click cashout, any reason why?
https://paste.pythondiscord.com/ruxotoluza
ohh thx
you need to defer the interaction
@ui.button(label="Cashout", style=discord.ButtonStyle.green, custom_id="erqwkelrqwkadsf")
async def cash_callback(self, button, inter):
await self.Cashout()
button.disabled = True
button.label = "Cashed"
await inter.message.edit(view=self)
This results in not disabling and messed up format
#Authentication with twitch API:
client_id = os.getenv('client_id')
client_secret = os.getenv('Dweller_token')
twitch = Twitch(client_id, client_secret)
does anyone know how to get my twitch token?
Traceback (most recent call last):
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 800, in _load_from_module_spec
setup(self, **extras)
File "c:\Users\kouxi\Runa\cogs\twitch.py", line 102, in setup
bot.add_cog(TwitchCog(bot))
File "c:\Users\kouxi\Runa\cogs\twitch.py", line 15, in __init__
twitch = Twitch(client_id, client_secret)
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\twitch.py", line 168, in __init__
self.authenticate_app(target_app_auth_scope if target_app_auth_scope is not None else [])
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\twitch.py", line 436, in authenticate_app
self.__generate_app_token()
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\twitch.py", line 408, in __generate_app_token
raise MissingAppSecretException()
twitchAPI.types.MissingAppSecretException
how can i make my bot wait for something like a message
like when i press a button it should say: send your message
is there any way to do it?
!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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
yes. if ur using a lib check if they have implemented it yet
can you give a little example?
interaction.response.send_message
u mean reply to an interaction with a message or???? this question is confusing
There are two when you click to get on the documentation
Just use a modal
wdym
i don't want to use modal
i wnat to mention a user and it's not possible in modal
Click on the blue
i assume ur using chat cmds v
i want it to be like
Click Me Button
i click it
it says: mention the user
wdym?
Add in the button callback to use wait_for
no offense but ppl make stuff so complicated w bot sometimes
alright i'll check it out
it would be simpler to just use a slash command that has member parameter
dpy before 2.0 was a lot simpler imo
no like ur use case has no logic. It would make more sense to just use a slash command rather than creating an entire button
sending a message then using wait_for
a get a mentioned user in that message
i understand that it's total non-sense to use a button then add a whole different function to it when you can just use slash commands and make it simple
it's just that my client wants something else lol
tell him to wait for new select menu to be implemented into ur lib
you can fill them with roles, members, etc… now
I stopped making bots for ppl like that lmao
So bascially you're asking us to help you code something you're getting paid for instead of reading the documentation 
haha, i think you're right and it's best if i stick to slash command i'll just tell him it's waste of time
Why would you offer that in the first place
i am just asking for help not for your code i am not someone who likes to get spoonfed, i do sometimes ask for code (example code) to better understand how certain things work
you would be surprised at the amount of “bot devs” that get paid to make stuff for ppl who are literally copy pasting GH repos lol

Most libs have examples on the GH lib repo
ik dpy and disnake have them
Just use the documentation and examples, if you have the knowledge people want when buying your services then you don't need anything else than that
If you don't have the knowledge you're selling them and expect you to have, that's another situation
it's just people see other people doing that stuff they want a taste of it too
you're definitely doing something wrong somewhere but I can't tell where
format isn’t messed up. u put text in one box that made it longer
How do I get paid
u have cash out defined twice?
Reddit, discord servers that allow u to advertise services, networking. multiple ways
whatt
discords own implementation of automod killed most moderation bots IMO
It's nice, dyno/mee6 made a lot money with that
It detects different spam
they got some fast thinkers
u know what I recently found out discord is protecting mee6 lol
all the discord music bots mostly got removed yet you can still play YouTube videos with mee6 in VCs 🤣
L
Yeah you're right, they don't take actions on big bots. Jockie music bots are still playing music from yt and they even have premium perks from 1$-100$ monthly
yea sadgeeeee
Well we don't know what their internal specifications are
There was only one wave, and there are other bots than MEE6 that are still verified and still use YouTube
More might and probably will be coming later
And you don't know if MEE6 may have an official contract with YouTube - doubt they have but you never know
So wouldn't randomly speculate
i doing a command which requires to wait and lets say update time every one min and give result after 5 min, how do i achieve this?
disnake.
You can change Context class used in bot (https://github.com/DisnakeDev/disnake/blob/master/examples/custom_context.py)
how can you change Interaction class with that? i looked up in interaction_bot_base and didn't found something like getting interaction (i don't want to change library files)
You cannot really change the interaction class
This is due to the fact that Interaction object is sent by Discord, whereas the Context object is made by the library for an easier API usage
sad.. ok, thanks
I made a command named deathnote, i want it to go like, if user left reason null it will give output Heart attack but when i give reason it dont work and if i dont give a reason it says None(bad english btw)
@bot.command()
async def deathnote(ctx, member: discord.Member, *, reason = None ):
if reason==None:
reason=="Heart attack"
await ctx.send(f"User {member.mention} has died because of {reason}")
for commands, or interaction in general?
its possible for commands
You can simply do *, reason = "Heart attack" that way if there is no reason, it will default to heart attack
I think for commands will be enough for me.
Also won't
setattr(Interaction, "something", lambda self: print("hello"))
work?
bcs this code works:
class Something:
...
setattr(Something, "something", lambda self: print(self))
x = Something()
x.something()
Interaction class is slotted, it won't work
^
ohh
!d disnake.ext.commands.Bot.process_application_commands
await process_application_commands(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the application commands that have been registered to the bot and other groups. Without this coroutine, none of the application commands will be triggered.
By default, this coroutine is called inside the [`on_application_command()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_application_command "disnake.on_application_command") event. If you choose to override the [`on_application_command()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_application_command "disnake.on_application_command") event, then you should invoke this coroutine as well.
can override this method with providing your own interaction subclass
cool, thanks!
thanks a lot it worked!
it does say the bot is offline only your emoji is wrong
also
import disnake
from disnake.ext import commands
bot = commands.Bot()
setattr(disnake.Interaction, "test", lambda self: print("hello"))
@bot.slash_command()
async def show(interaction: disnake.CommandInteraction):
interaction.test()
bot.run()
this worked for me really, i got hello in console
but that will be better, ye
might be working, i really haven't checked any library:s souce code in a while
that's not true, it's saying that the Bot is offline
lmao you switched the emojis
probably the cache has not been updated yet
try to use an Api call
fetch_
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
nextcord.TextChannel
oh, you're using slash command
Use GuildChannel and SlashOption
You basically set test method for discord.Interaction class for no reason
it's an example
But why
i need to add some functions there
just because i want
it will make my life easier
I'd say this is an untypical way of extending functionality
Because you will have to do all this stuff for literally every function
You better make a custom subclass and then assign entire subclass to parent class name
Like
class MyInteraction(discord.Interaction):
def some_custom_func(self):
...
discord.Interaction = MyInteraction```
Apparently this works fine
"Its ugly, but fine as long as it works as intended" 😄
exenifix's method is better cause it will support stuff like IDEs autocompletes and typechecks lol
setattr wont help in either
Depending on what stuff he wants the functions to do it might be better to just use functions with interaction as argument instead of OOP
Even tho yr method is the correct one, tbh I feel like its ugly. I myself prefer editing the source files directly due, but we all got different opinions
I would fork if I wanted to extend functionality as well
Nice
But for stuff like "send success embed to interaction" I use some module with utility functions why bother subclassing internals and then overriding them
I agree
Diving in discord.py's source is the same as trying to dive into black magic ;-;
I never understood how everything works, all I know is, it ✨works✨
Python C sources (literally any C code actually) look even darker to me
Never tried to dive into it since I already have a headache for most of the day without diving into the same lol
can i make my cooldowns to only work if it's not me?
make ur custom cooldown
Its quite easy to read after you find the submethods of submethods of submethods
Why it doesnt work? py @bot.command() async def meme(ctx): subreddit = reddit.subreddit("dankmemes") all_subs = [] hot = subreddit.hot() for submission in hot: all_subs.append(submission) random_sub = random.choice(all_subs) url = random_sub.url name = random_sub.title author = random_sub.author upvotes = random_sub.score if random_sub.is_reddit_media_domain and not random_sub.is_video: embed = discord.Embed(title=name, description=f"{ctx.author.mention}", color=000000) embed.set_image(url=url) embed.set_footer( text=f'''from r/dankmemes by {author} | {upvotes} upvotes''') await ctx.send(embed=embed)
guildID I suppose
