#discord-bots
1 messages · Page 270 of 1
author = user who runs the command
user = the user who is being referenced e.g you’re finding the info about a user in a whois command etc
@upbeat ice would this work?
sure as long as the sql is doing what you want it to do
yea alright
depends on your use case
wdym?
well what are you trying to do when the user enters info twice? Append it? Overwrite it?
I guess there is no difference
append
then you will want to check out the Update statement
but wouldn’t update overwrite it?
That's why I'm telling you to store the them with indexes not id
i don’t know what an index is
Like 1 2 3 4
oh
disnake is better or discord.py?
what do you mean store them in an index instead of id? could you elaborate
Depends on which u feel comfortable with
all good now, its fine
But one is better
I say if you learn it yourself disnake very easy
Like make the key value be the index and the user id or name and the answer be the secondary value
Nope none is better both have same features
Yeah the difficulty is the only difference
so data = {user.name, user.id}?
You say which one has more?
Yeah
I literally said both are same
you can use sql to grab the users previous data -> update it with the new data -> set it back
This works too
Disnake?
then
sql = "INSERT INTO … (column1, column2) VALUES (%s, %s)"
cursor.execute(sql, data)```?
i personally don't use it but i know some people who like it
How?
Same disnake better
Because Easy
Feature wise
@turbid condor yes?
A library being easy doesn't automatically make it better than others
Try and see I don't know much about SQL still have to learn it
okay
That is, disnake bad🗿
What sql?
Google it
discord.py has CommandTree, disnake doesn't. discord.py's extension, cog, loading stuff is now async, which means you can do asynchronous setup stuff, disnake doesn't
I'm sure there are many more things that are very different
Wait disnake doesn't have cogs?
heres an example i have done for my use case sql await self.bot.database.execute( "INSERT INTO playerschedules (campaign_id, player_id, schedule) " "VALUES ($1, $2, $3::JSONB) " "ON CONFLICT (campaign_id, player_id) DO UPDATE " "SET schedule = playerschedules.schedule || $3::JSONB", self.campaign_id, interaction.user.id, schedule_json, )
When did I say that?
Tree command mean slash command?
Any interaction commands
Nvm i read it wrong
There is a disnake cog
Welp we are in a useless convo I'm here cuz am bored and sleepy
And, of course, in the end it's all about your preference
How can I set intents.message_content = True inside this
class Bot(commands.Bot):
def __init__(self):
super().__init__(
#command_prefix="!",
command_prefix=config.prefix,
activity=config.starting_activity,
intents=discord.Intents.default(),
help_command=None
)
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
self.load_extension(f"cogs.{filename[:-3]}")
was looking at different ways people set things up
Just define intents outside of your class
Create a discord.Intent variable, then just set it
Or put message_content=True inside the brackets
!d discord.Intents.default
classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences"), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members"), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content "discord.Intents.message_content").
Doesn't accept arguments, so no
I remember someone doing it like this earlier today
And surprisingly it worked
I wouldn't be surprised if it actually didn't
Or it might have been an other lib
!e
Sel=['a','b','c']
X=','.join(Sel)
print(X)
@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.
a,b,c
sorry, its not in main.py
Like this
global variables
Wdym not in main so are you gonna import this class in main?
yes
.
def main():
bot = Bot()
TOKEN = os.environ.get("TOKEN")
#keep_alive()
bot.run(TOKEN)
if __name__=="__main__":
main()```
But I'm using embed where to put it
Oh
Alright
Define a variable outside of your class
Import discord
intents=....
class .....
@grand moss
And then inside your class do intents=intents
Should work
global variables can be referenced anywhere
super().__init__(
intents=intents)```
Nah just intents=intents should work
thanks, I don't see the message intent waring anymore
What did you do?

I already explained you this what you did not get
I did what you said
Show
And where are u sending them in embed?
I dont see sending embed part here
Tbh I'm confused shouldn't random.choice be an array?
Help mee
Why even use random.choices when you can do random.choice
I want him to choose
I will kill you
Instead of random.choices just do random.choice
That will randomly choose 1 option from Selelct1
Likepy random.choice(Select1)
Instead of choices
!e
import random
Sel=['a','b','c']
X=random.choice(Sel)
print(X)
@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.
b
its telling me to await main()
#from utils.keep_alive import keep_alive
from utils.bot import Bot
import os
async def main():
bot = await Bot()
TOKEN = os.environ.get("TOKEN")
#keep_alive()
bot.run(TOKEN)
if __name__=="__main__":
main()```
main~~ doesnt~~ shouldnt need to be async
and you dont need to await Bot()
import it and instantiate it
when inputting only 1 value into a db do i need VALUES (%s)?
thats more related to #databases for next time https://www.w3schools.com/sql/sql_insert.asp
@sick birch it appears your assistance is needed
See previous: #python-discussion message
It's not like that, it's
import asyncio
async def main():
...
asyncio.run(main())
oh thanks. I haven't use asyncio so far
And yeah the body of your function got no async stuff so you can just bring the code out from it
import os
from utils.bot import Bot
Bot().run(os.getenv("TOKEN"))
do you load the cog
If you think the event is not being called add a print("blah") at the top
then you will know and not think
ok but where
also is it discord.py?
And?
where is this code
Proper intents enabled?
...
how you make sure this code snippet is being run
Then it's not @commands.Cog.listener()...
where is that
im currently working on an economy bot and in my db im making a database table for power ups how is the best way to check if they have a power up as well as having all of them separately timed say it activates randomly for between an hour and 4 hours so i wanna set it so they have access to that power up for that time only i was thinking of using interval but im not getting my logic right here, any help is appreciated thank you im working with postgres here
It's @bot.listen or @bot.event considering you use bot and not some weird naming
but its in a cog isnt it
Then add logging
add this print after loading cogs : print(bot.cogs)
For example
after loading cogs
show it
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
No wonder if you have thousands of cogs 
did you put it inside for loop
my god what kind of bot is that
nevermind
it's just in the loop so always prints everything again and again
how is the cog named you have this code in
cog not file
you know what a cog is?
its a class
that is subclass of commands.Cog
show full code of this cog
Possible to add custom buttons to a bots profile? Like how a rich presence works or not?
no
not like dis?
like i said before no its not possible for bots
why not here?
no code no help 
i dont see anything wrong for now cog is loaded so i need to see code maybe you did something wrong here
hm really weird its defined correctly
do you have any other on_message event in your bot?
Bro you have 2 functions named on_message, only second takes effect
i did not see other one 
Yes way
the Cog.listener() should take name of an event
so you can name your function something other
☺️
Depends what kind of powerups, if each is unique and grants unique stuff you can have table with powerup ID and user ID it belongs to
yes, cool, but how can i set it for a specific amount of time
Uh how exactly the time works
thats what im trying to figure out
do i do like a timestamp or a interval or something
You mean like what
- Powerups can be used only in certain time in day, eg. from 4am to 1pm UTC
- Powerups can be used after interval passed since their acquirance
a power up has a duration
i understand it as powerups will be active for amount of time
yes
Ah okay so user activates it and then it expires
correct
What db you using?
postgres
Ah great, datetime management will be easier then
CREATE TABLE IF NOT EXISTS powerups (
user_id BIGINT NOT NULL,
powerup_id WHATEVER NOT NULL,
is_active BOOLEAN DEFAULT false NOT NULL,
expiration_time TIMESTAMP
)
This should be pretty much sufficient table for desired functionality
When user acquires powerup, just insert user id and powerup id, when they activate powerup, update is_active and expiration_time
what if they use more than 1 power up at time
Just stack them
If powerups of same type aren't allowed to be stacked just do unique key
UNIQUE (user_id, powerup_id)
should the timestamp be a timestamp with timezone tho? a utc one or no
Yeah there are several approaches you can use
- In python code, when checking for
is_activealso check forexpiration_time - Create loop and regularly run
DELETE FROM powerups WHERE expiration_time < CURRENT_TIMESTAMP - Create postgres rule that would essentially do the same thing as in 1 but on db level
It automatically manages timezones
You just need datetime.now() + timedelta(...)
oh okay nice idk why i use utc for other stuff probably because of discords weird timestamps
ive honestly never used postgres rules
MIght be bit complicated for begginers but are a useful thing
i think its the best approach however
and id use it how exactly? Just call it when they run the command
like
CREATE OR REPLACE RULE delete_expired_powerups
AS ON DELETE TO powerups
DO INSTEAD
DELETE FROM powerups WHERE expirationTime < CURRENT_TIMESTAMP;```
ive used it once before lol im not too skilled
CREATE TABLE IF NOT EXISTS powerupnames(name TEXT, powerupSerial SERIAL PRIMARY KEY);
CREATE TABLE IF NOT EXISTS powerups(userID BIGINT powerupID INT, isActive BOOLEAN DEFAULT FALSE, expirationTime TIMESTAMP, FOREIGN KEY (powerupID) REFERENCES powerupnames(powerupSerial));``` i think as for tables this is a sufficient enough setup
Sorry confused it with trigger, it's not a rule
Nevermind triggers aren't for selects
oh so what do i use
Uh sorry I lied ☺️ you can't do stuff on select, you can only filter it out with view, first way would be best most likely
ah okay so when they run the command i check if the time is over and if it is i delete
or i can jam it into my task loop for giveaways
if select.values[0] == "01":
category = discord.utils.get(guild.categories, name="CHECKING")
channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
elif select.values[0] == "02":
category = discord.utils.get(guild.category, name="SAVINGS")
channel = await guild.create_text_channel(f'{interaction.author.name}', category=category, overwrites=overwrites)```
Its saying guild object has no attribute category
but it literally does
where have you defined guild
guild = interaction.guild
role = discord.utils.get(guild.roles, name="Employee")
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.author: discord.PermissionOverwrite(view_channel=True),
role: discord.PermissionOverwrite(view_channel=True)
}
select = Select(options=[
discord.SelectOption(label="Checking Account", value="01", description="Talk to a representative about opening a checking account."),
discord.SelectOption(label="Savings Account", value="02", description="Talk to a representative about opening a savings account")
])
async def select_callback(interaction):
if select.values[0] == "01":
category = discord.utils.get(guild.categories, name="CHECKING")
channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
elif select.values[0] == "02":
category = discord.utils.get(guild.category, name="SAVINGS")
channel = await guild.create_text_channel(f'{interaction.author.name}', category=category, overwrites=overwrites)
select.callback = select_callback
view = View(timeout=None)
view.add_item(select)
await interaction.send(view=view)```
any reason why you are using guild.category and not guild.categories
oops
wait i am using guild.categories
wait no im not
it says interaction failed but its creating the channel how i want it to
@upbeat ice do you have any clue why
no errors either
guild = interaction.guild
role = discord.utils.get(guild.roles, name="Employee")
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.author: discord.PermissionOverwrite(view_channel=True),
role: discord.PermissionOverwrite(view_channel=True)
}
select = Select(options=[
discord.SelectOption(label="Checking Account", value="01", description="Talk to a representative about opening a checking account."),
discord.SelectOption(label="Savings Account", value="02", description="Talk to a representative about opening a savings account")
])
async def select_callback(interaction):
if select.values[0] == "01":
category = discord.utils.get(guild.categories, name="CHECKING")
channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
elif select.values[0] == "02":
category = discord.utils.get(guild.categories, name="SAVINGS")
channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
select.callback = select_callback
view = View(timeout=None)
view.add_item(select)
await interaction.send(view=view)```
Thats the code
i fixed it
does anyone know how to make a uploader bot?
i wanna make my bot upload stuff from yt tt etc
it does not
it's categories
yeah i figured that out
does anyone know the docs?
?
if you have code related to d.py we can help otherwise see #❓|how-to-get-help
did you resolve this?
yes
What’s wrong with this code
Is there a free anti-raid security bot code i could have for my bot?
seems like an environment error
why not code it yourself
i just dont have time anymore with hcoeky and was hoping someone would have a code
like i have 5 mins before i have to leve
no one is going to write it for you here
Hi guys, i need help for create a button open link for embed
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
!d discord.ButtonStyle.link
Represents a link button.
The error already said it, the module discord.client is not callable
You're probably looking for discord.Client, with capitalized C
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
every time my bot goes offline then back online, the selections and buttons stop working unless i re put them in
is there any way to prevent this cus its really irritating
that sucks
class Client(discord.ext.commands.bot.Bot)
| Method resolution order:
| Client
| discord.ext.commands.bot.Bot
| discord.ext.commands.bot.BotBase
-- More --```
does anyone know why this happened
what even is this
i dont know
Make them persistent
it just randomly started showing up
how do you do that?
what does the code look like
like when the bot starts up it automatically sets up?
this seems like a heavy handed approach to something thats not really a problem
def __init__(self):
super().__init__(command_prefix='.', intents=discord.Intents.all())
async def on_ready(self):
prfx = (Back.RED + Fore.BLACK + time.strftime('%H:%M:%S UTC', time.gmtime()))
print(prfx + ' Logged in as ' + Fore.LIGHTCYAN_EX + client.user.name)
print(prfx + " Python Version " + Fore.LIGHTCYAN_EX + str(platform.python_version()))
synced = await client.tree.sync()
guild = client.get_guild(1019500131747381249)
syncs = await client.tree.sync(guild=guild)
print(prfx + ' Slash CMDs synced '+ Fore.LIGHTCYAN_EX + str(len(synced)) + ' Commands')
print(prfx + ' Guild Only Slash CMDs synced '+ Fore.LIGHTCYAN_EX + str(len(syncs)) + ' Commands')
print(prfx + ' Current Discord Version '+ Fore.LIGHTCYAN_EX + str(discord.__version__))
print('Bot is online!!!')```
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.author: discord.PermissionOverwrite(view_channel=True),
role: discord.PermissionOverwrite(view_channel=True)
}
overwrites_loans = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.author: discord.PermissionOverwrite(view_channel=True),
role2: discord.PermissionOverwrite(view_channel=True)
}```
its not adding the author to the ticket
That's what would happen when you call the help function
nvm it works now
show the code where you are adding the author
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
you dont add the author anywhere
line 29
channel = await guild.create_text_channel(f'checking-{interaction.user.name}', category=category, overwrites=overwrites_accounts)
i added the overwrites
do you have the members intent?
yes
i have all intents
and no errors?
interaction.author: discord.PermissionOverwrite(view_channel=True) this should be interaction.user
i tried interactions.user but it said context object has no attribute user
even though the docs literally say interactions has an attribute user
are you trying to use slashcommands?
no
async def setupTicket(ctx):
embed = discord.Embed(color=cb_color, title='SUPPORT', description=ticket_desc)
embed.set_thumbnail(url=bot.user.display_avatar)
await ctx.send(embed=embed)
await ticket(ctx)
ctx.message.delete()```
thats the command to setup the ticket
Can you see what's wrong?
Context and interaction objects are not the same
its an interaction though
im using an interaction so idk why its saying context
either way though, its not adding the members to the ticket they created
Just because you name it interaction doesn't make it an interaction object
^
in your case it would be interaction.member
although you really should use ctx instead of interaction because that means something entirely different
yeah thats my fault but will ctx.member work?
im not entirely sure.. i almost never use context objects but let me look it up
looks like its ctx.author.name
Btw in your code u are using interaction.author whereas it should interaction.user
well interaction is ctx for him
its not an actualy interaction
its a context object
That's why you should name variables properly
so can you tell me how to fix???
Fix what
You can use this: https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#context and look for your attributes
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
role: discord.PermissionOverwrite(view_channel=True)
}
overwrites_loans = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
role2: discord.PermissionOverwrite(view_channel=True)
}```
its not adding the author
its meant to say author not user btw
Wait is that a Select option? Or does it listen the bot listen to reply
Cuz if it's a select menu shouldn't you be putting that in a View and then send it along your message?
he has a view - dont know what is in it though view = View(timeout=None)
Well in here he is not sending a view with the embed
dont you have to call .update() on perm overwrite?
!d discord.PermissionOverwrite
class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.
Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.
The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.
x == y Checks if two overwrites are equal.
x != y Checks if two overwrites are not equal.
iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
do you get any errors @torn solar
idk what to do with that
!paste
https://paste.pythondiscord.com/CFXQ
there is my code
well some of it
im using permission overwrite but its not working
first off change ctx.user to ctx.author
done
now if you get any errors that would be helpful
also interaction.user.name should be interaction.author.name
interaction.user.mention -> interaction.author.mention
well those actually work
cus they are actualy interactions
but i tried it out with author and it didnt work
no errors
ill try to ask chat gpt
why don't you try subclassing
instead of doing this nested function
subclass discord.ui.Select
and subclass discord.ui.View while you are at it
@torn solar
i dont know how to sub class
im just getting very pissed of at how this should work and it isnt
i have a pretty simple oauth discord app that all it does is when a user click in the login with discord it pops the thing for the user to allows the perms it makes a request to dicord api for the access token, now i have the user data and i want to join him to discord server how can i make it?
i was trying with something like this
response = requests.post(f'https://discord.com/api/v10/guilds/{guild_id}/members/{user_id}', headers=headers, json=data) print(response)
headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } data = { 'access_token': access_token, 'nick': current_user.username }
but it didnt work
is it possible for slash commands to include 2 words? something like /ticket create
Yes, and they're called subcommands
how can I do so?
"didnt work" is too vague for us to know what's going on (what error did you get?), but i can say that the get guild member endpoint doesn't take any json= parameter
https://discord.com/developers/docs/resources/guild#get-guild-member
(also this question would probably be more appropriate in the api thread #965291516031549500, though it hasnt seen much attention)
!d discord.app_commands.CommandTree.Group
No documentation found for the requested symbol.
thank you!
@naive briar one more question, I am currently using extensions, can I use it with @commands.hybrid_command()?
@hybrid_group(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_group "discord.ext.commands.hybrid_group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
@commands.hybrid_group()
async def ticket(interaction: discord.Interaction):
pass```
something like this?
Yeah
let me try
feels a bit weird for dpy groups to have several different syntaxes for using them but not having a single source describing them

@commands.hybrid_group()
async def minecraft(interaction: discord.Interaction):
pass
@minecraft.command(name="status", description="Gets the status of a Minecraft server.")
async def status(interaction: discord.Interaction, ip: str):
await interaction.response.defer()
await interaction.send(f"Server: {ip}")
async def setup(bot):
bot.add_command(minecraft)
Hybrid command raised an error: Command 'status' raised an exception: AttributeError: 'Context' object has no attribute 'response'
hybrid group takes a commands.Context the same as hybrid commands do
I am kinda confused about this subcommand thing
what should I add to hybrid_group?
the first argument should be ctx: commands.Context
Both
do I use ctx instead of interaction?
are you using a type checker in your editor?
yes I am using vsc
if its configured correctly it should give you warnings based on your definitions and typehints, like using the wrong variable
from what i can recall, there's a group instance: py ticket = app_commands.Group(name="ticket", description="...") @ticket.command(name="create") async def ticket_create(interaction): ... bot.tree.add_command(ticket) a group subclass: py class TicketGroup(app_commands.Group, name="ticket"): @app_commands.command() async def create(self, interaction): ... bot.tree.add_command(TicketGroup()) a group instance within a cog: py class TicketCog(commands.Cog): ticket = app_commands.Group(name="ticket", description="...") @ticket.command(name="create") async def ticket_create(self, interaction): ... await bot.add_cog(TicketCog()) and a group for an entire cog: py class TicketCog(commands.GroupCog, group_name="ticket"): @app_commands.command() async def create(self, interaction): ... await bot.add_cog(TicketCog()) first is not mentioned in docs, first and second require manual teardown in extensions (source code says otherwise for this actually), third one only has subtle hints to its possibility in Cog docs, and second and fourth use app_commands.command() inside the class which isnt demonstrated in docs...
i got 401
not autorized
im gonna pass to that other theard than
!paste
https://paste.pythondiscord.com/ZS3Q
Idk why but ive tried everything and it wont add the ticket creator to the ticket channel
ok nvm solved the issue thanks anyway ; )
so the channel is created but with the wrong overwrites, right? you should be defining your overwrites inside the callback where you know who's creating the ticket, i.e. interaction.user
I want to make a slash command named '/solitaire leaderboard' but it says that I can't use space bar in a command name. However, I have seen some commands which have a display name containing space bar inside. How can I make it?
see the discussion above about subcommands/groups
#discord-bots message
#discord-bots message
the exact name requirements are described in API docs too
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming
channel = interaction.channel
embed = discord.Embed(title="Closing Confirmation", color=cb_color, description="\nTo confirm closing this ticket, react with ✅. Otherwise react with ❌\n")
confirm_close = Button(label="✅ Confirm", style=discord.ButtonStyle.gray)
cancel_close = Button(label="❌ Cancel", style=discord.ButtonStyle.gray)
view = View(timeout=None)
view.add_item(confirm_close)
view.add_item(cancel_close)
message = await interaction.response.send_message(embed=embed, view=view)
async def confirm_callback(interaction):
await channel.delete()
async def cancel_callback(interaction):
await message.delete()
cancel_close.callback = cancel_callback
confirm_close.callback = confirm_callback```
For the `cancel_callback` function it says Nonetype has no attribute delete()
even though its a message, and it was working before but randomly stopped
interaction.response.send_message doesn't return the sent message
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
so what is it returning?
can i not delete it?
you would need to delete it by using Interaction.delete_original_response
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
could also get the InteractionMessage by Interaction.original_response
oh thx. Is it possible to add commands within a command group created in another file by cog?
yeah u have to get the command or the cog u need to acess the command object
Hmm I tried some methods like these but it seems not work (AttributeError: 'NoneType' object has no attribute 'app_command')
cog is None
Is there any tutorial about this?
I've been trying to make a custom help command using the default one and subclassing it, but cogs aren't showing as categories and the help command won't show up in servers for some reason yet works in dms. I'd also prefer to have it list the categories then go help category to get the commands in that category, but I'm unsure exactly how to do that.
!customhelp
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
Haven't made a discord bot for almost a year now, is disnake still superior? xD
Have it ever been?
every discord library is good if you know how to use it
anything is good if you know how to use it :P
Well discord bot libraries used to have pros and cons? For example disnake, pycord had slash commands while discord.py didn't natively.
now discord.py has everything built in
as well as all discord libraries
So basically every library is equal feature wise?
yeah
Alriight
i'd still recommend disnake today though
with discord.py, iirc you have to go through setting up a command tree yourself
depends, but you have to sync the tree
in nextcord or disnake its handled a bit different so you dont have to sync it
yeah
i like disnake because of how you can just @bot.slash_command and it makes one for you
its the same in nextcord though
use the raw discord API 🙏
i have yet to see a discord bot made in bash using curl for interacting with the API
https://github.com/fieu/discord.sh
its for webhooks only
Hi, ☺️ Anyone Can help me?
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**.
I used disnake
then check it's docs for knowing what to check for
Where to paste this?
wdym
doesn't matter
What does that have to do with anything
It is recommended to learn python before hopping to discord.py
Help before you make fun of people
verse
didn't make fun of noone
you won't start to run before you can stand up
I have just asked you where to paste this?
im looking for a value in one list, then once i have this value, i will use its index position to find a value in another list, however the code i have now gives me an index number that doesnt work and idk why
if "orange" in values:
position = order_details.index("orange")
print(position)
multiplier = amount[position]
print(multiplier)
price = multiplier * 6.95
total_price.append(price)
print(price)```
can you show amount and position lists
its not a set list, its what a user has inputted.
amount should be smthn like ["1:" 200, "2:" 400].. and position is the order contents with the values, [100, "orange", 200 "apple"]. I then use a function to get the numbers and put them into a separate list
because the size of each list could vary
and therefore i need to get the corresponding values
show whole code
Sounds like a job for a dictionary
first check if the role you are trying to give is lower than your bot role in hiearchy and also does the bot have permissons to give role
con,cur = openCON()
cur.execute(f"SELECT * FROM order_details WHERE userID = '{interaction.user.id}'")
i = cur.fetchall()[0]
order_details = i['order_contents']
values = str(order_details.split(","))
print(values)
amount = extract_numbers_with_order(values)
if "orange" in values:
position = order_details.index("orange")
print(position)
multiplier = amount[position]
print(multiplier)
price = multiplier * 6.95
total_price.append(price)
print(price)```
100/100 you right
Fixed Thank you man
Some people who don't know anything tell me to learn python first
(you where asking where to paste a method)
Fix your mistake first and then mine
which mistake?
@thin raft
what's extract_numbers_with_order?
Love these conversation
def extract_numbers_with_order(input_string):
pattern = r'\d+'
numbers = re.findall(pattern, input_string)
numbers_with_order = {}
for i, num in enumerate(numbers, start=1):
numbers_with_order[i] = int(num)
return numbers_with_order```
gets all the numbers
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@client.event
async def on_raw_reaction_remove(reaction):
if reaction.channel_id == 1129756575175819324:
verified_role = get(reaction.member.guild.roles,name="Melon seedlings")
await reaction.member.remove_roles(verified_role)
``` can anyone tell me why its telling me that "nonetype" object has no attribute `guild`
so basically, a user will input their order into a modal. these values get stored in a database. then they can see the cost of their order. so to get the amount of each item i am extracting the numbers, however i dont know which item correspons to which amount. therefore i am looking through the data in the db ad=nd checking if "orange" is in the contents. then i was index this list to find the position and i can then use this position to find the amount of the oranges in the other list. once i have the amount i can multiply it by the price
Whether guild member related events are enabled.
This corresponds to the following events...
me?
yeah
uh yeah i have members intent enabled
can you print position and amount
in dev portal and in code?
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
intents.members = True?
yup
if i input an order of 100 oranges and 20 apples, the amount is [100, 20] and the position is 5
oh alr tnx:)
and order_details?
['100', ' oranges', ' 20', ' apples']
@thin raft still throwing me that error
use a dict
!d discord.RawReactionActionEvent.member
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
why
Why do you use ints when wanting to do number operations?
int is for integer right?
yeah
thays why
im asking why would you use ints and not lists for example
if you want to add one and two
uhh
what would i do with member then?
im not sure
let's get to the point then
each data type has it's own usecase
in your case a dict would be suited better
how would i use a dict here?
!e
amounts = {
"oranges": 100,
"apples": 5
}
for fruit, amount in amounts.items():
print(fruit, amount)
@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | oranges 100
002 | apples 5
se how easier it is?
oh yea that is easier
Can you show the structure from your table
my db table?
yeah
?
can you show current code
..
the values are just random stuff i inputted
whole code after changing intents
why don't you use more than one table
i dont see the need
orders(id INTEGER, user INTEGER)
items(order_id INTEGER, item STRING, amount INTEGER)
also howd i insert a dict into a db
use another table
import discord
from discord.utils import get
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print("online")
@client.event
async def on_raw_reaction_add(reaction):
if reaction.channel_id == 1129756575175819324:
if str(reaction.emoji) == "🍉":
verified_role = get(reaction.member.guild.roles,name="Melon seedlings")
await reaction.member.add_roles(verified_role)
@client.event
async def on_raw_reaction_remove(reaction):
if reaction.channel_id == 1129756575175819324:
verified_role = get(reaction.member.guild.roles,name="Melon seedlings")
await reaction.member.remove_roles(verified_role)```
can you do a print(reaction.guild.members)
everything is possible, just not recommended tho
ill stick with lists for now then swtch later
AttributeError
do u know why this wont work?
What?
Called it
any ideas?
what is event?
the rawreactionevent?
yeah
There's no orange element in your list that you sent
But there's orange, with a whitespace infront of it for some reason
where do i put it then?
yea i got rid of that
Actually oranges with an s
Right
Yeah then maybe actually give your code and not some nonsense
Because then it leads to such responses and you giving not even working code
it would work the same either way
@thin raft
in the event
@client.event
async def on_raw_reaction_remove(reaction):
if reaction.channel_id == 1129756575175819324:
verified_role = get(client.get_guild(reaction.guild_id).members.guild.roles,name="Melon seedlings")
await reaction.member.remove_roles(verified_role)
like this?
No
You already have the guild that is returned by the get_guild method
Why would you need members.guild
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.
What does this embed say
only on reaction_add
The member attribute will always be None if you try to get it from a payload you get from the on_raw_reaction_remove event
what do i do then?
Try to get the member from somewhere else?
@thin raft i found out why it’s bugging
it’s not giving me the index it’s giving me the number of characters before the value that i want
and idk why
but i want the user's role that unreacted be removed
How do I make groups for commands in main.py by discord.py and use them in different cogs?
how can I use choices in slash?
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
thank you
i guess in theory this might be possible, but i cant imagine discord.py natively supports it so its likely impractical to write - why are you looking for this instead of defining your groups inside their cogs?
what method can I use to define "Choice"?
the docs are referring to the app_commands.Choice class
is this the correct way of doing so?
gamemode would receive int, so gamemode.name isnt valid
so only int?
cause it is not showing suggestions
@commands.hybrid_command(name="plancke", description="Says hello!")
@app_commands.describe(gamemode='Choose a Hypixel gamemode')
@app_commands.choices(gamemode=[
discord.app_commands.Choice(name='Hypixel Level', value=1),
discord.app_commands.Choice(name='Super Smash', value=2),
discord.app_commands.Choice(name='Blitz', value=3),
])
async def plancke(interaction: discord.Interaction, gamemode: int, ign: str):
await interaction.defer(ephemeral=False)
await interaction.send(f'{gamemode.name}')```
ya, also the interaction.defer/send methods dont exist in discord.py and should be replaced with interaction.response.defer() / interaction.followup.send() respectively (or interaction.response.send_message() if you decide to remove the defer)
I am using hybrid.command, if I don't do that it errors out
oh right, in that case your first argument should have been typehinted with commands.Context
intraction: commands.Context?
id suggest clicking the curly braces on the bottom right of vscode to turn on type checking, you'll get a lot more helpful warnings that way (though only if you write your typehints correctly)
probably a wise idea to rename the parameter to ctx so we dont confuse it with discord.Interaction
alright
that seemed to work, thank you!
oh its hypixel stats bot
its just a lot of random stuff mashed together tbh
i see
@hushed galleon hello, sorry for the mentions, how can I access the name in discord.app_commands.Choice(name='Hypixel Level', value=1),?
you could set the value to the same thing as the name, but the Literal syntax suggested in docs is likely more appropriate for your use case
e.g. gamemode: typing.Literal["Hypixel Level", ...], which would replace your choices() decorator
do you suggest Literal?
Hey! is there an up to date guides on how to add and use cogs, my discord code being in 1 file is an absolute mess.
I have tried to find a tutorial but have had no luck.
Any help is greatly appreciated.
what would the file name be for a cog?
doesnt matter
- dont share your bot token
- how is it supposed to know what testcog is
import it or use setup functions
why you do Intents.all() and then still enable some
also bot.add_cog is awaitable if you use discord.py
why does it say the file doesent exist when im sure it exists
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: './logfile.txt'
lient = commands.Bot(command_prefix='.', intents=discord.Intents.all())
@client.command()
async def hello(ctx):
ctx.send("Bonsoir, here are your logs. \\/")
ctx.send(discord.File(r'logfile.txt'))
with open('logfile.txt', 'w') as dalog:
dalog.write("")
client.run('no token for u')
Show file tree and from where you try to Access it
how can i get the time an embed was sent within a button class?
property created_at```
The message’s creation time in UTC.
yea
but how’d i use message within a button class
what you mean by that?
so when a user clicks a button it send and embed and i want the embed to contain the time the message was sent
you talking about embed timestamp?
yes
!d discord.Embed
You would just send the current time in the embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
pass timestamp kwarg^
ok ty
I believe embed timestamps adjust themselves to the viewer's timezone (?)
yes
!d discord.Embed.timestamp
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
channel = interaction.channel
embed = discord.Embed(title="Closing Confirmation", color=cb_color, description="\nTo confirm closing this ticket, react with ✅. Otherwise react with ❌\n")
embed.set_footer(text="Requested by " + interaction.user.name)
confirm_close = Button(label="✅ Confirm", style=discord.ButtonStyle.gray)
cancel_close = Button(label="❌ Cancel", style=discord.ButtonStyle.gray)
view = View(timeout=None)
view.add_item(confirm_close)
view.add_item(cancel_close)
message = await interaction.response.send_message(embed=embed, view=view)
async def confirm_callback(interaction):
await channel.delete()
async def cancel_callback(interaction):
await message.delete_original_response()
cancel_close.callback = cancel_callback
confirm_close.callback = confirm_callback```
The cancel_callback isnt working, it says Nonetype has no attribute delete_originial_response()
I need help
like rn... its really easy tho
I need to make my bot say a message.author.user
?
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
im trying to make an embed
embed=discord.Embed(title=f"{message.author.user} etc", descirption="etc", color=discord.Color.purple())```
its not working tho
what exactly do you want the title to do
there is no author.user
you could do message.author.name or message.user.display_name
You can't put mentions in a embed title AFAIK
i thought it just didnt ping
not a mention
just his user
also can I do for the discord.Color.a_hex_code
hey guys
message.author.display_name or message.author.name, as Brandon said.
No. Only RGB and the named colors they have.
ok
embed=discord.Embed(title=f"{message.author.name} etc", descirption="etc", color=discord.Color.purple())```
would this work?
try it
description is spelled wrong.
Well, you can now, for a long time ago
My knowledge about Discord is apparently outdated, then.
how do I make him ping the user in the content
await message.channel.send(content=f"@{message.author.id}", embed=embed)```
use mention
message.author.mention, as said above.
last question... how do I make it add a role to a user when they send a message
!d discord.Member.add_role
No documentation found for the requested symbol.
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
There we are
how could i remove a role from a user that removed a reaction on on_raw_reaction_removed?
async def on_raw_reaction_remove(reaction):
if reaction.channel_id == 1129756575175819324:
verified_role = get(client.get_guild(reaction.guild_id).roles,name="Melon seedlings")
i have this but idk how to get the user that removed the role
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
check there for the attributes of your reaction parameter
anyone knows the docs for the slash commands in discord.py?
never give up
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
How would you make it that any arguments passed to the bot or if the bot is in a command parameter (E.g Send_Money) it just returns the commands without the command going through
how do i disable a dropdown menu after it has been interacted with?
It depends on your preference, but my bias says discord.py
any idea how I can mention such commands in normal messages aswell as in embeds??
You mean slash command (</uwu:0>) mention?
</tag:1079848585027399791>
how did you omg
just mention it
wdym just mention them in the message content
</slashname:id>
like @ them?
use their id
@timber wren
nooo
i am not talking about that bruh
i am talking about mentioning slash commands
but how do I get the id of the slash command?
yeah well maybe if ur original message was readable english i wouldve understood
Also there is a property that can do that for you (if you do that with your bot's slash command)
!d discord.app_commands.AppCommand.mention
property mention```
Returns a string that allows you to mention the given AppCommand.
he didnt mean that

ooo
he did
are u ok?
yea i did
</tag:1079848585027399791>
</tag:1079848585027399791>
i clearly said "mention commands"
"mention such commands"
banned in google 
https://github.com/Rapptz/discord.py
oh you mean like /alert
nvm @distant python i got it
hey uh @buoyant quail can I
slash_command.mention(name = name)
i dont- think it is working that way
kinda confused in here
Actually i don't see how do you retrieve AppCommand object in dpy, i see only just Command which has no needed attrs
Use mention by id
counter = 0
@client.tree.command(name="counter", description="count up using a button")
async def counter(interaction: discord.Interaction):
countbutton = Button(label="count", style=discord.ButtonStyle.primary)
view = View()
view.add_item(countbutton)
global counter
counter = 0
await interaction.response.send_message(f"{counter}", view=view)
async def button_callback(interaction):
global counter
counter += 1
response = await interaction.original_response()
await response.edit(content=f"{counter}", view=view)
countbutton.callback = button_callback
``` im making a button that everytime you press the number goes up
but I get this error
```Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 89, in button_callback
response = await interaction.original_response()
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/interactions.py", line 397, in original_response
data = await adapter.get_original_interaction_response(
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
You didn't respond anything, so there is no original response
You want interaction.message maybe
ok I fixed it it had to be in the command function and not the button function but every time its clicked it says the interaction failed even though it worked
counter = 0
@client.tree.command(name="counter", description="count up using a button")
async def counter(interaction: discord.Interaction):
countbutton = Button(label="count", style=discord.ButtonStyle.primary)
view = View()
view.add_item(countbutton)
global counter
counter = 0
await interaction.response.send_message(f"{counter}", view=view)
response = await interaction.original_response()
async def button_callback(interaction):
global counter
counter += 1
await response.edit(content=f"{counter}", view=view)
countbutton.callback = button_callback
Because editing some message is not a response to interaction
You can defer it if you don't want to send anything
ok
!d discord.InteractionResponse.edit_message 🐈
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
it sends a web request when interacted with, so still a response
i have a selection menu, how can i disable it in the callback?
update it with disabled to True
!d discord.ui.Select.disabled
property disabled```
Whether the select is disabled or not.
i tried self.disabled = True then await interaction.response.edit_message(view=self)
but it didnt work
code?
in callback you already get the select object
unless you are not using decorators
async def callback(self, interaction: Interaction):
giveaway_json["boosted_roles"] = self.values
self.disabled = True
await interaction.response.edit_message(view=self)
this is my code
in the ui.Select class
i belive you are using wrong method to edit the message
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
ill try this
payload["components"] = view.to_components()
AttributeError: 'PERCENTAGE_DD' object has no attribute 'to_components'
still the same error
ui.Select class!? You can't directly pass that into the view argument
You need to put it in a view first
!d itertools.combinations
itertools.combinations(iterable, r)```
Return *r* length subsequences of elements from the input *iterable*.
The combination tuples are emitted in lexicographic ordering according to the order of the input *iterable*. So, if the input *iterable* is sorted, the output tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeated values in each combination.
Roughly equivalent to:
!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.
await delete(embed..)?
Edit the message and set the embeds argument to an empty list
I used to do that, not sure if it still works
uh
i was gonna do m = await message.reply(embed=suc_embed, view=order())
then
await m.delete() in the button class but i cant access m
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
What
would it be await delete_original_response() or await delete_original_message()
Are you not using discord.py? Because that's a weird question since I just wrote delete_original_response
damn right
i get an Unkown Webhook error
!traceback and your code
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.
hint: don't use global variables
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Administrator\Desktop\alon_order\main.py", line 1513, in button_callback2
await interaction.delete_original_response()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 506, in delete_original_response
await func
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
```py
class continue_order(discord.ui.View): # interaction_1st, main ticket button
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Proceed", style=discord.ButtonStyle.green, custom_id="continue_order2")
async def button_callback1(self, button, interaction:discord.Interaction):
for child in self.children:
child.disabled = True
@discord.ui.button(label="Redo ", style=discord.ButtonStyle.red, custom_id="continue_order3")
async def button_callback2(self, button, interaction:discord.Interaction):
for child in self.children:
child.disabled = True
await interaction.delete_original_response()```
Is it intentional that you're calling the interaction.delete_original_response in the loop?
You can only call it once since it will delete the message that the component (view) is attached to
oh shoot its in the loop
thats unintentional
ok i mved it out the loop and still get the same error
Are you sure it's the same?
same what?
As the previous error you sent
await interaction.message.delete() works \
yay that did, tysm
how to disable allow command from pm(DM) ? i tried this one but failed ,
,
if (message.author == bot.user) and (str(message.guild) == "None"):
return
else:
await bot.process_commands(message)
this one also not working
message.guild is None
What do you mean by not working
Can you show your code
@bot.event
async def on_message(message):
if (message.author == bot.user) and (str(message.guild) == "None"):
return
else:
await bot.process_commands(message)
This could be caused by the first condition and the and statement
Why would you even need to convert it to string and check if it matches "None"
Since even if the member.guild is None, if the message author isn't the bot, the and statement will make your conditions ends in False
i tried to check is it problem of string, because it returns as None but is it None none or string none
message.guild is None
!d or - try this instead of and
6.11. Boolean operations
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.
The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
does python works diffrent 😮 i didnt know it , i thought its double check
What works different
in js or php and works as double check
if X returns true checks Y if its true too it executes
yes. that's what and 'does'
!e
print(False and False)
print(False and True)
print(True and True)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | False
003 | True
oke more simple question how to disable DM commands 🙂
nvm i changed my code
elif message.guild is not None:
await bot.process_commands(message)
!d discord.ext.commands.guild_only Also exists if you only want this for specific commands
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
👍
Do I need to reset the color back to the default?
async def on_ready(self):
total_members = sum([guild.member_count for guild in client.guilds])
print('\u001b[31m' + f'Logged in as: {client.user} (ID: {client.user.id})' + '\u001b[0m')
print('\u001b[31m' + f'Connected to {len(client.guilds)} servers' + '\u001b[0m')
print('\u001b[31m' + f'Serving {total_members} members' + '\u001b[0m')
print('\u001b[32m' + 'Bot is ready!' + '\u001b[0m')
print('\u001b[31m' + '------------------------------' + '\u001b[0m')```
What a pronouns

why not use colorama?
What is that?
!pypi colorama
i am trying to get command names and descriptions , but when i parse name into description it gives error , when i type manually it works..
My Code :
for command in self.bot.commands:
pkt = str(command).strip()
print(pkt)
print(self.bot.get_command(pkt).description)
#Gives Error because get_command says its None but its not actually
Working One:
print(self.bot.get_command("ping").description)
Does anyone knows what is wrong 🤔 There is not enough info about custom help commands (which is im trying to do) in API
What does print(pkt) output?
my commands
2023-07-16 23:15:00 INFO loggers Got command help from bybatu in bot
help
update
laws
status
mod
restart
ping
Why do you need to use bot.get_command in the for loop anyway? You already have it in the form of command
You can also just do command.description
it gives error on that , i dunno why
What error?
hold on let me show output
well 🤔 it worked now probably i did some typing errors
Shows the bot's latency.
Shows list of commands
Update the law and map.
Shows recent laws
Shows the status of the services working on background
Add a mod to the bot
@sick birch thaanks
Nice!
anyone here using replit?, how do I import a file(.py) from a different folder?
nvm got it
anyone knows the doc link for the discord.py buttons?
for slash commands?
https://discord-py-slash-command.readthedocs.io/en/latest/ here’s interactions as a whole
thanks
@copper gulch you don't need to use that, discord.py has built in support for slash commands and buttons
Here's a basic slash command example
And here's a basic button example
thank you thank you
channel = interaction.channel
embed = discord.Embed(title="Closing Confirmation", color=cb_color, description="\nTo confirm closing this ticket, react with ✅. Otherwise react with ❌\n")
embed.set_footer(text="Requested by " + interaction.user.name)
confirm_close = Button(label="✅ Confirm", style=discord.ButtonStyle.gray)
cancel_close = Button(label="❌ Cancel", style=discord.ButtonStyle.gray)
view = View(timeout=None)
view.add_item(confirm_close)
view.add_item(cancel_close)
message = await interaction.response.send_message(embed=embed, view=view)
async def confirm_callback(interaction):
await channel.delete()
async def cancel_callback(interaction):
await message.delete_original_response()
cancel_close.callback = cancel_callback
confirm_close.callback = confirm_callback```
The cancel_callback isnt working, it says Nonetype has no attribute delete_originial_response()
hello
i am am making a discord AI using GPT-3 model. i have install required packages but i can't install PyTorch in replit. GPT-3 requires the PyTorch package.
can anyone help me to solve the error?
Repl : https://replit.com/join/ebaqwyjfxm-anlexalphast
Heyo, a while ago, when I would do cntrl^C on my discord bot, it would stop immediately. I started using Botbase from pydis_core and a couple of other things, and now it takes a while for the program to terminate. Any ideas why?
@discord.ui.select(label="Checking Account", value="01", description="Talk to a representative about what a checking account offers.", custom_id="ticket_checking")
It says select got an unexpected keyword argument 'label'
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
cause select does not have label
yeah im dumb
The select.values doesn't return the selected options' label, but their values
It's in the attribute's name
so use the value and not the label?
Yes??
ok sorry some stack overflow post used the label same way i was
also @naive briar while your here since your so much help
why does it say interaction failed when it worked?
async def on_member_join(member):
guild = member.guild
role = discord.utils.get(guild.roles, name="Customer")
await member.add_roles(roles=role)```
does anyone know why it isnt giving the member the role?
Dont pass it as keyword
messages support hyperlink now, that's cool
how are you using hyperlinks
thought only bots can do it
the new discord markdown feature allows normal users to do so
its rolling out slowly*
how to edit haidisql in table CREATE code:
And I want to put this:
CREATE TABLE bans (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(255),
username VARCHAR(255)
);
@slow fog
i don't know anything about "haidisql"
And do you know how to connect to ban command to save information ?
#databases is more suitable place for this question
It's apparently called HeidiSQL and is a software for db management
When asking there make sure to specify what database you use
@languid wagon :white_check_mark: Your 3.11 eval job has completed with return code 0.
DiscordFlag.HOUSE_BALANCE, DiscordFlag.ACTIVE_DEVELOPER
async def ticket_callback(interaction):
guild = interaction.guild
Moderator_role = guild.get_role(config.MODERATOR_ROLE)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
Moderator_role: discord.PermissionOverwrite(view_channel=True)
}
minecraftemojiID = "1127972711193391267"
discordemojiid = "1127973464179998780"
discordemoji = await interaction.guild.fetch_emoji(discordemojiid)
minecraftemoji = await interaction.guild.fetch_emoji(minecraftemojiID)
selectmenu = ui.Select(placeholder="Select a platform", options=[
discord.SelectOption(
label= "Minecraft",
value="01",
emoji = minecraftemoji
),
discord.SelectOption(
label= "Discord",
value="02",
emoji = discordemoji
)
])
view = ui.View(timeout=None)
view.add_item(selectmenu)
await interaction.response.send_message("Select a platform", view=view)
async def selectmenu_callback(interaction):
if selectmenu.values[0] == "01":
category = discord.utils.get(guild.categories, id=1130129162489827389)
channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}", category=category, overwrites=overwrites)
await interaction.response.send_message("Opened a ticket", ephemeral=True)
selectmenu.callback = selectmenu_callback```
When i select the minecraft select option, it says the "opened ticket" message but it isn't creating the channel
where's the problem???
Is it possible to get the python discord bot @unkempt canyon to my own server?
!d discord.Guild.fetch_emoji
await fetch_emoji(emoji_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") from the guild.
Note
This method is an API call. For general usage, consider iterating over [`emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.emojis "discord.Guild.emojis") instead.
Changed in version 2.0: `emoji_id` parameter is now positional-only.
emoji works
look at the docs (especially at the types)
._.
weird cause shouldnt be
yes, the source code is available
but a lot of the features are designed specifically for this server
why
!src
so i can just copy the whole source code and make my own python discord bot?
i used interaction.guild.fetch_emoji()
yeah but you'd have to change a lot of stuff to make it work properly for your server
but you pass string not int to it
okay ty
so its not creating the channel?
I passed the id
no
but as a string..
did you check if the if ... was True?
if selectmenu.values[0] == "01": this one
snowflakes can be given in strings right?
wdym
the emoji_id param is not of type Snowflake
oh
what if the if was False
then everything under it is not ran
so the channel is not created


