#discord-bots
1 messages · Page 329 of 1
disnake
already went with disnake, but thanks for the ping 
Which embed do you think looks better for a user interface
2nd
ty
how do i get the embedded images in the button callback?
for src in results:
emb=discord.Embed(title=f"cats", url=link,
description="catto", color=0x00ff00, timestamp=datetime.datetime.now())
emb.set_author(name=interaction.user.name, icon_url=interaction.user.display_avatar)
emb.set_footer(text=catFact)
emb.set_image(url=src)
embed_list.append(emb)
await DUMP_CHANNEL.send(embeds=embed_list, view=PosNegView())
get the message from the callback and get the embeds, then you can get the image
The message that sent this interaction.
This is only available for InteractionType.component interactions.
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
property image```
Returns an `EmbedProxy` denoting the image contents.
Possible attributes you can access are...
Possible attributes you can access are:
urlproxy_urlwidthheight
got it
thanks for your help
for emb in interaction.message.embeds:
print(emb.image.url)
How to setup wealcomer
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
What part of my syntax did i screw up here?
...
async def on_timeout(self) -> None:
await self.message.channel.send("Timed ouuuuut")
await self.disable_all_items()
...
@bot.command()
async def clicky(ctx):
buttony = BinaryChoice(timeout= 30)
message = await ctx.send(view=buttony)
buttony.message = message
I'm attempting to timeout the View() and I thought i had it correct?
https://paste.pythondiscord.com/ULYQ
Why does this code produce failed interaction sometimes?
d!interaction
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
Whenver I select a option, it mostly fails.
Is it not 100% failure? And are you doing the same actions each time to replicate it?
Like, I dunno much, just seeing what you're tried
It's not 100% failure sometimes, it works.
🤔
sometimes it works, but most of the time it doesn't.
At what line does it fail?
Do you get an error code?
line 90
it says that
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\USER\Desktop\Programming\service\cogs\tickets.py", line 229, in service_type
await interaction.response.send_message(f"Ticket created in <#{channel.id}>", ephemeral=True)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 801, in send_message
await adapter.create_interaction_response(
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\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
You have to respond to an interaction within 3 seconds
If you use discord.InteractionResponse.defer() you’ll have 15 minutes
Where did you catch that? Not my error, but curious
Written in the documentation.
The error can be caused by a few reasons, but it’s usually not responding fast enough. That error, plus the just overall large amount of operations done before responding brought me there
If you’re talking about the 3 second restriction it’s up to discord and can be viewed in their documentation
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\USER\Desktop\Programming\service\cogs\tickets.py", line 230, in service_type
await discord.InteractionResponse.defer(f"Ticket created in <#{channel.id}>", ephemeral=True)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 638, in defer
if self._response_type:
AttributeError: 'str' object has no attribute '_response_type'
@final iron
You need an instance of InteractionResponse
discord.Interaction.response will return the instance
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
like this?
await discord.InteractionResponse.defer(interaction.followup.send_message(f"Ticket created in <#{channel.id}>"), ephemeral=True)
huh

This returns the InteractionResponse instance
you call defer on an instance of InteractionResponse, not the class itself
I don't understand, would an example be possible?
await interaction.response.defer() to defer the interaction
await interaction.followup.send("hello") to send a followup message
ohh okay, thank you
interaction.response gives you an instance of discord.InteractionResponse, so you can use the .defer() method on that
Defer only works for application commands, this is a prefix command.
how do you have an interaction object if this is a prefix command 
oh wait it's a hybrid command
await defer(*, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction based contexts.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
If this isn’t an interaction based context then it does nothing.
ctx won't work, I'm using interaction for select menus.
huh
You always get an interaction object for select menus
No matter how they’re invoked
Yeah ik that, ctx object won't work.
And why cant you defer with the InteractionResponse object?
Off topic, what’s the advantage to using pycord or other discord bot libraries?
||The fix is to not use hybrid commands||
Why did you spoiler that?lol
It's personal preference really, most libraries are forks of discord.py
I don't think pycord has a very good reputation
async def createChannel(interaction,client,attackingFaction,defendingFaction,mainguild=ID):
guild = client.get_guild(mainguild)
category = guild.get_channel(ChannelID)
length = len(category.text_channels)
print(length)
channel = await guild.create_text_channel("Test 4", category=category, position=length)
Whilst creating the text channel i pass the position (last), yet it fails to put it into position
position (int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
since its starting at 0 you need to subtract 1 from the length
ah true
forgot that quirk
same thing
does it work when you try to place it for example at second position?
since it doesnt place it last where does it
first
and how many text channels are there in this category
currently 2
and what is the value of length
2
nope
async def createChannel(interaction,client,attackingFaction,defendingFaction,mainguild=):
guild = client.get_guild(mainguild)
category = guild.get_channel()
length = len(category.text_channels)
print(length)
channel = await guild.create_text_channel("Test 4", category=category, position=length)
you still dont subtract 1 do you
i have tried with it
async def createChannel(interaction,client,attackingFaction,defendingFaction,mainguild=):
guild = client.get_guild(mainguild)
category = guild.get_channel()
length = len(category.text_channels)
channel = await guild.create_text_channel("Test 4", category=category)
channel.position = length
This works, just have to do it seperated
weird
How do you send the message
And you're missing an f for your f-string fyi
_ _
OH
And you need to send the file as well when sending the embed
e.g.
await channel.send(file=file, embed=embed)
i did what you said
but the problem is now
the msg wont send for some reason 😭
Likely have some error(s)
e.g. the part at get_channel
If the channel is not in cache it can't be used as it will return None
So you'd have to do something like
channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)
Which will first try to get the channel from the cache and if it will return None it makes an API call with fetch_channel
Example:
!e
print(None or 5)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
5
LOVE YOU BRO
I HAD THIS ISSUE FOR SO LONG
❤️

hi guys i have a question
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.reactions = True # Enable reaction events
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
starboard_channel_id = 1187079412395556896 # Replace with your starboard channel ID
@bot.event
async def on_ready():
await bot.wait_until_ready()
print(f'Logged in as {bot.user.name}')
@bot.event
async def on_reaction_add(reaction, user):
if reaction.emoji == '⭐️' and not user.bot:
channel = reaction.message.channel
starboard_channel = bot.get_channel(starboard_channel_id)
if isinstance(starboard_channel, discord.TextChannel):
starred_message = reaction.message
# Check if the message is already in the starboard channel
starboard_message = await starboard_channel.fetch_message(starred_message.id)
if starboard_message is None:
# Create a new message in the starboard channel
starboard_message = await starboard_channel.send(f'**{reaction.count} ⭐️**\n{starred_message.content}')
else:
# Update the star count
await starboard_message.edit(content=f'**{reaction.count} ⭐️**\n{starred_message.content}')
@bot.event
async def on_message_delete(message):
# Remove from starboard when the original message is deleted
starboard_channel = bot.get_channel(starboard_channel_id)
if isinstance(starboard_channel, discord.TextChannel):
try:
starboard_message = await starboard_channel.fetch_message(message.id)
await starboard_message.delete()
except discord.NotFound:
pass
# Run the bot with your token
bot.run(os.environ['TOKEN'])
i wrote this bot that has a starboard system just like dyno bot. I’m running the bot on replit mobile. There’s nothing wrong with the code i guess but when i run the bot
it doesn’t work. first it says the token on the bot might be expired but it isnt cause i have reset it 5 times and updated the token in the code. i was thinking it also could be the that are some missing intents in the code or some. but i have authorized and enabled all intents in the bot in the developer site
.
if possible can someone help me finding where the issue is? again im running the bot on replit and it’s not always online but i dont think that’s an issue. i also have copied the channels id and have granted the bot permission to talk in the channel
can you send the traceback?
yes just a second
Why is that?
They steal code without credit, one of the least used forks, terrible implementations etc
Oh, that’s a huge problem and 100% a reason not to support their code
Question how do I add options to hybrid slash commands?
Typehint the argument with typing.Literal or create an Enum
Is there a way to add to it via the commands?
huh
Like for example the list I am trying to do is based of the commands available in the bot
I dont wanna write it manually so is there a way to make it add the list automatically
Take it like this
Probably not with hybrid commands
There are 3 commands, help, botinfo, and serverinfo
Enums are generally immutable
so I have to do manually ig
Or don't use a hybrid command for this
well the thing tbh is I want it to be prefix and slash command compatible for most commands
You can still do that...
seperately or via hybrids?
You can just create 1 prefix command, and 1 slash command
oh it wont interfere?
I thought it would say that the comand already exists
Is there a reason why it would not be in cache? Can you give me an example?
Not all items are given by discord on startup.
How do I escape the error, Interaction has already responded before
async def callback(self, interaction: discord.Interaction):
self.disabled = True
await interaction.response.send_message(
embed=CreateEmbed(title='Отправляю отзыв...'),
ephemeral=True
)
user_id = await db.select_user(session, interaction.channel.id)
user = interaction.guild.get_member(user_id)
feedback_roles = [interaction.guild.get_role(role_id) for role_id in await db.select_roles_feedback(session)]
for role in feedback_roles:
await user.add_roles(role)
await user.send(text.get_message(self.lang, 'dm', 'feedback').format(await db.select_feedback_channel(session)))
await interaction.response.edit_message(embed=CreateEmbed(title='Напоминание об отзыве было отправлено!'))
await log.send_log(interaction, 'feedback')
self.disabled = False
dont respond to it twice lol
how do i edit then
!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) 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.
is discord having issues
If I had a bot that sent a message then waited 15 seconds then edited that message can i do that?
Sure
Why do you think its having issues
iscord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
Has nothing to do with discord having issues lol
then whats that for
Invalid Form Body
Yea but it used to work exactly nothing vhanged?
Are you asking for help to solve it
Give this a read over
Specifically this
Be specific about what you need help with, make sure to include a code example, the error message (if you got one), and an explanation of the problem. Don’t share code or error messages as screenshots, because those helping often need to copy parts of the code or error. If your question still doesn’t get answered, try reading our guide on asking good questions and try again.
how to increase void time in discord py, for example the default is 3 seconds, how can I increase it to 10-15
What do you mean by "void time"?
like, an interaction is only available for 3 seconds before it becomes invalid. How to increase that time?
you can't increase the time but you can defer within 3 seconds and send a follow up later
oh okay
wish HelpCommand was generic :-(
I smell, feminine men
How do I make this run with a slash command using discords slash feature
async def on_message_delete(message):
if log_channel:
embed = discord.Embed(
title="Deleted Message Log",
description=f"Message sent by {message.author.mention} deleted in {message.channel.mention}",
color=discord.Color.red()
)
embed.add_field(name="Content", value=message.content or "No content", inline=False)
embed.set_footer(text=f"User ID: {message.author.id}")
await log_channel.send(embed=embed)
@bot.event
async def on_message_edit(before, after):
if log_channel and before.content != after.content:
embed = discord.Embed(
title="Edited Message Log",
description=f"Message sent by {before.author.mention} edited in {before.channel.mention}",
color=discord.Color.orange()
)
embed.add_field(name="Before", value=before.content or "No content", inline=False)
embed.add_field(name="After", value=after.content or "No content", inline=False)
embed.set_footer(text=f"User ID: {before.author.id}")
await log_channel.send(embed=embed)
@bot.command()
@commands.has_permissions(manage_channels=True)
async def setlogchannel(ctx, channel: discord.TextChannel):
global log_channel
log_channel = channel
embed = discord.Embed(title="Log Channel Setup")
embed.add_field(name='Deleted and edited messages will now be logged in', value=channel.mention)
await ctx.send(embed=embed)
@setlogchannel.error
async def setlogchannel_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have permission to do this.")
elif isinstance(error, commands.BadArgument):
await ctx.send("Please mention a valid text channel.")```
from discord.ext import commands
Is installed
and discord obv
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
That's how you make slash commands, read it
How to set wealcomer and wealcome message in channel
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
So is there a reason for not using bot.get_channel(channel_id) or await bot.fetch_channel(channel_id), I mean why would you use only get_channel in that case?
How to make embed announcement
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.
For interaction based contexts this does one of the following...
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...
There isn't really a reason to always just use get_channel
I'm just trying to understand the logic here. Why would you not just use both of them/or await if that could save you in the future?
That's what I said
Use both
Disnake also has some of those built-in
!d disnake.ext.commands.Bot.getch_user
await getch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Tries to get the user from the cache. If it fails, fetches the user from the API.
This only propagates exceptions when the `strict` parameter is enabled.
I have seen many programmers only using get_channel for some reason 🤔
Yeah well, unfortunate for them
Usually channels get cached pretty fast, but not always the case so yeh
Disnake have fetch_channel built-in on failure for get_channel, while discord.py does not?
Why?
hey guys, how can i make command group in cog?
This channel is made for library design, choices, etc. questions
That's not what the channel topic says
And this channel has never been that way
Oh I'm dumb you meant the foreign channel
I thought you were answering
Btw I just realized that is for the user and not channel
My bad Disnake works the same way. The returned channel or None if not found.
I am here again to see which is better
The first one
what is the approach to include a custom number of buttons depending on the number of embed images (1 to 4)? somehow creating 4 views per case doesnt seem like the way although thats all i can find now
heyyy sup?? i have tried to download d.py to my new laptop but when i went to my code editor(vscode) it says "Import "discord" could not be resolved", i upgraded my pip version... is ther anything i can do?
Buttons get added to views. You don’t need to create a new one for each button
hey guys, can someone please tell me whats wrong? First time working with command class in cog
How to turn a select menu back to it's placeholder after selecting an option?
all my buttons are in one view so far
but how do i include only some of them to be used depending on custom logic, because now its just adding all the buttons that i define in the view
You can only do Reload(client)
when i do that i get this error
can you show us the entire reload class
I believe you need a super().__init__() in your Reload's ctor
ohh, actually i new so i dont know much about it, but is it something like i have in main.py?
like this
intents = discord.Intents().all()
super().__init__(command_prefix = commands.when_mentioned_or(prefix), intents = intents)```
Anyone mind helping me with this?
its working thank you so much and could u please explain to me how __init__ and super().__init__() works and whats the difference
__init__ is part of creating an instance of a class, and super() is how you inherit a parent class
https://realpython.com/python-class-constructor/
https://realpython.com/python-super/
The superclass inside your Reload is the app_commands.Group class, so when you call super().__init__() you're really calling the initializer of the Group class. This lets discord.py set some internal attributes there (like the parent attribute which was causing your error)
okayy, thank you so much i understand it more now <3
thank you so much too, ill read that webs <3
(it is a more in-depth explanation of those terms in general, Robin's explanation for your case here is a good summary)
okay okay, ill read it anyways so i can learn something new
usually i store the buttons as attributes of a view subclass*, add only the ones desired, and then later if i want to change out the buttons, i'll clear the items and add them back, e.g. ```py
class PaginatorView(discord.ui.View):
def init(self):
super().init()
self.first = FirstPageButton(...)
self.prev = PrevPageButton(...)
self.next = NextPageButton(...)
self.last = LastPageButton(...)
self.update_buttons()
def update_buttons(self):
self.clear_items()
if not self.at_first_entry():
self.add_item(self.first)
self.add_item(self.prev)
if not self.at_last_entry():
self.add_item(self.next)
self.add_item(self.last)``` \* if you use the decorator form of defining buttons, you can access those button instances using their function name
I have tried everything how can I check if a user has admin privilages ? This does not work, been at this longer than id like to admit
@bot.tree.command(name='delall')
@commands.has_permissions(administrator = True)
@app_commands.describe(input = '"all" to delete all codes')
async def delall(interaction: discord.Interaction, input:str , ):
if input == 'all':
sc = open('Codes.txt' , 'w')
await interaction.response.send_message(f'**{interaction.user.name}** hat alle gültigen codes gelöscht')
while True:
now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
break
print(Fore.RED + f'{interaction.user.name} hat alle codes gelöscht :: {now}')
sc.close()
elif commands.MissingPermissions:
await interaction.response.send_message('You dont have Admin privilages stop being naughty')
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions).
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
I just fixed it. Just to run into another problem xd
Hmm ;-;?
This is not printing, I am the owner of the server and I have admin role.
what am I missing
@bot.event
async def on_message (message):
sc = open('Codes.txt' , 'r')
scContent = sc.read()
if message.content == '.c' and message.author.has_permissions.administrator:
print(f'{message.author} hier sind alle Codes: \n{scContent}')
# read from file and print output
await message.reply(f'**{message.author}** hier sind alle Codes: `\n{scContent}`')
sc.close()
else:
message.response('Stop being naughty')
If i remove and message.author.has_permissions.administrator: it does print but then everyone can print
This isn’t how you use has_permissions
It’s a decorator for commands, which you should be using
I dont want to for this specific purpose. Is there a way around that ? And still being able to limit it to admin ?
Why don’t you want to?
because as far as im concerend. You can only have the slash commands with and input and I would like to avoid that. Or am I wrong
slash commands don't need to have any parameters, but i think pep was also referring to discord.py's prefix command system which is typically preferred over on_message()
btw if you weren't using it already, you can set default permission requirements on application commands so they won't show up to other users
!d discord.app_commands.default_permissions
see third paragraph: "Setting an empty permissions field ... will disallow anyone except server administrators from using the command in a guild."
(if you don't want to allow the command in dms, apply the @app_commands.guild_only() decorator too)
@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). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
no shot
thats wicked that fixes alot for me thanks
probably my last question xd. But is there a way to fasten up the process of registering commands ? Or does it just take forever ?
at some point in time, discord made global commands sync near instantly so if it hasn't shown up by now, your bot probably hasn't synced its commands correctly
hmm ok, because I tried discord.js for a hot minute and they registered instantly
what discord.py code do you have to sync your commands?
@bot.event
async def on_ready():
print(f'{bot.user} is ready to rumble!')
print('Published by Moritz Reiswaffel')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} commands!')
except Exception as e:
print(e)
print('------------------------------')
```
just this, I have a boilerplate for a command to sync but I dont work
hm, not the best practice but that seems functional
does it say Synced {n} commands when you start the bot?
yes
do the commands show up if you click your bot icon in the command list?
or if you check in your server's integrations tab
they do, but I took discord like 5min now to register the delall command
oh well, the fact that sync() returned some number of commands means that discord's API responded to your bot with the list of commands that got registered, so any lag afterwards is likely from discord's side
ffs
hmm ok, guess Ill have to live with that. Now I just gotta figure out my slash commands
there is bots called "bot maker" its a bot can make a bots for you
for example: you click a button in the bot to make "autoline bot" then it will ask you for a token and prefix then when you insert the info the bot will work
does anyone have an idea how this thing work?
Usually restarting your discord client will fix it
You’re assuming we have context that you haven’t provided. What is an autoline bot
bot maker....and here I just wrote my discord bot from scratch.
there are some of them out there but they're not too customizable and are mainly targetted towards people who can't/don't know how to code
Yeah I looked around at some before I decided to just do it myself. It's not as daunting as I thought it would be
my first ever discord bot was made using Discord bot maker on steam with some nice gui
i doubt its still a thing
it was like 2 years ago
dam it costs money now shush
I need help. First time writing a bot. The bot is online, but does not respond to command.
Hello, I have a question:
Does Python discord.py bots run their own instance for each server they're in or not?
Example:
I have this code
class GameCog(commands.Cog):
def __init__(self):
self.l = []
@commands.command(name="add")
async def add(self, ctx):
self.l.append('Example data')
And I have two discord servers ( Server1 and Server2 ).
If I run the add command in Server1 ( which adds one element to the list) and then I re-run that command on another server, will it add the element to a new list on to the old one?
Is basically the same instance of the bot executed for all servers or viceversa?
that is not the way you should use commands. You should use discord.etx.commands.Bot.
This from the documentation https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=commands bot#discord.ext.commands.Bot
I believe tho you could have to enable discord message intents
No
If your bot is sufficiently large enough, then you'll need to start sharding, where one instance handles some number of guilds (but not 1)
After you run the command in both guilds, the value of the list l will be ["Example data", "Example data"]
Talking about code you can do it like that (using too the discord.etx.commands.Bot)
You will have to enable message intents from Discord Developer Portal too!
import discord
from discord.ext.commands import Bot
intents = discord.Intents.default()
intents.message_content = True
bot = Bot(command_prefix="!", intents=intents)
okay, that sounds like a problem. I am creating tictactoe game, which stores the players and the board. It means that for every server the bot is into will share the same data.
you could use a dict where the ID is the guild ID and the value is whatever you want
sounds like I will have to create an array of games and players (well in a structurated way)
yes it was exactly what I was thinking
thank you, Robin
no prob
**I am available to work for you on your projects at a very cheap price ** 
See: rule 9
I've already told you this is against rule 6/9. This is going to be your last warning
tbh you should just get a job with higher pay tho
there are websites for this anyway
Is there a decorator for checking if a message was sent to the bots direct messages?
🤔
or what's the most optimal way to handle it?
ATM I was thinking of doing "on_message" and checking if the message was sent to dms
no
This is something extremely easy to implement yourself
I know, I was just hoping for something simpler lol
you could write a really simple check that just inverts the value of https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=guild_only#discord.ext.commands.guild_only
is this pycord
yeah that confused me just a little
does anyone knows if there’s a way i can host 2 or more discord bots for free?
How do you @ roles?
same way you @ anything else
i meant using discordpy
!d discord.Role.mention
property mention```
Returns a string that allows you to mention a role.
I’ll pay someone 20$ to recreate this discord bot (I have screenshots of the commands and what they are suppose to do)
!rule 9
its not important its just any bot for example I asking how to make the bot maker
when you insert any bot token in it the bot will work in some code like "autoline" or anything
Hello, I am a previous comer to discord.py and can't seem to successfully load a command cog despite my efforts of research on the newest documentation, it could be that I'm missing something but would the following blocks of code be valid to load a cog?
from discord.ext.commands import Bot, Cog, Context
from discord.ext.commands import command
class TrialCog(Cog):
@command()
async def say_hi(ctx: Context, *) -> None:
await ctx.send(str.format("Hey there {0}", ctx.author.mention))
async def setup() -> None:
await bot.add_cog(TrialCog)
```.
from asyncio import run
from discord import Intents
from discord.ext.commands import Bot
async def main() -> None:
intents = Intents.default()
my_bot = Bot(command_prefix="!", intents=intents)
await bot.load_extension("trialcog")
await my_bot.run("")
run(main())```
It really doesn't make sense to me why this wouldn't work
The error I'm getting Extension 'trialcog' raised an error: TypeError: cogs must derive from Cog
await bot.add_cog(Greetings(bot))
https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#cog-registration
Compare that with your line
Even if I add the parenthesis I get the same error
Nevermind, I got the system working I just needed to refresh my knowledge and understand the run function of the Bot which isn't asynchronous, thanks though!
You will get this error as long as add_cog's argument is an instance of a class derived from a class other than Cog. If you're still getting it, seems like you added parentheses in the wrong place
Yeah I figured that
hey
ive got this script and ive got no idea why it doesnt work
theres no errors
import discord
import os
import random
import time
from discord.ext import commands
from threading import Thread
from discord.flags import Intents
TOKEN = os.environ['TOKEN']
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('{0.user} e online'.format(client))
@client.event
async def on_message(message):
if message.content.startswith('!ves'):
await message.channel.send('whatsappvess')
client.run(TOKEN)
anyone care to help?
You haven't enabled the message content intent, so you won't receive any message content
so just intents.messages = True?
I said message content, not messages
tias
so yes?
Try it and see
Read the error and do what it says
!intents
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.
For free? 😏
Which one should I use?
1.
wins = None
losses = None
if wins and losses:
print(f"{wins / (wins + losses) * 100:.2f}%")```
2.
```py
wins = None
losses = None
if wins is not None and losses is not None:
print(f"{wins / (wins + losses) * 100:.2f}%")```
depends what other values wins and losses can take
if its for example 1 or 5 its fine with the first example
but if it can be 0 and you still want to print it out then it wont work
Which one would you use? Would you still print out the winrate with 0 wins and 5 losses (0.00% winrate) for example?
do i need to make my backend model structure async if i'm using it with discord.py (which is also async)
i want to use async locks on some of the classes but i'm not too keen on having to make my model async, when i also want to access it synchronously outside of the bot
Hmh I think I'm just going to use:
if wins is not None and losses is not None:
print(f"{wins / (wins + losses) * 100:.2f}%" if wins + losses != 0 else "0.00%")```
i would print out 0% winrate yes
what do i do if i need to do both of these in the same callback?
await interaction.response.edit_message(view=view)
await interaction.response.send_message(f"{mode}:\n{res}", ephemeral=True)
just checking if there is a better way than to use discord.Client.get_channel(interaction.channel_id).send() 
btw, you can do {wins / (wins + losses):.2%} would pretty much be the same thing
use interaction.followup.send
works thanks
I am currently making a chess bot and want to edit the original chess board message
svg_data = chess.svg.board(board=self.board)
png_data = cairosvg.svg2png(bytestring=svg_data)
image = discord.File(BytesIO(png_data), filename="board.png")
if self.turn == 1:
await interaction.response.send_message(file = image)
else:
await interaction.response.edit_message(content="New Move", file=image)
This is what i am currently doing but it doesnt work
What exactly doesn't work
Mm I think you can send files as svg without converting them to png can't you
And of course, please describe what doesn't work and attach traceback if you got any
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Example...
thanks
ImportError: cannot import name 'InputText' from 'discord.ui' (/home/xxxxxx/.local/lib/python3.9/site-packages/discord/ui/__init__.py)
Any idea why this isn't working?
It’s TextInput.
Oh
Thanks
This is valid code right?
class MyModal(Modal):
def __init__(self) -> None:
super().__init__("A Modal") #title of the modal up top
self.add_item(TextInput(label="Short Input", placeholder="Placeholder"))
self.add_item(
TextInput(
label= "Long Input",
value= "Default", #sort of like a default
)
)
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Your Modal Results", color=discord.Color.blurple())
embed.add_field(name="First Input", value=self.children[0].value, inline=False)
embed.add_field(name="Second Input", value=self.children[1].value, inline=False)
await interaction.response.send_message(embeds=[embed])
@bot.tree.command(name="sample-application", description="Sample application")
async def sample_application(interaction: discord.Interaction) -> None:
modal = MyModal()
await interaction.response.send_modal(modal)
await interaction.response.send_message("Application started", ephemeral=True)
tias
Hey all, quick question - what is currently the best Discord library in Python in terms of syntax / feature functionality / completeness of API / stability etc particularly in terms of integration with direct file playback for a music bot (yt is unnecessary and will not be used) and if any python library has integration of bot "listening" eg voice activation that would also be of big interest. I'd love a birds eye view at the present landscape.
I was previously using Disnake with a pretty complex/extensive bot that is still widely used but I'm trying to decide on library for the overhaul I'm about to perform and want to understand my options as best I can.
Thanks! ❤️
Also, just to note, some of the things I really liked about Disnake that I'd want from whichever library I end up using:
Cogs, they did a great job as an OOP way of organizing the project in a logical and meaningful way
Slash Command decorators, I really liked the syntax for creating commands, it was very effective - I don't want to have an ugly on_message handler because it seems like bad practice to do so and after using Disnake's command implementation I don't want to lose that sort of quality implementation.
Additionally, a high quality music player wrapper that can play local files is essential as well
Intuitive modals would also be very nice for command systems.
Generally, except for hikari all of the libraries, nextcord, pycord, disnake etc are forks of discord.py
but afaik discord.py was not being actively developed/maintained and only last year the original dev returned to the project so I guess I'm reaching out to see if the forks are ahead or behind overall at this point versus the original
Each library has a slash command implementation, discord.py, nextcord and pycord all use decorators for their slash commands, I’m not sure what disnake does
btw thank you for the response ❤️
About listening, pycord has native support for it, and discord.py has an extension
PyCords implementation is just ripoff of the discord.py extension though
They copied the code so it’s about the same
classic
most dedicated Pycord developer
haha understood, so presently/moving forward is discord.py the best option given my desired parameters above? Does discord.py do cogs in the way disnake did?
disnake is a fork of discord.py, so unless they modified it, it should be the exact same
!d disnake.ext.commands.Bot.add_cog
add_cog(cog, *, override=False)```
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
Changed in version 2.0: [`ClientException`](https://docs.disnake.dev/en/latest/api/exceptions.html#disnake.ClientException) is raised when a cog with the same name is already loaded.
looks like disnake didn't change the cog system from discordpy
Oh excellent! That is great news
I think it might be based on the old 1.7.3 implementation
I looked at dpy docs and didn't see obvious slash command decorator though, did I overlook it?
https://github.com/Rapptz/discord.py/tree/master/examples/app_commands
discord.py has a different implementation where application commands are added to a CommandTree, and then synced to discord
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
discord.py implements app_commands which slash commands are a subset of
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
ooh so if I'm understanding correctly looking at the example,
@client.tree.command()
is how commands are added - what denotes it as a slash command? I don't see any params passed into the decorator which I'd normally expect at least a name="" value to map the command to a specific command name in the command namespace - I can only surmise based on this example that it names based on the python function name?
Then likewise, looking at this:
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
The purpose of this if I'm reading the comments correctly in the example is to immediately sync servers with the new commands?
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)
So here, I see that we're defining a client instance which is later used, and in that client instance we're instantiating an object of type CommandTree with params being the Client object, and then logically the tree commands above would modify that instance and would be "global" commands which I'd surmise by the above take 1 hour to update. Why didn't disnake run into this issue? I don't recall slash commands in disnake requiring an hour to update - was it doing the copy operation under the hood and I wasn't aware?
Lots of questions, tyvm for the great answers btw
the tree denotes it as a slash command
or, well, an application command
discordpy has a container called a "command tree" that holds information about all application commands
oooh interesting, so in this case application command is synonymous with what I'd consider slash command?
a slash command is a type of application command
so are context menus
and command tree object stores those in a way that is communicated to discord
the .sync is what actually communicates them with discord
ooh interesting - are there examples of complex but elegant usage for context menus? I'd guess I can look at CommandTree in documentation and probably find clues in terms of how it might be done, yes?
context menus aren't all that complex so no, I'm afraid
are context menus also written to CommandTree or are they stored separately? Just since you used application command which I'd surmise is the parent class and slash command and context menu are effectively children/subclass implementations and would probably be stored in the same CommandTree object, is that a correct assumption?
context menus are also application commands, so they're stored under CommandTree
just since you used application command which I'd surmise is the parent class and slash command and context menu are effectively children/subclass implementations
this is a perfect analogy
not sure if my brain is just blanking or that's the only two types of application commands, though
I expect I can check documentation now that I know what I'm looking for
thank you very much btw! 🙂
no prob, have fun
@ebon island I’ve created this post https://discord.com/channels/267624335836053506/1177841083376480308 on context menus if you’re interested
Can anyone who is familar with Python come to dm's and help me with a script? I cant send it all here 😭
!paste
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.
We need help knowing what's not working
The dropdown doesn't show
Selects have to be added to discord.ui.View's first, and then pass into the view kwarg
!d discord.ext.commands.Context.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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.
For interaction based contexts this does one of the following...
Notice how view is supposed to be an instance of discord.ui.View
Oh yeah
dropdown_message = await ctx.send("Choose a resource to add to your backpack:", discord.ui.View)
It's not this is it?
no
you need an instace of discord.ui.View, or a subclass
View the examples in the repo for a proper implementation
.. Sorry I don't know what any of it means 😭
Join the discord.py server -> #1083160687733395466
I got banned for invalid reasons there
perm banned
god knows why
also i dont have access to the link haha
yes, which is absolute bullshit
read back my messages
I have literally nothing against what anyone wants to be or feel like 😭
this danny person just seemed incredibly abusive of his 'very big' moderator job
Also, is there anyway I could have a small setup of a websocket connection with discord's event gateway
just for fun to see what payloads are received by discord.py (but instead just me having a very simple client instead of the discord.py wrapper around it)
ah its not that easy, discord does require feedback using heartbeats
So i made a game and it works fine, but the bot doesn’t pick up some words, i suspect it’s ratelimits but i just want some more opinions.
code: https://paste.pythondiscord.com/L5KQ (lines 63-85)
example below
eh, it's possible that your wait_for was too slow to catch up, missing some on_message event while you're processing the words and reacting, if it is ratelimited, you can't react to any but eventually you do still react on them, instead of doing this wait_for while loop, you may wanna just create a temporary listener, would be much efficient
Something simple like this```py
async def wait_for_messages(bot, timeduration, check):
q = asyncio.Queue()
async def on_message(message):
if check(message):
q.put_nowait(message)
bot.add_listener(on_message)
start_time = time.time()
while time.time() - start_time < float(timeduration):
yield await q.get()
bot.remove_listener(on_message)
Then using them as ```py
async for UserWord in wait_for_messages(bot, timeduration, check):
... # process here
So that way you dont miss any on_message events while processing them, recommend using a queue
this is just an idea tbh, i didnt test this code
you could implement it yourself, aiohttp implements the Websocket protocol
How do I correctly add options to the discord.ui.Select class? putting list as super().__init__ option is not the case as i need to use await, to access the list from database
class DeleteProductChoice(discord.ui.Select):
def __init__(self, channel_id: int = None):
self.channel_id = channel_id
super().__init__(
placeholder='Товар',
min_values=1,
max_values=1,
)
async def options(self):
return [discord.SelectOption(label=label) for label in await db.select_products(session, self.channel_id)]
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
await interaction.followup.send(
f'{self.values[0]}',
ephemeral=True
)
it will need to be passed in from "upstream" where you fetch the data
ok, thought I could do it with some kind of function inside the class
class MySelect(discord.ui.Select):
def __init__(self, options: list[str]):
super().__init__(
placeholder="Pick one",
min_values=1,
max_values=1,
options=[discord.SelectOption(label=text) for text in options]
)
async def callback(self, interaction: discord.Interaction):
...
@bot.command()
async def my_command(ctx: commands.Context):
options = await fetch_data() # let's say this fetches a list of strings from the database
view = discord.ui.View()
select = MySelect(options)
view.add_item(select)
await ctx.send(view=view)
@void mauve
yeah I got it, thanks
Are they fr banning people for damn pronouns 💀
Good
sensitive area 💀
Is there a way to register persistent views dynamically? So, basically I have some products that are added to the database, and they have a button which creates ticket referring to specific product from the shop, and in order to make button persistent I need to pass unique id to each button on different products.
This implementation gives out TypeError: View.to_components() missing 1 required positional argument: 'self'
async def setup_hook(self) -> None:
for extension in self.initial_extensions:
await self.load_extension(extension)
view_metadata = await db.select_products_metadata(session)
for data in view_metadata:
print(data)
self.add_view(TicketCreationView(data[0], data[1]))
Heres the file with the view that needs to be persistent:
https://paste.pythondiscord.com/NUNQ
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
ERROR:discord.ui.view:Ignoring exception in view <TicketCreationView timeout=None children=1> for item <CreateTicketButton style=<ButtonStyle.success: 3> url=None disabled=False label='🛒 Купить' emoji=None row=None>
Traceback (most recent call last):
File "F:\PYPROJECTS\discord\CIS-SHOP-TicketBot\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "F:\PYPROJECTS\discord\CIS-SHOP-TicketBot\package\bot\modules\view\create_ticket.py", line 56, in callback
await interaction.response.send_message(
File "F:\PYPROJECTS\discord\CIS-SHOP-TicketBot\venv\Lib\site-packages\discord\interactions.py", line 786, in send_message
params = interaction_message_response_params(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\PYPROJECTS\discord\CIS-SHOP-TicketBot\venv\Lib\site-packages\discord\webhook\async_.py", line 578, in interaction_message_response_params
data['components'] = view.to_components()
^^^^^^^^^^^^^^^^^^^^
TypeError: View.to_components() missing 1 required positional argument: 'self'
which line is interaction.response.send_message? because it's not in your code there what's in create_ticket.py
oh sorry, implemented it in another file:
create_ticket_logic.py: https://paste.pythondiscord.com/N2WA
hmm error suggested that you passed in view into send_message, but ion see it there
did you changed it?
It's an entirely different file
so thats the problem?
You didn't init the class?
where exactly

I would recommend using low-level components instead
👄👁️👄
popular_words = open("answers.txt").readlines()
i get:
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.wordle' raised an error: FileNotFoundError: [Errno 2] No such file or directory: 'answers.txt'
but it looks fine(see pic)
How are you running the project
And what's your working directory
asyncio.run(main())
Make sure it's max bot and not root
I meant command line
what do you mean by that?
async with client:
await load()
BOT_TOKKEN = settings.TOKKEN
await client.run(BOT_TOKKEN)
asyncio.run(main())```
No, command line is python main.py
i am running that with vscode
so what do you mean by that
Tbh yk what
Yeah your root is not max bot
Gotta fix that
File -> Open Folder -> max bot
You need to have that folder as root opened and venv inside
ok
it is not in cogs
couldn't you just use DynamicItem?
will it make the view persistent? will i be able to use the buttton after restart?
now it give me the error that " No module named 'discord'" even i pip installed this
it is the interpreter
?
well it's a similar concept, bot.add_dynamic_items, but instead of each view, you just create a template for it, see an example here
thanks, Ill do the research on that
Either move your previous venv into max bot or create new venv, set it from commands palette and install discord there
i did it
Screenshot please
Full
Mm pretty sure previous installation ended up with error
Also it seems you somehow tried installing it globally
do you know how can i change this?
Do pip install discord.py again
weird venv seems to be activated tho
Consider using the `--user` option or check the permissions.``` same error
Screenshot how you used pip install pls
looked the rror
error
it says need admin premmisions gave the vscode and now it installed it
It might be that the venv is broken if it's not newly created
but discord is still not resolved
Well it seems you are installing them globally
The only possible situation when it may happen is your venv is broken and it fallbacks to global pip
just add the --user flag when installing and give it a try
ok 1 sec
how did u make the venv tho?
Try
- Killing terminal
- Deleting the venv and creating new via
py -3.11 -m venv venv
does he have 3.11?
ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv.
Yeah I think, it was on screenshots
ah venv issue
@spark nimbus ^
why does error says 3.8 site packages then 😔
Because it fallbacks to global since venv it broken
yes
well usually the global python is the one u install latest
why would someone install 3.8 after 3.11 ;-;
I used to do that quite often when doing machine learning, but then I discovered I could just use conda
done and i this error:
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited```
All ML libs are stuck at 3.9 max 💀
Well at least ones I'm familiar with
not sure which libs ur talking abt
Tensorflow
show the code
Great at least it now runs
thats 3.9<=3.11 iirc
!paste
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.
Maybe it was directml
It's client.start, not run
I think
working thx
both are there except run is a sync method
i am inputting values to my bot by saying "!input 100 apples, 100 bananas", but i have this code that checks if what im inputting is correct and in a specific list, however it only checks the first value that i am inputting. how can i make it check all the values i am inputting
found_items = [item for item in items if any(word in message.content.lower() for word in item.split("-"))]
Input checking? Would recommend regex
if re.fullmatch(r"(?:\d+ \w+(?:, )?)+", your_input)
I think that's the thing
would this work for checking the whole list to all the items that can be inputted?
Yea ive implemented one
It was a bit tricky to figure out at first with sending heartbeats and stuff
That applies to string
could you explain more?
Actually you need to explain more ☺️ what is items
items is the list with what can be inputted e.g items = [“apples”, “bananas”….
That can be done either via injecting it into regex pattern or by filtering them after searching
First method is more efficient imo
inp = message.content.split(",")
split_list = [word for item in inp for word in item.split()]
split_list.remove("!input")
splitlist = ','.join(split_list)
items = ["apples", ...]
found_items = [item for item in items if any(word in message.content.lower() for word in item.split("-"))]
if found_items: ```
this is what i have so far
for what im trying to do yes
!e ```py
import re
print(re.findall(r"\d", "൫"))
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
['൫']


sooooo
so if this pattern was correct r"(?:\d+ \w+(?:, )?)+" use r"(?:[0-9]+ \w+(?:, )?)+" instead
how would i implement it in this code
!e ```py
import re
input_string = "!input 100 apples, 100 bananas"
for match in re.finditer(r"(?P<amount>[0-9]+)\s*(?P<item>\w+)", input_string):
print(match.group("amount"), match.group("item"))
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 100 apples
002 | 100 bananas
but that doesnt check if the inputted values are correct and in the items list
yeah regex is just so you validate the input from user
after you got only things that are in format you want then you validate them with your data
thats the part im having issues with, the validating part
match.group("amount") is the amount and match.group("item") is the item
then explain how you want to validate
when is the value correct
when the value is correct it just proceeds, if not it sends and error message
why can't I get the ID of the webhook message?
!e
allowed_fruits = ["bananas", "apples"]
valid = "100 bananas, 300 apples"
invalid = "500 oranges, 30 bananas"
# regex way
import re
pattern = re.compile(rf"(?:[0-9]+ (?:{'|'.join(allowed_fruits)})[, ]*)+")
print(pattern.fullmatch(valid) is not None)
print(pattern.fullmatch(invalid) is not None)
# non regex
f = lambda s: all(i.split()[1] in allowed_fruits for i in s.split(", "))
print(f(valid))
print(f(invalid))
@vale wing :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | False
002 | False
003 | True
004 | False
Damn my regex is bad
!e
a = ["bananas", "apples"]
print(rf"(?:[0-9]+ {'|'.join(a)}[, ]*)+")```
just turn on wait - wait=True
@left dew ok here's fixed regex way
!e
allowed_fruits = ["bananas", "apples"]
valid = "100 bananas, 300 apples"
invalid = "500 oranges, 30 bananas"
# regex way
import re
pattern = re.compile(rf"(?:[0-9]+ (?:{'|'.join(allowed_fruits)})[, ]*)+")
print(pattern.fullmatch(valid) is not None)
print(pattern.fullmatch(invalid) is not None)
@vale wing :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | True
002 | False
Can put that thing into regex101 and it will explain what each construction does
hi, how would i check if the pattern.fullmatch is true? and would i have to remove the "!input" first?
fullmatch() is not None returns boolean
When it doesn't match, function returns None, when it does it's a Match object
You can just ```py
if fullmatch(...):
...
Since it's either Match or None
ohh okay
can i do if fullmatch(splitlist)?
order = message.content.split(",")
split_list = [word for item in order for word in item.split()]
split_list.remove("!order")
splitlist = ','.join(split_list)```
so just message.content?
on_message hurts hard
its the best
@bot.command()
async def cmd(ctx: commands.Context, *, text: str):
process(text)
And the text will be everything after command
Use it instead, why parse manually when smart people who made the lib already implemented it for you
And not only parsing
can i just do text.content?
or is it just text
No you can't, it is a string, not instance of Message
thanks it works now
have a nice christmas
id = int(id)
^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
I'm trying to get a webhack message and change it. How can I fix the error?
Don't see this line anywhere in your code
Please provide full traceback
Unhandled exception in internal background task 'status_task'.
Traceback (most recent call last):
File "C:\Users\Тимур\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
File "c:\Users\Тимур\Documents\MEGALODON\cogs\status.py", line 133, in status_task
await message_admins.edit(embed=embed_first)
File "C:\Users\Тимур\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 892, in edit
thread = Object(self._thread_id)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Тимур\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\object.py", line 77, in __init__
id = int(id)
^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'```
That's actually internal discord.py code
2nd, id does not have a value
odd
Nah it's just that nobody cares about id function
ik, but its still bad practice
can you show more context instead of these cut out lines
well, message_admins is None
meaning your passed id is incorrect
to get the admins message
Please print
messagemessage.idmessage_adminsmessage_admins.id
this is where your error is at
bro, its clear. Message is None
fetch_message didnt return a discord.Message object
webhookmessage*
bruh
Would be AttributeError 🤷♂️
ok then dont listen
want to see how i fetch my messages which returns None?
for an incorrect message id
my message id is correct
Ok good luck figuring this out 👌
sec bro
youre right, tho i have never seen a message object without a message id
Ig because there was another condition which wasn't being fulfilled due to an absence of else block? Idk that's what explains it
I spent hours trying to do it and that's the only thing that worked.
Wait what the heck why are u tryna edit the module files.....?
make a pull request for this
for an actual proper solution xd
seems like Object(self.channel.id) is None
very odd
yea he shouldnt, but it seems like a discord.WebhookMessage issue
Bro edited internals
You might have found a bug 🤯
a bug in py-cord that is
https://github.com/Pycord-Development/pycord/blob/v2.4.1/discord/webhook/async_.py#L1827
when the message channel is a PartialMessageable, which i believe only happens if the webhook was created with partial()/from_url() or the guilds intent is off, it defines the _thread_id attribute which could be None, but the WebhookMessage.edit/delete methods assume that _thread_id isn't None
Great
according to the git blame it looks like a 2 year old bug as well
remember kids, don't be a lazy type-hinter!
bug report filed: Pycord-Development/pycord#2298
in the mean time i suggest you try to retrieve the webhook from TextChannel using .webhooks() which shouldn't have the same issues, or continue using your own fork until they release a fix
you can also use the message returned by send() to edit the message, rather than trying to fetch it twice
what does this error mean?
TypeError: View.to_components() missing 1 required positional argument: 'self'
the method didn't receive an implicit first argument, likely because you called it on the class instead of on an instance
a full traceback is more useful, but i'd wager a guess that you passed a View class directly to send(view=) rather than instantiating the view first, i.e. py view = discord.ui.View() view.add_item(MyButton(...)) await ctx.send(..., view=view)
i just forgot the brackets on my view
how use self?
that's a bug in their documentation, self is automatically given when you call the method on an Embed instance
?
what about it?
ah, you'll need to copy whatever name it had beforehand
name = embed.fields[index].name?
yeah something like that
it is works, thanks
Hello! if anyone's around, would they be willing to look at my code in https://discord.com/channels/267624335836053506/1187854689983795311
I know the thread is closed, and I'll reposted if someone asks. I didn't want to spam with the same question
What is the problem
- Since the interaction fails on my SessionAction buttons, the disable function doesn't pop off
- I feel that there's a better why to do what I'm doing, and I hope I've done enough code to give folks a sense of what I'm trying to do
Thank you
Hello, how use Cogs and slash command inside ?
Did I answer your question?
you might find it easier to call the corresponding method from DoingStuff directly in SessionAction rather than waiting for the view, but regardless, the reason it says "interaction failed" is because discord expects you to respond to the interaction, whether that be interaction.response.send_message(), edit_message(), or defer()
if you really don't want your view to perform the action directly, you can store the given interaction as an attribute and retrieve it in your command, i.e. ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Click me!")
async def on_click(self, interaction, button):
self.interaction = interaction
self.stop()
view = MyView()
await ctx.send(..., view=view)
await view.wait()
Give some appropriate response
await view.interaction.response.edit_message(content="Do you want to continue?", view=ConfirmView())```
I'll give that a try, thank you so much!
though if it didn't disable your buttons despite having not responded, that might suggest your bot didn't receive the interaction at all? or the view somehow stopped listening before wait() could return
interesting and slightly annoying
I see you using on_click, assuming that's a builtin method?
nah i just named it like that cause it makes sense for the example
How make slash commands in cog ?
Oh ok ty
That makes sense, and it works well enough. Now i need to figure out how to get that selection to return a string that I can use for other stuff
Its the first time i try cogs
@app_commands.command(name = "ping", description = "See the latency of the bot")
@commands.command(name="ping", description="See the latency of the bot")
async def ping(self, ctx: commands.Context):
embed = discord.Embed(title="__**Latency**__", colour=discord.Color.dark_purple())
embed.add_field(name="Time Latency :", value=f"`{round(self.bot.latency * 1000)} ms`")
embed.set_footer(text=f'Requested by {ctx.author} | ID-{ctx.author.id}')
await ctx.send(embed=embed)
This can work with slash command and prefix command ?
no, you'll need to use hybrid commands instead
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#hybrid-commands
(@commands.hybrid_command() in cogs)
hmmm, ok i go try ty
I don't see my command here
@bot.event
async def on_ready():
await bot.add_cog(HelperCog(bot))
await setup_hook()
print(f"{bot.user.name} has connected to Discord!")
@bot.event
async def setup_hook():
await bot.tree.sync()```
Its correct for refresh slash command ?
on_ready runs after setup_hook (which btw you shouldn't be manually calling in on_ready), but in order for sync() to see your cog command, your cog has to be added first
in other words you should add the cog in setup_hook() instead
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = commands.when_mentioned_or("d!"), description = "A discord bot made with love by icetea_lemon", intents = intents)
@bot.event
async def on_ready():
await setup_hook()
print(f"{bot.user.name} has connected to Discord!")
@bot.event
async def setup_hook():
await bot.add_cog(HelperCog(bot))
await bot.tree.sync()```
Like that ?
the bot.tree.sync you had earlier was correct
mb
i wouldn't recommend calling setup_hook in on_ready though
setup_hook's meant to only be called once during login, and discord.py does that for you
I don't need to call the function ? she call herself ?
@bot.event is assigning the setup_hook method to your bot which lets discord.py call it automatically
Ok its good i have remove the call and discord call the function when he login the app
But now i need to wait my command appear in my server...
uhh you shouldn't have to wait that long...
The command don't appear
This is my main
import discord
from discord.ext import commands, tasks
from discord import app_commands
from cogs.helper import HelperCog
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = commands.when_mentioned_or("d!"), description = "A discord bot made with love by icetea_lemon", intents = intents)
@bot.event
async def on_ready():
print(f"{bot.user.name} has connected to Discord!")
@bot.event
async def setup_hook():
await bot.add_cog(HelperCog(bot))
await bot.tree.sync()
print("Cog loaded && slash commands synced")
bot.run("")```
And my cog
```py
import discord
from discord.ext import commands
from discord import app_commands
class HelperCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name = "ping", description = "Get the bot's latency")
async def ping(self, ctx: commands.Context):
embed = discord.Embed(title="__**Latency**__", colour=discord.Color.dark_purple())
embed.add_field(name="Time Latency :", value=f"`{round(self.bot.latency * 1000)} ms`")
embed.set_footer(text=f'Requested by {ctx.author} | ID-{ctx.author.id}')
await ctx.send(embed=embed)```
seems fine to me, maybe try restarting discord to see if your command shows up?
there is a error ?
import interactions
bot = interactions.Client(
token="",
)
@interactions.slash_command(
name="my_first_command",
description="This is the first command I made!",
async def my_first_command(ctx: interactions.CommandContext):
await ctx.send("Hi there!")
)
bot.start()```
Hey, I'm trying to make a discord bot that pings my server and for some reason it shows that my port and IP is unreachable, how can I make it reachable?
def check_port(ip, port):
try:
with socket.create_connection((ip, port), timeout=5) as connection:
print(f"Port {port} on {ip} is open.")
except (socket.timeout, ConnectionRefusedError):
print(f"Port {port} on {ip} is closed or unreachable.")
@tasks.loop(seconds=10)
async def check_status():
channel = bot.get_channel(1188279478166761513)
sever_up_embed = discord.Embed(
title="Server Status",
description="KitPvP: :online:",
color=discord.Color.green()
)
sever_down_embed = discord.Embed(
title="Server Status",
description="KitPvP: :offline:",
color=discord.Color.red()
)
try:
check_port("my ip", 5799)
await channel.purge(limit=6)
await channel.send(embed=sever_up_embed)
except ConnectionRefusedError:
await channel.purge(limit=6)
await channel.send(embed=sever_down_embed)
this is more of a #1035199133436354600 but make sure your IP is reachable and port is open if this script is running outside the server
Also, consider: https://github.com/py-mine/mcstatus
How can I make a discordbot wait for a button press when I DM the bot?
My server is a Bedrock server would this work still?
How good and flexible is that "Pycord" library?
personally I haven't heard good things about it but try it out and if it works for you, great
I just ask because I saw that it has an in-built function for multilingual bots
And I wanna implement that in mine, but I have no clue how to get started in the discord.py for multilingual options
interesting
I thought about a json with the text in different langs
that would indeed be one way
i have a demonstrative bot that uses the stdlib gettext module for translations if you want to look into that, along with a tutorial for gettext in the onboarding
https://github.com/thegamecracks/discord.py-i18n-demo
(src/dpygt/translator.py is how gettext gets integrated with discord.py)
and there's also the fluent-compiler package if you'd rather the use Project Fluent spec over gettext
okay, lemme check
how to do slash cmd?
i know of 2 main ways
-
using
discord.Clientand manage the commanTree on your own -
Using
discord.ext.commands.Botand using cogs to create the commands.
i would recommend using commands.Bot and cogs
oke thankz dude
how to set folders
could you specify more.
the cmds add cogs folder so that like how do ?
Set like what?
mention and auto repond
Detect the message with an on_message event -> Check if the message mentions a user with the discord.Message.mentions property -> If it does, see if the mentioned user has a response setup -> Pull the response from the database and send it
Are you asking for the code for it?
yess
yes code
This is a server meant for learning. Nobody is going to spoonfeed you the code
hmm
We can, and will assist you in creating the code, but nobody is going to entirely write it for you
If you have any questions feel free to ask
Yeah yeah
As a comically large spoon feeder I confirm
When you install a library through pip on Windows, sometimes you may encounter this error:
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
This means the library you're installing has code written in other languages and needs additional tools to install. To install these tools, follow the following steps: (Requires 6GB+ disk space)
1. Open https://visualstudio.microsoft.com/visual-cpp-build-tools/.
2. Click Download Build Tools >. A file named vs_BuildTools or vs_BuildTools.exe should start downloading. If no downloads start after a few seconds, click click here to retry.
3. Run the downloaded file. Click Continue to proceed.
4. Choose C++ build tools and press Install. You may need a reboot after the installation.
5. Try installing the library via pip again.
good time to all i have a quick question .... is yt_dlp better than yt_dl for music functions in adiscord bot ?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
If you open the link you will notice that there are both Java and Bedrock classes ;)
thanks
Hello guys…python noob here…I’m learning how to code a discord bot with the aid of chat gpt…anyone here bored with free time wanna coach a noob? So far I have a compliment feature and a broken uno game feature that I’m working on
feel free to ask any specific questions you may have here
we don't recommend using ChatGPT if you're new, by the way
Understandable…I have a basic entry understanding of reading and manipulating code..but I’m new to the language…I’ll be learning the normal way as well by watching and reading guides… but I like getting my hands dirty and diving in so I’m using gpt in the meantime to assist me
import discord
from discord.ext import commands
import aiohttp
import json
class Fun(commands.Cog):
"""Fun Cog"""
def __init__(self, bot):
self.bot = bot
@commands.command(name="cat", aliases=["getcat"], description="Get a random cat picture.", usage="cat")
async def _cat(self, ctx):
try:
async with aiohttp.ClientSession() as session:
async with session.get('https://api.thecatapi.com/v1/images/search') as response:
data = await response.json()
image_url: str = data[0]['url']
embed = discord.Embed(title='🐱Мяу!', color=discord.Color.random())
embed.set_image(url=image_url)
await ctx.send(embed=embed)
except aiohttp.ClientError as e:
await ctx.send(f"An error occurred while executing the command: {str(e)}")
async def setup(bot):
await bot.add_cog(Fun(bot))
Is everything in the code above correct on the part of the "aiohttp" library?
looks to be the correct format. Is there an error that is causing your exception clause to kick in?
There is no error, I just decided to make sure that I did everything right (I just started learning aiohttp)
yup. I tend to like to use discord's error handlers instead of try/excepts in the command handlers though
@cat.error?

I tend to make my command handlers as light as humanly possible
I'd actually more than likely refactor out the aiohttp request as well 😄
Hehe
Hey, thanks for helping but How can I make this into a whole number instead of a float?
Depends. Do you want to round or truncate?
I'll round then
You can just use the round function
Thanks, also how can I detect that the server is offline using mcstatus? I tried reading there FAQ and everything and I didn't found what I needed
How do i setup a "wait for button press" event?
i've tried several different things and nothing works ;-;
assuming you're using views, the most basic option is to use its wait()/stop() methods
https://github.com/Rapptz/discord.py/blob/v2.3.2/examples/views/confirm.py#L29-L33
examples/views/confirm.py lines 29 to 33
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()```
actually i guess the callback itself is what one might consider as "waiting for a button press", but a suitable solution depends on what you want to do
I'm trying to make a ticket bot (I know, original!).
And I want it to be so when you DM the bot, it replies with "what type of ticket" and several buttons, and when u press 1 it does the thing associated with the button
im at the "get what button u press" stage
I guess I could just do everything inside the button/interaction? 🤔
yes
each button has it's own function so it should be pretty easy
tip: try shorting the ping
kinda long number
Read the message again, it's exactly what they asked for
oh xd
Guys, does Modals support discord.ui.Select?
class discord.ui.TextInput(*, label, style=<TextStyle.short: 1>, custom_id=..., placeholder=None, default=None, required=True, min_length=None, max_length=None, row=None)```
Represents a UI text input.
str(x) Returns the value of the text input or an empty string if the value is `None`.
New in version 2.0.
Only that
No
well thats sad
Can set a default value and placeholder, that's it
thanks
Hey all, so I am trying to create a temporary voice channel thing, where once everyone has left, it deletes the channel however only problem I'm having is that, when people leave by clicking the disconnect button, once the last person does it the channel doesn't get deleted, however if they join a different voice channel, it does, is there any way to fix it?
what's the code that you've tried?
@commands.Cog.listener()
async def on_voice_state_update(self, member:discord.Member, before: discord.VoiceState, after: discord.VoiceState):
possible_channel_name = f'{member.name}\'s Channel'
if after.channel.name == 'Create a Channel':
tempchan = await after.channel.clone(name=f'{member.name}\'s Channel', reason='{member.name} created a channel.')
await member.move_to(tempchan)
if before.channel:
if before.channel.name == possible_channel_name:
if len(before.channel.members) == 0:
await before.channel.delete()
do you not get any errors? after.channel can be None when you leave a vc instead of moving to another vc
uhh no errors no
i think it's probably getting silenced somehow, because after.channel will be none when you disconnect a vc, so you need to fix that if statement by just str your vc obj instead of using .name
if str(after.channel) == 'Create a Channel:'
that isn't the channel i'm trying to delete, or am i wrong?
i wanted to delete the channel that has been created after joining
im talking about your first if statement, the bottom if statement is fine
if it errors in your first if statement, your bottom statement isn't ran
might need to use some try statements
you can just avoid that entirely by casting to str to get the name
you were entirely right, thank you :)
one more thing tho, i wanted to create them in a specific category, i tried just feeding the catID but that didn't work
what code did you tried?
literally just passing category=id in the tempchan = await after.channel.clone(name=f'{member.name}\'s Channel')
yea clone doesnt have that unfortunately, need to edit the vc, ```py
tempchan = await channel.clone(...)
await tempchan.edit(category=discord.Object(your category id))
welcome
back again, same issue as before it won't leave the channel when disconnecting, i assume it's because i edited what category it's in?
na that wouldn't trigger any error, what's the current code now?
@commands.Cog.listener()
async def on_voice_state_update(self, member:discord.Member, before: discord.VoiceState, after: discord.VoiceState):
possible_channel_name = f'{member.name}\'s Channel'
if str(after.channel.name) == 'Create a Channel':
tempchan = await after.channel.clone(name=f'{member.name}\'s Channel')
await tempchan.edit(category=discord.Object(1188678397442916473))
await member.move_to(tempchan)
self.channels_info.append({member.id: {
'channel': tempchan,
"channel_id": tempchan.id,
'name': possible_channel_name
}})
if before.channel:
if before.channel.name == possible_channel_name:
if len(before.channel.members) == 0:
await before.channel.delete()
pretty much the same really, just added the tempchan.edit
the if statement is still error prone here str(after.channel.name), should just be str(after.channel)
ah, i see sorry read the previous statement wrong, 3 am atm ahah
oke, incase you miss it in the docs
how do you check if a discord.Member isi a bot
How do i send two messages in one Interaction?
Like, this is the code https://paste.pythondiscord.com/ZEVQ
But I'm getting this error:
INFO - bot : Inicialidado como Adeptus#4094
2023-12-25 08:15:22 ERROR cogs.status_Cmd Error checking the status of https://api.adeptusstudio.com: Cannot connect to host api.adeptusstudio.com:443 ssl:default [Name or service not known]
ERROR - discord.app_commands.tree : Ignoring exception in command
discord.errors.InteractionResponded: This interaction has already been responded to before
The above exception was the direct cause of the following exception:
You can't, all you can do is send a separate message in the channel
Which is just like normal with
!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) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#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) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
how can i fix this
i need to check the user if its same but it is not letting me do it
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
Has no user attribute
its a class view
but i want to check if the interaction is from a specific user
how do i check that then
I'd be a good idea to show your code
yea sure
oh it gliched again wait lemme do the fix
https://paste.pythondiscord.com/KDCA @slate swan Here
@slate swan ?
No need to double ping, not your 24/7 support agent
ok jeez
Switch interaction and button
?
examples/views/confirm.py line 30
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
oh interaction comes first
Could've guessed by the error saying your interaction is a Button and not an Interaction
I am trying to code a discord modal function with these features..
i am trying to a slash command /getrole, once executed, the modal box thingy will pop up and a random one of 5 questions will be displayed:
How many users did our repository reach in 2023?
Users from how many countries are on our Discord server?
What month did we reach 20,000 members on our Discord server?
How many members did our r/IGCSE subreddit gain in 2023?```
after they guess the question correctly, a role is added to their profile. if they do not get it correctly, it should say 'Incorrect answer!'
stuck at creating the modal
this is my code
this is the error
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x00000184E39C5C00>:
Traceback (most recent call last):
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 895, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\Kaushik\Documents\Programming\r-IGCSEBot Code\r-IGCSE-Beta\2023role.py", line 91, in getrole
await interaction.response.send_modal(GetRole())
File "c:\Users\Kaushik\Documents\Programming\r-IGCSEBot Code\r-IGCSE-Beta\2023role.py", line 75, in __init__
self.add_item(self.question5)
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\modal.py", line 185, in add_item
self.__weights.add_item(item)
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 100, in add_item
index = self.find_open_space(item)
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 90, in find_open_space
raise ValueError("Could not find open space for item")
ValueError: Could not find open space for item
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: ValueError: Could not find open space for item```
@slate swan
!e
print(len("Question 3: Users from how many countries are on our Discord server?"))
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
68
The max length of the label is 45 characters
!e
How many members did our r/IGCSE subreddit gain in 2023?```
!e
print(len(How many members did our r/IGCSE subreddit gain in 2023?))```
I literally already did it, why flooding the channel with nonsense
pyprint(len("How many members did our r/IGCSE subreddit gain in 2023?"))
Your label for question 3 is like 68 characters long, it should be max 45
How can I ignore all other attributes and only log when a member joins or leaves a voice channel?
voice_logs_channel = client.get_channel(1017103688810119258)
if before.channel:
embed = discord.Embed(
title="Member left voice channel",
description=f"{member.mention} left #{before.channel.name}",
timestamp=datetime.datetime.now(),
color=discord.Color.red()
)
embed.set_footer(text=f"ID: {member.id}")
embed.set_author(name=member, icon_url=member.display_avatar.url)
if voice_logs_channel:
await voice_logs_channel.send(embed=embed)
if after.channel:
embed = discord.Embed(
title="Member joined voice channel",
description=f"{member.mention} joined #{after.channel.name}",
timestamp=datetime.datetime.now(),
color=discord.Color.green()
)
embed.set_footer(text=f"ID: {member.id}")
embed.set_author(name=member, icon_url=member.display_avatar.url)
if voice_logs_channel:
await voice_logs_channel.send(embed=embed)```
how can i check in a server if there is a channel named for example:"random-channel-name"
You can use utils.get and Guild.text_channels
By checking if before and after are different
iterate through the guilds text channels then use the .name attribute to get the name
example:
for channel in guild.text_channels:
if channel.name == "a name i want to look for":
# do something....
Utils.get is better though
yes
Do you mean something like this?
if before.channel != after.channel:
if before.channel:
# Do something here
if after.channel:
# Do something else
Yes
Or similar. You may need to add extra checks depending on what you wanna do
I just wanna check when they join and leave a voice channel, nothing else.
E.g.
if before different to after, but neither are none: moved from before to after.
if before is none: member just joined the after.
if after is none: member left the before.
Yup! Thanks
its a bit better to rely on the followup webhook given by the interaction to send more messages, since interactions bypass send permissions that would normally affect TextChannel.send()
(or in other words, if the command was used in a channel where the bot couldn't send messages, TextChannel.send() would fail while interaction.followup.send() wouldn't)
I don't understand this. Can you show me an example?
since we're only interested in the channels let's say before = before.channel and after = after.channel:
- if
(before is not None) and (after is not None) and (before != after), then the user was moved from one channel to another - if
(before is None) and (after is not None), then the user joined a channel - if
(before is not None) and (after is None), then the user left a channel
hrmm... perhaps some parenthesis would help
Okay okay! I'll take a look
So something like this should do the work?
if (before is not None) and (after is not None) and (before != after) or (before is None) and (after is not None):
# Do something here
if (before is not None) and (after is None):
# Do something else

