#discord-bots
1 messages · Page 130 of 1
yeah you dont
might as well learn a bit of fast api in the process
but ill come back to it tomorrow
hii I'm using the new discord.py for slash commands I'm not sure how to set up cogs
is there any reference for using cogs?
thank you
but how do you ink the cog with main file
so when the main script runs it calls this cog
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
!slashcommands
How do I use args with the / commands?
When I do, I get this error: TypeError: parameter 'arg' is missing a type annotation in callback 'feedpeasant'
Code:
@client.tree.command(name = "feedpeasant", description = "Feed the peasants")
async def feedpeasant(interaction: discord.Interaction, arg='None') -> None:
role = discord.utils.find(lambda r: r.name == 'mod', interaction.message.author.roles)
if role in interaction.author.roles:
if arg == 'None':
await interaction.response.send_message('You must specify a peasant to feed')
else:
if arg == 'all':
await interaction.response.send_message('Feeding all peasants :bread:')
with open('log.txt', "a") as f:
f.write("\nA mod has fed all peasants \n Command has been run at: " + time.ctime())
f.close()
elif arg == interaction.message.author.mention:
await interaction.response.send_message('You cannot feed yourself goofy')
with open('log.txt', "a") as f:
f.write("\nA mod has tried to feed themselves \n Command has been run at: " + time.ctime())
f.close()
if arg != 'all' and arg != interaction.message.author.mention:
await interaction.response.send_message(f'Feeding {arg} :bread:')
with open('log.txt', "a") as f:
f.write("\nA mod has fed {arg} \n Command has been run at: " + time.ctime())
f.close()
else:
await interaction.response.send_message('You are not a mod, you peasant. Get back to bread farming.')
with open('log.txt', "a") as f:
f.write("\nA peasant tried to feed someone \n Command has been run at: " + time.ctime())
f.close()
so interaction.args?
no
ohhh, args: discord.Args
like arg: <the type you want the arg to be>
type meaning string?
yea
For most of my code, that works. Although for one part I'm not sure why it doesn't, it's the exact same layout as the others.
nvm got it
ty for ur help
How do i add slash command to cogs?
ty
How can I use CTX with / commands since I don't know how else to check a user's roles.
I'm making my Rpg game. I want to know, for example, you want to build a plant, it will take an hour to build, for example, there are workers, and they must somehow influence the time, 1 worker takes 2 minutes. How to take time from building? (discord.py, db - postgre)
@commands.cooldown(1, 60*60*24, commands.BucketType.user)
is there any way to store the cooldown somewhere so after the bot restarts it will continue your time
cant seem to find it in docs but is there a way to add the role icon images through a cmd?
nvm i found it 
I got an issue connecting to Mongo, and I have no idea what's going wrong as it was working perfectly yesterday.
I'm using it for a discord bot.
File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\main\Downloads\Personal Stuff\Christmasbot\cbot.py", line 558, in on_message
if (cb_cdata.count_documents(query_one) == 0):
File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pymongo\collection.py", line 1835, in count_documents
return self._retryable_non_cursor_read(_cmd, session)
I believe this is where the issue is, but the error is quite long. I can attach a .txt if needed. Any ideas?
How can I send a message multiple times, and not just have it reply to the user?
!paste use this for long output
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Rate bot pfp
.
Help please
store a mapping of building and time stamps
wdym just use edit_orginal_response if interaction else ctx.send
and edit the message
But it’s slash commands
And I want it to be separate messages
use interaction.channel.send
Remember you still need to respond
defer and send as chrispy says
You can't just defer
how do I role-lock a command?
make a check
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_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.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
ty
I keep the / right?
No
what do I replace it with then?
is it like
@discord.app_commands.checks.has_role(mod, /)?
No
/ indicates positional arguments
https://docs.python.org/3/glossary.html#term-parameter
These functions will be used for example:
def basic(pos_only, /, pos_or_kw, *, kw_only): ...
def var(*args, **kwargs): ...
```Python has 5 types of parameters:
• Positional-only, all parameters before `/` or `*args`
This can only be passed with `basic(1, ...)`, not `basic(pos_only=1, ...)`
• Positional-or-keyword, "normal" parameters
This can be passed with either `basic(..., 2, ...)` or `basic(..., pos_or_kw=2, ...)`
• Keyword-only, all parameters after `*,` or `*args`
This can only be passed with `basic(..., kw_only=3)`, not `basic(..., 3)`
• Var-positional, `*args`, inside the function this will be a `tuple`.
This takes as many positional args as you want to give it. This is used by `print`.
`var(1, 2, 3, 4, 5, ...)`
• Var-keyword, `**kwargs`, inside the function this will be a `dict`.
This takes as many keyword args as you want to give it. This is used by `dict`.
`var(foo=1, bar=2, baz=3, ...)`
did you read this at all
it just means everything before it must be positional
bro just(function)
yes, i got it
What can I replace them with
I'm good at coding but bad at design 💀
Make the edges more round
life of programmers || use turtle to draw ||
lol
is it possible to respond to the user if they don't have the correct role?
make the centre line discord nitro and add some sparkles on side ig
Yeah, handle an exception it raises
include wumpus in it
do it in the predicate
If he uses the has_role and not the custom check there's no predicate
Where would I put that? I've never done error handling
!d discord.ext.commands.Command.error 
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
i did say use a custom check
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.
lol
guys this is a slash command
from discord import Interaction
from discord.app_commands import AppCommandError
bot = commands.Bot(...)
# Bot has a built-in tree
# but this is the same for a
# CommandTree you define.
tree = bot.tree
@tree.error
async def on_app_command_error(
interaction: Interaction,
error: AppCommandError
):
...```
I forgor 🤗
...
!d disnake.ext.commands.Bot.on_slash_command_error 🦶
await on_slash_command_error(interaction, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default slash command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.11)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for slash command error.
Disnaek gud 👍
cause im not very smart
that doesnt even exist (in dpy)
where do I put that in my code?
anywhere
i meant using the tree.error my bad i wasnt specific
why? whats wrong
idk
well hover over it then-
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
@app_commands.has_permission(ban_members=True)
how can I make the user need perms to do a slash command?
how do I get more information on it?
@naive briar is there a way to reset the cooldown using a command?
🤨
also is there a way for it not to get erased when you reset the bot
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
User: Zio Economy#3124
Prefix: z
Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'purge' defined in function 'ban'
In parameter 'amount'
description._errors: [{'code': 'BASE_TYPE_REQUIRED', 'message': 'This field is required'}]
You have to store the cooldown somewhere in a database
@client.tree.command(name='purge', description='Deletes messages.')
@app_commands.describe(amount = '')
async def ban(interaction: discord.Interaction, amount: str):
if amount == '':
await interaction.response.send_message('Please provide an integer to purge.', ephemeral=True)
amount = int(amount)
if amount <= 0:
await interaction.response.send_message(f'Cannot purge {amount} mesages!.', ephemeral=True)
if amount >= 201:
await interaction.response.send_message(f'Cannot purge more than 200 mesages!.', ephemeral=True)
if amount <= 200 and amount >= 1:
purge = discord.Embed(title='purged', description=f'**Purged**: {amount} message')
await interaction.channel.purge(limit=amount)
await interaction.response.send_message(embed=purge, ephemeral=True)
okay, how about resetting the cooldown?
!d discord.app_commands.Cooldown.reset
reset()```
Reset the cooldown to its initial state.
guild not defined
@bright wedge like how do i do that then
do i do in the async def guild?
@bot.command()
@commands.has_permissions(administrator=True)
async def changeprefix(ctx, prefix):
with open("prefix.json", "r") as f:
prefix = json.load(f)
prefix[str(guild.id)] = prefix
with open("prefix.json", "w") as f:
json.dump(prefix, f)
you write this pert?
ctx.guild
!d discord.ext.commands.Context.guild
Returns the guild associated with this context’s command. None if not available.
oh thanks
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1422, in on_message
await self.process_commands(message)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1418, in process_commands
ctx = await self.get_context(message)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1324, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1266, in get_prefix
ret = await nextcord.utils.maybe_coroutine(prefix, self, message) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\utils.py", line 548, in maybe_coroutine
value = f(*args, **kwargs)
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 23, in get_prefix
prefix = json.load(f)
File "C:\Program Files\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Program Files\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Program Files\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
def get_prefix(bot, message):
with open("prefix.json", "r") as f:
prefix = json.load(f)
return prefix[str(message.guild.id)]
bot = commands.Bot(command_prefix= get_prefix , help_command=None, intents=nextcord.Intents.all())
@bot.event
async def on_guild_join(guild):
with open("prefix.json", "r") as f:
prefix = json.load(f)
prefix[str(guild.id)] = "!"
with open("prefix.json", "w") as f:
json.dump(prefix, f)
@bot.command()
@commands.has_permissions(administrator=True)
async def changeprefix(ctx, prefix):
with open("prefix.json", "r") as f:
prefix = json.load(f)
prefix[str(ctx.guild.id)] = prefix
with open("prefix.json", "w") as f:
json.dump(prefix, f)
Brackets in your js file
👍
What do you mean
Must use custom function
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 24, in get_prefix
return prefix[str(message.guild.id)]
KeyError: '1036249066193047562'
do i use int
whats prefix
Yes
ill try
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 24, in get_prefix
return prefix[int(message.guild.id)]
KeyError: 1036249066193047562
just put a try except
You need to create it, there is no ready function for that.
It's easy if you think it
The key doesn't exist
And JSON isn't a database
Store your ids as int
Okat
How can i build in a simple rich presence
Hey @prisma crystal!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
How would I go about removing a title from an embed when done embed_to_dic
help
I would just set the embed's title property to None instead of converting it to dict then convert it back
Its a webhook copying from one channel to another, and dk wot cld be in first embed
how do you delete a channel with discord py
embed.set_image('https://static.wikia.nocookie.net/monopoly/images/a/a5/Monopoly_Board_Game_%28UK%29.jpg/revision/latest/scale-to-width-down/1000?cb=20220120173735')
```this is not how u use it?? (2 argument is given but 1 is only needed)
!d discord.TextChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
I don't know what do you mean 🫠
how does this work
Its confusing dw 🙂 , i think jsut gunna edit the dict easiest way forward imo
Doesn't seem like it 
await interaction.channel.delete()?
@slate swan
a
thank you
how do i make my bot only listen to user?
A specific user or all users that isn't a bot
how do you do all users that isnt a bot?
!d discord.User.bot - check if this is True or not
Specifies if the user is a bot account.
add me i wanna ask u something
why u deleting ur messages now
and y u aint responding
can you leave me alone
.
how to add cogs to the new discord.py slash command version?
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
provided u made ur bot with commands.Bot and not discord.Client
👍
im not on pc rn im outside ill try help later if u havnt already resolved ur problem
ok 👍
bro just add cog as u do normally
wait I confused with you both guys 🤣
can I show my code to you?
import discord
from discord import app_commands
from discord.ext import commands
class test(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command(
name="ping",description="whatever"
)
async def ping(
self,
interaction: discord.Interaction,
):
await interaction.response.send_message(f"Pong! {round(app_commands.latency * 1000)}ms")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(test(bot), guilds=[discord.Object(id=456)])
``` this is in my cogs/test.py
is there any mistakes?
how do you make the bot delete 2 messages instead of only 1?
seems fine yes
yet it doesn't show up on my bot
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
``` is in my main.py
oh lemme try
says await out of functions
It only works in a async function
if I make a function for this then where should I call it? on_ready?
ok
@bot.event
async def on_ready():
print('Bot is up and ready')
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} command(s)')
except Exception as e:
print(e)
``` the main func
Reading the walkthrough would have told you that
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
yep seems like I already had a setup_hook in the on_ready
setup_hook is an event
this isnt working
oh like on_ready
can anyone help, its supposed to post whatever the user sends into a embed
nothing is happening
@shrewd apex the cog is not syncing 🤦♂️
u don't sync the cog u do bot.tree.sync()

i changed
like in this?
changed it to what?
dude
whats the point of that line
i need my bot only respond to discord people not bots
Hey so I have a modal, How do I send the modal embed to another channel, A channel with it's ID
then that if statement does that... remove the other one
so if message.author.bot:
anyways it wont matter
your first if statement checks the user id
it's only going to execute the rest of the code if the message author's id is that
?
oh right
what do you mean by the modal embed
fetch the channel and then send the embed thru it
i cant send much im on phone
dont get how do i edit the inter thing
could u send ur current code and ill see if i can try
ok
async def callback(self, interaction) -> None:
embed = disnake.Embed(title="Apply for Pilot")
for key, value in interaction.text_values.items():
embed.add_field(name=key, value=value, inline=False)
await interaction.response.send_message(embed=embed)
@client.slash_command()
async def apply_pilot(inter: disnake.ApplicationCommandInteraction):
await inter.response.send_modal(modal=MyModal())
ah ill have to look at it on pc @cold oyster srry
how i can make a slash command works in all guilds?
@tree.command(name = "test", description = "My first application Command")
async def first_command(interaction):
await interaction.response.send_message("Hello!")
sync the tree globally
await tree.sync(guild=None)
you can just await tree.sync()
in ur callback try do channel = interaction.guild.get_channel() and put your channel id in the parenthesis then under just type await channel.send(embed=embed) this is what i think ur tryna achieveme btw
ty
should I've mentioned earlier that I'm trying to use slash commands? If that make any change
hey, when I launch my bot it says process with exited code 1 do you have an idea please?
File "c:\Users\HP\OneDrive\Desktop\Folder\Qbot\main.py", line 76, in callback
await channel.send_message(embed=embed)
AttributeError: 'TextChannel' object has no attribute 'send_message'```
async def callback(self, interaction) -> None:
embed = disnake.Embed(title="Apply for Pilot")
channel = interaction.guild.get_channel(1037373141460193350)
for key, value in interaction.text_values.items():
embed.add_field(name=key, value=value, inline=False)
await channel.send_message(embed=embed)
@client.slash_command()
async def apply_pilot(inter: disnake.ApplicationCommandInteraction):
await inter.response.send_modal(modal=MyModal())```
My code
its just channel.send
wdym
oh ok
hey, when I launch my bot it says process with exited code 1 do you have an idea please?
It's send the embed, But in the modal it says "Something went wrong"
could u screenshot
alr
Hmm
Hey @mystic birch!
It looks like you tried to attach file type(s) that we do not allow (.js). 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.
Respond to the modal's interaction
hey, how did you send it like that with the colors please?
add py to the end
py
@mystic birch
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
are these aphostrophes?
no?
backticks
you are dont lie as soon as i saw that embed from your message i knew instantly you had contact with my friend and now hes told me that ur an alt of a scammer who makes scam roblox servers
thanks
no I don’t
I’m not a alt either 💀
You got no proof either
suddenly I can't launch my bot you know why? I put the token lower
And you know nothing abt what I do and my story so yeah
Go ask in discord.gg/djs
thanks
🥸
anyways keep ur story in my dms and dont talk here
Nah I don’t feel like wasting time on you anyways
this channel lol
🍵
why does the tea emoji look like matcha tea
Hello i want to make a discord bot that outputs the newest video of a channel with a slash command i managed to get the video id with yt api now how do i form the link i want to add
(data["items"][0]["id"]["videoId"])
infront of
https://www.youtube.com/watch?v=
!fstring
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
@slate swan
show full code
?
i now get this
print(f"https://www.youtube.com/watch?v= {data["items"][0]["id"]["videoId"]}") ^ SyntaxError: f-string: unmatched '['
use single quotes in your f string
you can't use " inside a f string with "
toggle one of them
!e
print(f'{"lol"}')
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
lol
@commands.is_owner() how do i put discord user id instead
!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.
thank you very much
has been there's for more thana year from what i remember
*than a
Guess i just cant remember
How do i get message.content in a variable from a slash command?
so you know in async def command(args) well one of args will need to be discord.Interaction I think well for next-cord that's it
@client.tree.command()
async def test(interaction: Interaction):
im using this
what do i change here
to get user input
join is an int
What?
sorry join is an int lmao
voice[1] returns an int and you're trying to use in to the variable that has its value which would be join
!e
1 in 1
@primal token :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: argument of type 'int' is not iterable
I'm pretty sure most libraries use arguments, but how do you set them up? I'm not sure, you would need to find out
what are the arguments?
?
@client.tree.command()
async def test(interaction: Interaction):
what do i change here
async def uwu(inter: discord.Interaction, argument: str) -> None:
...
# Usage: /uwu yes
@bot.tree.command(description="idk")
async def msg(inter: discord.Interaction, message: str) -> None:
print(message)
,
uwu ;-;
uwu namespaces the hell
ashley moment
ahem
sarth got bad memories
hell yeah
we all do dont we ;-;
😔
samarth moment
When i try to do this command the Bot does not anwser i want the bot to send the link and the person who uses the command to be able to put in some text that comes after the link
`#Send message "video" when user sends /video
@slash.slash(name="video", description="Sends newest video", options =
[manage_commands.create_option( #create an arg
name = "text", #Name the arg as "text"
description = "....", #Describe arg
option_type = 3, #option_type 3 is string
required = false #Make arg required
)])
async def _space(ctx: SlashContext, sentence):
newword = "" #define new sentence
for char in sentence: #For each character in given sentence
newword = newword + char + " " #Add to new sentence with space
await ctx.send(content=newword) #send mew sentence
async def _help(ctx: SlashContext):
await ctx.send(content=f'https://www.youtube.com/watch?v={(data["items"][0]["id"]["videoId"])}')`
i got an error my code is ```py
import discord
from discord import app_commands
class aclient(discord.Client):
def innit(self):
super().innit(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = 990534020880277514))
self.synced = True
print(f"We have logged in as {self.user}")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name = Hello, description = "Hello user", guild = discord.Object(id = 990534020880277514))
async def self(interaction: discord.Interaction, name: str):
await interaction.response.send_message(f"Hello {name}! I was made by me!")
client.run('xxxxx')```
what is it?
ping when anyone is ready
!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.
Can someone help?
Which library are you using
this is a dm command that sends a message to a specific user but for some reason it only sends the the first word of what I want to send.
e,g If I wanted the bot to send hello world it would only send hello
you spelled _init_ wrong
bruh
that was
fixed?
how do i make my bot automatically delete a embed it sends after a few seconds
!d discord.TextChannel.send
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.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Set the delete_after
When i try to do this command the Bot does not anwser i want the bot to send the link and the person who uses the command to be able to put in some text that comes after the link
`#Send message "video" when user sends /video
@slash.slash(name="video", description="Sends newest video", options =
[manage_commands.create_option( #create an arg
name = "text", #Name the arg as "text"
description = "....", #Describe arg
option_type = 3, #option_type 3 is string
required = false #Make arg required
)])
async def _space(ctx: SlashContext, sentence):
newword = "" #define new sentence
for char in sentence: #For each character in given sentence
newword = newword + char + " " #Add to new sentence with space
await ctx.send(content=newword) #send mew sentence
async def _help(ctx: SlashContext):
await ctx.send(content=f'https://www.youtube.com/watch?v={(data["items"][0]["id"]["videoId"])}')`
huh
What's the problem
it doesnt work
That doesn't help me understand why
And I've never seen manage_commands in discord.py before
The bot starts but when i try the command it says application doesnt react
i can use /video [text: test]
but when i send it it wont respont
Do you get any errors in the console
wait
An exception has occurred while executing command video:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 744, in invoke_command
await coro
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 145, in invoke
return await self.func(*args, **kwargs)
TypeError: _space() got an unexpected keyword argument 'text'
It seems like the library is calling the slash command's callback with the option names as kwargs. Try changing the option name to sentence or changing the sentence argument to text
thanks
now it gives a text but not the link also there a spaces between every letter
!e
text = "Hello, world!"
new_text = ""
for char in text:
new_text += (char + " ")
print(new_text)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
H e l l o , w o r l d !
how to stop bot command discord.py?
how do i put the inputed text behind the link?
!join check this out
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
I already know about it
Ah okay
why wont it delete the embed after sleeping for 4 seconds??
it's because messages can be deleted, embeds cannot
and where is embedvar even coming from
embeds cant be deleted at all?
thats where embed came from
uh...no?
a message contains embeds
so delete the message containing embeds
im confused by what u mean
channel.send returns the sent message
Store that in a variable then delete it
alright
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Or just set the delete_after argument
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 37, in sync
await interaction.response.send_message(f"synced {len(synced)} commands in this guild!", ephemeral=True)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/interactions.py", line 718, in send_message
await adapter.create_interaction_response(
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'sync' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
@client.tree.command(name='sync', description='If commands arent working or there oudated, use this.')
async def sync(interaction: discord.Interaction):
synced = await client.tree.sync(guild=interaction.guild)
await interaction.response.send_message(f"synced {len(synced)} commands in this guild!", ephemeral=True)
```
It took too long to respond
Also this is not the way to do this.
Register globally instead.
keep getting erros when doing this
What's the error then
For the await channel.send make it into a variable and call the variable with .delete() at the end
use the delete_after lol
Or that
Your pc specs lol
Is that an arg?
kwarg
how?
like that?
r u using buttons
Don't assign a guild.
c = await interaction.guild.create_text_channel(
f"Ticket {interaction.user.id}", overwrites=overwrites)
await c.send(
f"{interaction.user.mention} **Please wait for staff**, Your **next** ticket can be open in **5m**. **Staff members** do **{prefix}close** to **close this ticket**. **(#{client.ticketnumber})**"
this would be easier to do
im not using buttons @slate swan
Why don't you make message send in channel using the button it's easier and more convenient
yea^
and you can check if they have a ticket
Using an event is very excessive
ticket = utils.get(interaction.guild.text_channels,
name=f"ticket-{interaction.user.id}")
if ticket is not None:
await interaction.response.send_message(
f"{interaction.user.mention} you already have a ticket open here {ticket.mention}.",
because i need my bot to send a message as soon as a ticket is made via ticket tool then to delete itself after a few seconds
yea
Yea, you can do it the way I said lol
here @winter coral
but i cant have buttons
You can still do it
@stark zenith *
its better
i js want a quick message saying "waiting for a sessiosn" then it deletes itself after a few seconds
alright
c = await ctx.guild.create_text_channel(f"Ticket {ctx.author.id}")
message = await c.send(
f"{ctx.author.mention} waiting for sesson"
await asyncio.sleep(5)
await message.delete()
Fair enough, but put the channel create from command into variable for example
chnanel_created = guild.Chanel.create or whatever
msgg = chnanel_created.send("hi")
time.sleep(5)
msgg.delete()
A lot more efficient
Perfect example
yea lol
just took it from mine 😎
Lol I have done the same thing with mine too
I mean it's most convenient way so I'm not surprised
yea
i love making slash commands]
Ngl i use to use discord py but now I use nextcord due to the fact of discord py devs randomly quiting the project
What database
json
ik its not the best but
What?
idk
json isn't a database
it is now
💀
-_-
Why is pip install discord working with 3.10 but not 3.11?
^
I haven't used mongodb myself but how is it easier? You literally write what you want done in sql and it does it 
MongoDB is a simple and easy to use database. This tutorial will show you how to use MongoDB with python and the python module pymongo. Pymongo is the offical MongoDB API that allows for you to easily perfor mdatabse operations.
Please Note: This is simply the basics of MongoDB in python, it is meant to get you started and give you an introduct...
Use it and you will see why
People sometimes think it's easier because it's unstructured
But for something like Discord a relational database is more fitting due to the relational nature of its data
I need structure in my life 
same friend
Correct that's why
What database is best for discord.py?
hmm yea i've seen many use mongo
any idea when it will?
Fun fact: when discord was first released it used mongo db but they had to migrate to Casandra due to a lot of issues
i prefer pickle
@slate swan this wont work see anything wrong i could fix?
really depends
Remove the first channel send and in 2nd one put await in front of it
msgg = await channel.send(embed=embedVar)
ah alr ty
thiserror now
it was never awaited so what do you think needs to be done
Take a minute and read the error
oh im dumb 💀
agreed
Woo learning 📈
alright i think i got lemme run it
yeah learning py i think im doing good so far
started 3 days ago so yeah
I think its the easiest error / warning you can get
works 👍 thanks guys
Yea I love it when they tell me exactly what I missed
@client.tree.command(name='sell', description='Sell your items here!')
@app_commands.describe(amount='How much to sell?')
@app_commands.describe(choices='Choose an item!')
@app_commands.choices(choices=[
discord.app_commands.Choice(name='Clownfish', value=1),
discord.app_commands.Choice(name='Sunfish', value=2),
discord.app_commands.Choice(name='Nametag', value=3)
])
async def sell(interaction: discord.Interaction, choices: discord.app_commands.Choice[int] ,amount: int):
if choices == 1:
how can I see what the user put for the choice?
Discord py is asynchronous so you need to await shit
What do you mean by see what they put
chill idk how bruh
What's a tree I've never seen it before
.
read the docs
i dont understand the docs?
im trying to run a command based off the user input
So what's the problem? If choices == sunfish: do a thing
yea basically
So what's the question
Never heard of her
Why not bot.slash_command()
discordpy does have slash_command
It uses a tree as a container for application commands
design choices lol, danny didn't want to implement it in the commands framework but another app_commands one
Also the tree gives more control over what you can do with app commands
can someone help me make a sync command
i tried here but i get this error
I didn't know there were any differences tbh I just thought it made more sense to use the tree
🗿 read the source code and you'll find much more interesting stuff there
Did you sync your sync command to make it accessible lol
imagine syncing a command to sync a command that syncs commands
can someone help me why my command isnt working
well show the actual command
the color is suppose to be a integer and you gave it a string
did u put smth like: discord.Color("red")
That's a good one
@client.tree.command(name='sync', description='If commands arent working or there oudated, use this!')
async def sync(interaction: discord.Interaction):
synccmds = await client.tree.sync(guild=interaction.guild)
await interaction.response.send_message(f"synced {len(synccmds)} commands in this guild!", ephemeral=True)
return
can someone please help me fix this?
same error
send ur code
@client.command()
async def update(ctx):
embed = discord.Embed(
title = 'title',
description = 'desc',
colour = None
)
embed.set_footer(text = 'this is a footer')
embed.set_image(url='')
embed.set_thumbnail(url='')
embed.set_author(name='Jordan', icon_url='')
embed.add_field(name='field name', value='field value', inline=False)
embed.add_field(name='field name', value='field value', inline=True)
embed.add_field(name='field name', value='field value', inline=False)
embed.add_field(name='field name', value='field value', inline=True)
await client.say(embed=embed)
I told you to not pass color
did you
u want my help?
any idea when discord.py will start working with 3.11?
your helping now anyone can help but your choosing too
nope
rephrase that
it works with 3.11....
your already choosing to help so I don't need to ask
@visual trellis he doesnt have to help...
ik he dont need to
hence why i said hes choosing too
not for me
when I try to do pip install discord it gives me an error
yes and when an error gets raised , you should read it
it has the solution mentioned
and its pip install discord.py, not pip install discord
anyone know how i can 2 embeds together like this? cant find any resources online helping me with it
i try both
same error
send(embeds=[embed1, embed2])
its literally in the docs
thanks
Can someone help me make a on message event, so basically if someone says a word, lets put "free" as an example, It says don't beg for free stuff, then deletes the users message, which in my case is free
def get_prefix(bot, message):
with open("prefix.json", "r") as f:
prefix = json.load(f)
return prefix[int(message.guild.id)]
bot = commands.Bot(command_prefix= get_prefix , help_command=None, intents=nextcord.Intents.all())
@bot.event
async def on_guild_join(guild):
with open("prefix.json", "r") as f:
prefix = json.load(f)
prefix[int(guild.id)] = "!"
with open("prefix.json", "w") as f:
json.dump(prefix, f)
@bot.command()
@commands.has_permissions(administrator=True)
async def changeprefix(ctx, prefix):
with open("prefix.json", "r") as f:
prefix = json.load(f)
prefix[int(ctx.guild.id)] = prefix
with open("prefix.json", "w") as f:
json.dump(prefix, f)
error:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1422, in on_message
await self.process_commands(message)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1418, in process_commands
ctx = await self.get_context(message)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1324, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1266, in get_prefix
ret = await nextcord.utils.maybe_coroutine(prefix, self, message) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\utils.py", line 548, in maybe_coroutine
value = f(*args, **kwargs)
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 24, in get_prefix
return prefix[int(message.guild.id)]
KeyError: 1036249066193047562```
jsons don't have integer Keys
you meant to use str(message.guild.id) there maybe
and stop using json as a database!
i dont know database so i am using json for now
Can someone help me with this py @client.event async def on_message(message, inter: discord.Interaction, user: discord.User): message = "free"
u do discord.Member
How can i do so if someone says that word, in any channel, bot deletes the users message and Pings it and says: This word is blacklisted
message.content btw
message: message.content?
message = "free"
All I need is a small event
in here
@client.event
async def on_message(message, inter: discord.Interaction, user: discord.Member):
message.content = "free"```
I have this now
if message.content == “free”:
await message.delete()
something like that i think
u should use if statment
if message.content == “free”:
await message.delete()
await message.author.send(f“{message.author.mention} this is a blacklisted word”
something like that i think so hard on mobile
embed.colour=int("0x" + colour, 16)
so thats what i did how do i do that if they put a color like red it will be red and not w hex
@warped mirage try this
@client.event
async def on_message(message, inter: discord.Interaction, user: discord.Member):
message.content = "free"
if message.content == "free":
await message.delete()
await message.author.send(f"{message.author.mention} this is a blacklisted word");```
so this?
without message.content = "free"
cuz u already did it
@client.event
async def on_message(message, inter: discord.Interaction, user: discord.Member):
if message.content == "free":
await message.delete()
await message.author.send(f"{message.author.mention} this is a blacklisted word");```?
What are you even trying to do
I think you want message.channel.send instead of message.author.send
how can i make it so that when i input a number and another one that it becomes 1 for example 2 and 1 it becomes 21
i want so it pings the user
That's what the f string is for
might be a weird question
I've downloaded the thing it told me to
doesn't work still
Convert them to string then join them together
@client.event
async def on_message(message, member: discord.Member):
if message.content == "free":
await message.delete()
await message.channel.send(f"{member.mention},\nDon't beg for free stuff...\nUse [#95138054399863123](/guild/267624335836053506/channel/95138054399863123/) to beg!", after_delete = 10)```
err: TypeError: on_message() missing 1 required positional argument: 'member'
How can i fix?
how ?
embed.colour=int("0x" + colour, 16)
so thats what i did how do i do that if they put a color like red it will be red and not w hex
on_message event should have only message in the parameter
member isnt defined now.
Then get the member from the message
How?
!d discord.Message.author
@client.event
async def on_message(message):
if message.content == "free":
await message.delete()
await message.channel.send(f"{member.mention},\nDon't beg for free stuff...\nUse [#951380543998663123](/guild/267624335836053506/channel/951380543998663123/) to beg!", after_delete = 10)```
this is what I have
didnt i already sent u sum ab the author
Doesnt work
🥲
And either way, it starts with "member"
!e
nums = (0, 1, 9)
print("".join(map(str, nums)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
019
Can someone please help?
ok
embed.colour=int("0x" + colour, 16)
so thats what i did how do i do that if they put a color like red it will be red and not w hex
u didnt bring member in it, example.
async def on_message(message, member: discord.Member):
So how do i fix?
bring member syntax in on_message
Don't
message.author?
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
So i showed what i have atm, can someone help me fix?
whats the problem tho
currently, member is not defined
embed.colour=int("0x" + colour, 16)```
so thats what i did how do i do that if they put a color like red it will be red and not w hex i made that members can make an embed and they need to choose color
message.author?
I want so it pings the member
wait so message.author.mention doesnt work?
i tried
It deleted message but
await message.author.mention(f"Don't beg for free stuff...\nUse [#951380543998668810](/guild/267624335836053506/channel/951380543998668810/) to beg!", after_delete = 10)
TypeError: 'str' object is not callable```
?
The f string is what you notice first lol
Just like you did in the f string here
How do i fix?
how can i do it with input numbers like i have this
@bot.command()
async def f(ctx, express: str):
print("".join(map(str, express)))
``` but it only gives 1 number and not 2 or 3 or 4
await message.channel.send(f”{message.author.mention}”)
await message.channel.send()
They told you like 5+ times
thats what i did
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
@warped mirage
help
This won't even work.
it wont?
And why would you f string a single variable
String isn't closed.
its hard on mob sorry
await message.channel.send(message.author.mention)
im just saying to put it in the f string cos he wanted to say something else with it
@client.event
async def on_message(message, ctx, member:discord.Member):
if message.content == "free":
await message.delete()
await ctx.send(f"{ctx.author.mention} Don't beg for free stuff...\nUse [#951380543998663123](/guild/267624335836053506/channel/951380543998663123/) to beg!", after_delete = 10)```
ty
@warped mirage just copy what he sent at this point tbh ^
how can i do it with input numbers ?
just like a calc like this
@bot.command(aliases=["calc"])
async def calculator(ctx, *, expression:str):
calculation = eval(expression)
embed = discord.Embed(title="Calculator:", color=color)
embed.add_field(name="Input:", value=f"{expression}", inline=False)
embed.add_field(name="Result:", value=f"{calculation}", inline=False)
await ctx.send(embed=embed)
I don't know what do you mean by that
ill explain
so i have this
async def f(ctx, express: str):
print("".join(map(str, express)))```
And someone can do some naughty things if you're using eval for the calculator
but this doesnt work cuz it only print the first number
?
like what ?
You're only getting one argument
how can i make it more ?
@bot.command()
async def f(ctx, express: str, number1: str, number2: str):
print("".join(map(str, express)))```
eval() is tempting, but it’s truly dangerous. Here’s how common safety attempts can be circumvented.
but like i want infinite numberos
i believe, or im wrong
that can work but only with 3 number or smth
Yes, but if you keep assigning it, you can have more.
what does os.system('clear') do ?
Clear the console
You can do something like
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py#L45-L47
examples/basic_bot.py lines 45 to 47
async def choose(ctx, *choices: str):
"""Chooses between multiple choices."""
await ctx.send(random.choice(choices))```
clears the console on linux systems
clears the console
is this for infinite numberos ?
Not just linux
Yes just linux, windows is cls
what am i supposed to do with this ? it only gives the last given number
What do you mean
What does your code look like
hey guys
i worked on my discord bot and i want to use like a restart command do you know how to code it
@bot.command(description='For when you wanna settle the score some other way')
async def choose(ctx, *choices: str):
"""Chooses between multiple choices."""
await ctx.send(random.choice(choices))
You're choosing random element from it
it has to be a list
what should i do ?
@bot.event
async def on_raw_reaction_add(payload):
print(payload.member.id)
channel = bot.get_channel(payload.channel_id)
user = bot.get_user(id=payload.user_id)
print(str(user.name))
print("reaction added")
if (payload.member != bot.user):
await channel.send((user.id, "just reacted to a message!"))
The goal is to send a message when someone adds a reaction to a message for some reason user is returning "none"
im coding with disnake
!d discord.Client.get_user - the user was not found
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
And you must have members intent enabled
just do os.system("clear")?
That's not the same.
It has to logout fron the bot and re login
you need to install that too, only downloading wont help
os.execv() later
!d discord.Client.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
install what
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
it's a function
use brackets
can u show me how i should do it?
"Visual studio C++ not found" thats what the first line in the image says, take a hint maybe?
cause i dont know how
can someone give me a spicy layout for a help embed 🙏 (@)
in python and in every other language you use brackets to run a function
so bot.close()
do you use cogs?
nah
i downloaded that
but I can edit it if it is one
like this
guess what, didnt work
and now you install it....
yes
ok let me try
yeah it works for hundreds of people but not you, cool
use slash commands in this modern era
i did that bro
they are well descriptive
and how can restart it
added it to path?
!d disnake.Client.start
aren't slash cmd descriptions enough?
?
await start(token, *, reconnect=True, ignore_session_start_limit=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.login "disnake.Client.login") + [`connect()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.connect "disnake.Client.connect").
Their docs pages looks beautiful
I mean, you don't really need help menus for slash commands
Nextcord ->>
yea but its still looks neat, dyno has it, disboard, dank memer, list goes on
at current state, hell nah
the rewrite might be interesting tho
if i were to rate discord libs it would be like
hikari
disnake
dpy
nextcord
hm dont know where to put it
I'm planning to make a help menu for my slash commands. However, mine in particular deals with 10+ roles being stored as well as channel options and stuff so it needs a bit more explaining
You forgor discord_components
and discord_utils.slash
what is pycord?
Pycord is super underdeveloped
how can I add a cooldown to slash cmds...
ffmpeg wrapper 
!pip pycord
im very confused
yup
i had some dude trying to help me yesterday
i did it in front of him and even he was confused
that's a different case when it's something complicated for users

!d discord.app_commands.Cooldown
class discord.app_commands.Cooldown(rate, per)```
Represents a cooldown for a command.
New in version 2.0.
is there such thing in disnake?
!d disnake.ext.commands.Cooldown
class disnake.ext.commands.Cooldown(rate, per)```
Represents a cooldown for a command.
so it's same for slash and prefix based cmds
well that's actually an issue of some libraries that discord.py depend on, they dont' have wheels for python 3.11 built yet, eventho they have pull requests for that its taking time
oh alright
do you know when it'll be fixed or nah?
that's upto those libraries' maintainers, i can;t say anythin
@client.tree.command(name="beg", description="Beg for money!")
@commands.cooldown(1, 10, commands.BucketType.user)
@client.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(error)
else:
raise error
why doesnt this work
You are using a message cooldown on a slash command.
There's no on_application_command_error event
app_commands.CommandOnCooldown

and this, you'll be using @client.tree.error instead
how can I make it be for slash commands?
there's something called on_app_command_error but idk what class it belongs to
@discord.app_commands.Cooldown(1, 10)
Not that easy
@client.tree.command(name="beg", description="Beg for money!")
@app_commands.checks.cooldown(1, 15, key=lamdba i: (i.user.id))
what about this
im interested
How can i build in a simple rich presence, my friends told me it does not work
from typing import Callable, TypeVar
from enum import Enum
from discord.app_commands import Cooldown
# noinspection PyProtectedMember
from discord.app_commands.checks import _create_cooldown_decorator
T = TypeVar('T')
class Btypes(Enum):
guild = lambda i: (i.guild_id, i.guild_id)
channel = lambda i: (i.guild_id, i.channel_id)
user = lambda i: (i.guild_id, i.user.id)
def koeldown(rate: float | int, per: float | int, btype: Btypes) -> Callable[[T], T]:
return _create_cooldown_decorator(btype, lambda interaction: Cooldown(rate, per))
# Usage
from utils.cooldowns import Btypes, koeldown
@koeldown(1, 150, Btypes.user)
async def...
this right?
..```py
@client.tree.error
async def on_app_command_error(error: app_commands.AppCommandError, interaction: discord.Interaction):
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message(error, ephemeral=True)
else: raise error
Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at /home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py:1087> exception=TypeError('exceptions must derive from BaseException')>
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 872, in _invoke_with_namespace
if not await self._check_can_run(interaction):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 1010, in _check_can_run
return await async_all(f(interaction) for f in predicates)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/utils.py", line 662, in async_all
elem = await elem
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/checks.py", line 407, in predicate
raise CommandOnCooldown(bucket, retry_after)
discord.app_commands.errors.CommandOnCooldown: You are on cooldown. Try again in 12.99s
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
await self._call(interaction)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1244, in _call
await self.on_error(interaction, e)
File "main.py", line 129, in on_app_command_error
raise error
TypeError: exceptions must derive from BaseException
I suggest building the error on the base of the tree
?
I've made it in my own bot as well, example: ```py
class CmdTree(CommandTree):
"""A subclass of CommandTree to override on_error"""
async def on_error(self, interaction: Interaction, error: AppCommandError) -> None:
# Per usual, getting the original error
error = getattr(error, 'original', error)
log.debug("Reached error_handler")
if isinstance(error, (NotFound, HTTPException, Forbidden)):
log.warn(f"'{interaction.command.name}' command raised {error.status} {error.__class__}")
raise error
elif isinstance(error, CommandOnCooldown):
await interaction.response.send_message(
f"This command is on cooldown! Time left: {time_fmt(error.retry_after)}", ephemeral=True)
else:
raise error
@slate swan A lot on slash isn't easy, many work arounds and things need to be taken into account.
im watching a yt vid and it works for him ._.
What date was the video released?
Isn't the purpose of a global error handler to handle errors? So why do you raise the error
5 months ago
unhandled errors shall be raised, or atleast logged somewhere
what if there's some error that's totally random, it will just be silenced
Because if it is any other error I most likely made a coding error, this isn't a public bot so I don't have any permissions errors etc anyways.
!d discord.User.mention
property mention```
Returns a string that allows you to mention the given user.
that mentions the command author
That's it.
ik but he's raising the error after logging the error, they aren't unhandled
Help please!!!
@bot.command()
async def repeat(ctx, *args, amount = 1):
await ctx.channel.purge(limit = amount)
embed = discord.Embed(color = 0x177121, description = args)
await ctx.send(embed = embed)
If I write a command, for example, >repeat hi hello, then I get parentheses in the message (clearly visible on the screenshot). How to remove brackets?
I'm only handling 4 error types yes.
Because I don't have any more errors to handle.
can somone help me fix my slash command cooldown
.
@bot.command()
async def repeat(ctx, *, args: str, amount: int = 1):
await ctx.channel.purge(limit=amount)
embed = discord.Embed(color=0x177121, description=args)
await ctx.send(embed=embed)
Also this is called an echo not repeat, I'd be confused lol
Also just do ctx.message.delete()
!d str.join
Thanks
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
Why join if his * is just in the wrong place.
I was just answering his question?
In this case, yes args should be a kwarg, but if he wants to convert the tuple into a string he would use that, i may be incorrect in this context but i answered his question
Can anyone tell me why it only returns the name of the author of the message, and not the message as well
import discord
from discord.ext import commands
class Myclient(discord.Client):
async def on_ready(self):
print('Logged on as {0}'.format(self.user))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
client = Myclient(intents=discord.Intents.default())
client.run('token')
I already tried to change the intend to 'all'
Didn't work
class View(discord.ui.View):
def __init__(self, *, timeout: float = 3600.0):
super().__init__(timeout=timeout)
self.value = 0
self.cd = commands.CooldownMapping.from_cooldown(1.0, 2.0, key)
async def interaction_check(self, interaction: discord.Interaction):
retry_after = self.cd.update_rate_limit(interaction)
if retry_after:
raise ButtonOnCooldown(retry_after)
how can I stop my button from intefering with my test menu
@client.command()
async def test(ctx):
select = Select(options=[
discord.SelectOption(label="Cloudy", emoji=':cloud:', description='cloudy weather'),
discord.SelectOption(label="Rainy", description='rainy weather')
])
view = View()
view.add_item(select)
await ctx.send("test menus", view=view)
Did you enable the appropriate intents on the developer dashboard?
color=0xFFFF00
Hm?
Could you show the new code with all intents?
It's basically the same thing, what changes is that the bot doesn't even run
Errors?
That one
Are all 3 of the privledged intents enabled?
Just the last one
Make sure to enable all 3, then run your bot again with discord.Intents.all()
when a ticket is opened via ticket tool i want my bot to copy the id i send so i can add the person to the ticket, this is how far i came anything i can fix?
that's not the whole error traceback
there are examples on how to use wait_for in the docs
where
never said it was not
read the WHOLE error traceback
the dpy docs of wait_for
color=0xFF0
please someone help me 😭
What exactly is the problem you're having
😩
when i do ztest it sends the button to
instead of just the menu
Because your command sends the view
The view is the buttons
Don't send the buttons with view=view 
then what do I do?!!?!??!?!
Create the menu in the interaction instead of the button view? Remove the items from the view before sending it?
what
Show me what it does currently in discord
i dont want the button
view = View()
view.remove_item(View)
view.add_item(select)
await ctx.send("test menus", view=select)
i tried this but it doesnt work
wait
view = View()
view.remove_item(view)
view.add_item(select)
await ctx.send("test menus", view=view)
does the same thing
Show the entirety of your view code now
@client.command()
async def test(ctx):
select = Select(options=[
discord.SelectOption(label="Cloudy", emoji='☁️', description='cloudy weather'),
discord.SelectOption(label="Rainy", description='rainy weather')
])
view = View()
view.remove_item(view)
view.add_item(select)
await ctx.send("test menus", view=view)
That's not your view
Traceback (most recent call last):
File "/home/--/--/--/venv/lib/python3.10/site-packages/discord/client.py", line 627, in connect
await self.ws.poll_event()
File "/home/--/--/--/venv/lib/python3.10/site-packages/discord/gateway.py", line 645, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
``` Any idea what could cause this?
Docs link for reference: https://discord.com/developers/docs/topics/gateway#heartbeat-interval-example-heartbeat-ack
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Is that the whole traceback?
class View(discord.ui.View):
def __init__(self, *, timeout: float = 3600.0):
super().__init__(timeout=timeout)
self.value = 0
self.cd = commands.CooldownMapping.from_cooldown(1.0, 2.0, key)
async def interaction_check(self, interaction: discord.Interaction):
retry_after = self.cd.update_rate_limit(interaction)
if retry_after:
raise ButtonOnCooldown(retry_after)
return True
async def on_error(self, interaction: discord.Interaction, error: Exception,
item: discord.ui.Item):
if isinstance(error, ButtonOnCooldown):
seconds = int(error.retry_after)
unit = 'second' if seconds == 1 else 'seconds'
await interaction.response.send_message(f"Please wait {seconds} {unit}.",
ephmeral=True)
else:
await super().on_error(interaction, error, item)
@discord.ui.button(label='Create Support Channel Here',
style=discord.ButtonStyle.green)
async def count(self, interaction: discord.Interaction,
button: discord.ui.Button):
ticket = utils.get(interaction.guild.text_channels,
name=f"ticket-{interaction.user.id}")
if ticket is not None:
await interaction.response.send_message(
f"{interaction.user.mention} you already have a ticket open here {ticket.mention}.",
ephemeral=True)
Yup
1000 is an unkown error, is it persisting?
Hold up just don't send the view and instead send the select lol
It sometimes happens, I am unsure why that is
select = Select(options=[
discord.SelectOption(label="Cloudy", emoji='☁️', description='cloudy weather'),
discord.SelectOption(label="Rainy", description='rainy weather')
])
What platform are you running your code on?
Is it local?
Yes it is local (linux)
Hm. It might just be on Discord's end then
Maybe i have to open another issue then :sight:
Remove_item(count)
Instead of view
alr alr
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 1629, in test
view.remove_item(count)
NameError: name 'count' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'count' is not defined
view = View()
view.remove_item(count)
view.add_item(select)

