#discord-bots

1 messages · Page 329 of 1

naive briar
#

discord.py, obviously

rugged shadow
#

disnake

pulsar bridge
#

already went with disnake, but thanks for the ping PI_2cool

drowsy thistle
#

Which embed do you think looks better for a user interface

drowsy thistle
hot sparrow
#

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())
slate swan
#

get the message from the callback and get the embeds, then you can get the image

unkempt canyonBOT
#

property image```
Returns an `EmbedProxy` denoting the image contents.

Possible attributes you can access are...
slate swan
#

Possible attributes you can access are:

  • url
  • proxy_url
  • width
  • height
hot sparrow
#

thanks for your help

#
for emb in interaction.message.embeds:
  print(emb.image.url)
agile idol
#

How to setup wealcomer

slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

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.
lean shard
#

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?

rough shuttle
#

d!interaction

#

!d discord.Interaction

unkempt canyonBOT
#

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.
rough shuttle
lean shard
#

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

rough shuttle
lean shard
#

🤔

rough shuttle
#

sometimes it works, but most of the time it doesn't.

lean shard
#

At what line does it fail?
Do you get an error code?

rough shuttle
#

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
final iron
#

If you use discord.InteractionResponse.defer() you’ll have 15 minutes

rough shuttle
#

okay.

lean shard
rough shuttle
final iron
#

If you’re talking about the 3 second restriction it’s up to discord and can be viewed in their documentation

rough shuttle
#
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

final iron
#

You need an instance of InteractionResponse

#

discord.Interaction.response will return the instance

#

!d discord.Interaction.response

unkempt canyonBOT
#

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.

rough shuttle
#

like this?

await discord.InteractionResponse.defer(interaction.followup.send_message(f"Ticket created in <#{channel.id}>"), ephemeral=True)

final iron
#

huh

slate swan
final iron
sick birch
rough shuttle
sick birch
rough shuttle
#

ohh okay, thank you

sick birch
#

interaction.response gives you an instance of discord.InteractionResponse, so you can use the .defer() method on that

rough shuttle
sick birch
#

how do you have an interaction object if this is a prefix command pithink

rough shuttle
#

oh wait it's a hybrid command

slate swan
#

then its ctx.defer()

#

!d discord.ext.commands.Context.defer

unkempt canyonBOT
#

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.
rough shuttle
final iron
#

huh

#

You always get an interaction object for select menus

#

No matter how they’re invoked

rough shuttle
final iron
#

And why cant you defer with the InteractionResponse object?

lean shard
#

Off topic, what’s the advantage to using pycord or other discord bot libraries?

slate swan
#

||The fix is to not use hybrid commands||

lean shard
#

Why did you spoiler that?lol

slate swan
sick birch
#

I don't think pycord has a very good reputation

edgy plinth
#
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

slate swan
#

since its starting at 0 you need to subtract 1 from the length

edgy plinth
#

forgot that quirk

slate swan
#

does it work when you try to place it for example at second position?

slate swan
#

since it doesnt place it last where does it

edgy plinth
#

first

slate swan
#

and how many text channels are there in this category

edgy plinth
#

currently 2

slate swan
#

and what is the value of length

edgy plinth
#

2

slate swan
#

i see you print that already

#

so it should work

edgy plinth
#

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)
slate swan
#

you still dont subtract 1 do you

edgy plinth
#
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

slate swan
#

weird

slate swan
#

anyone know why the image aint appearing in the embed

#

this is replit btw

slate swan
#

And you're missing an f for your f-string fyi

slate swan
#

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)
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

5
slate swan
#

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?

slate swan
lean shard
final iron
lean shard
#

Oh, that’s a huge problem and 100% a reason not to support their code

drowsy thistle
#

Question how do I add options to hybrid slash commands?

final iron
drowsy thistle
final iron
#

huh

drowsy thistle
#

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

final iron
#

Probably not with hybrid commands

drowsy thistle
#

There are 3 commands, help, botinfo, and serverinfo

final iron
#

Enums are generally immutable

drowsy thistle
#

so I have to do manually ig

final iron
#

Or don't use a hybrid command for this

drowsy thistle
#

well the thing tbh is I want it to be prefix and slash command compatible for most commands

final iron
#

You can still do that...

drowsy thistle
final iron
#

You can just create 1 prefix command, and 1 slash command

drowsy thistle
#

oh it wont interfere?

final iron
#

No?

#

Why would it

drowsy thistle
#

I thought it would say that the comand already exists

final iron
#

Why

#

They're 2 separate types of commands

drowsy thistle
#

oh ig then sure why not, thanks

#

also cute penguin, (dont shoot me tho)

young dagger
final iron
void mauve
#

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
void mauve
final iron
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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.
void mauve
#

oh ic

#

thanks

drowsy thistle
#

is discord having issues

warm whale
#

If I had a bot that sent a message then waited 15 seconds then edited that message can i do that?

final iron
drowsy thistle
final iron
#

Has nothing to do with discord having issues lol

drowsy thistle
#

then whats that for

final iron
#

Invalid Form Body

drowsy thistle
#

Yea but it used to work exactly nothing vhanged?

final iron
#

Are you asking for help to solve it

drowsy thistle
#

Yea

#

idk why it started showing this thing out of a sudden

final iron
#

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.

rough shuttle
#

how to increase void time in discord py, for example the default is 3 seconds, how can I increase it to 10-15

sick birch
rough shuttle
sick birch
rough shuttle
#

oh okay

slate swan
#

wish HelpCommand was generic :-(

desert kiln
#

I smell, feminine men

dim solar
#

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

slate swan
slate swan
#

That's how you make slash commands, read it

agile idol
#

How to set wealcomer and wealcome message in channel

agile idol
#

Helo?

unkempt canyonBOT
#

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.
young dagger
agile idol
#

How to make embed announcement

unkempt canyonBOT
#
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...
slate swan
young dagger
slate swan
#

That's what I said

#

Use both

#

Disnake also has some of those built-in

#

!d disnake.ext.commands.Bot.getch_user

unkempt canyonBOT
#

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.
slate swan
#

e.g. that

#

Not sure why it doesn't have for channels as well but whatever

young dagger
slate swan
#

Yeah well, unfortunate for them

#

Usually channels get cached pretty fast, but not always the case so yeh

young dagger
#

Why?

slate swan
brazen geyser
#

hey guys, how can i make command group in cog?

slate swan
#

This channel is made for library design, choices, etc. questions

brazen raft
#

And this channel has never been that way

#

Oh I'm dumb you meant the foreign channel

#

I thought you were answering

young dagger
#

My bad Disnake works the same way. The returned channel or None if not found.

drowsy thistle
#

I am here again to see which is better

young dagger
#

The first one

hot sparrow
#

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

spark nimbus
#

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?

final iron
brazen geyser
#

hey guys, can someone please tell me whats wrong? First time working with command class in cog

rough shuttle
#

How to turn a select menu back to it's placeholder after selecting an option?

hot sparrow
#

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

sick birch
brazen geyser
sick birch
#

can you show us the entire reload class

sick birch
brazen geyser
#

like this

    intents = discord.Intents().all()
    super().__init__(command_prefix = commands.when_mentioned_or(prefix), intents = intents)```
sick birch
#

yeah but the arguments are different

#

I think you can get away with not passing any

brazen geyser
#

so just

    super().__init__()```
#

or am i wrong?

sick birch
#

should be fine

#

try it out and let me know

rough shuttle
brazen geyser
velvet compass
sick birch
brazen geyser
brazen geyser
velvet compass
#

(it is a more in-depth explanation of those terms in general, Robin's explanation for your case here is a good summary)

brazen geyser
hushed galleon
# hot sparrow but how do i include only some of them to be used depending on custom logic, bec...

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
true vector
#

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')
shrewd fjord
unkempt canyonBOT
#

@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...
true vector
shrewd fjord
#

Hmm ;-;?

true vector
#

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')
true vector
# shrewd fjord Hmm ;-;?

If i remove and message.author.has_permissions.administrator: it does print but then everyone can print

final iron
#

It’s a decorator for commands, which you should be using

true vector
#

I dont want to for this specific purpose. Is there a way around that ? And still being able to limit it to admin ?

final iron
#

Why don’t you want to?

true vector
#

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

hushed galleon
#

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)

unkempt canyonBOT
#

@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.
true vector
#

thats wicked that fixes alot for me thanks

true vector
hushed galleon
#

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

true vector
#

hmm ok, because I tried discord.js for a hot minute and they registered instantly

hushed galleon
#

what discord.py code do you have to sync your commands?

true vector
#
@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

hushed galleon
#

hm, not the best practice but that seems functional

#

does it say Synced {n} commands when you start the bot?

true vector
#

yes

hushed galleon
#

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

true vector
#

they do, but I took discord like 5min now to register the delall command

hushed galleon
#

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

true vector
#

ffs

#

hmm ok, guess Ill have to live with that. Now I just gotta figure out my slash commands

harsh orbit
#

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?

final iron
final iron
odd path
#

bot maker....and here I just wrote my discord bot from scratch.

sick birch
odd path
slate swan
#

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

tepid wadi
#

I need help. First time writing a bot. The bot is online, but does not respond to command.

livid hedge
#

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?

livid hedge
#

I believe tho you could have to enable discord message intents

sick birch
#

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)

sick birch
livid hedge
livid hedge
sick birch
livid hedge
#

sounds like I will have to create an array of games and players (well in a structurated way)

livid hedge
#

thank you, Robin

sick birch
#

no prob

unreal gazelle
#

**I am available to work for you on your projects at a very cheap price ** ActiveDeveloperBadge

sick birch
golden portal
#

tbh you should just get a job with higher pay tho

final iron
#

there are websites for this anyway

drifting arrow
#

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

final iron
#

This is something extremely easy to implement yourself

drifting arrow
#

I know, I was just hoping for something simpler lol

odd path
#

yeah that confused me just a little

slate swan
#

does anyone knows if there’s a way i can host 2 or more discord bots for free?

drifting arrow
#

How do you @ roles?

sick birch
drifting arrow
#

i meant using discordpy

sick birch
#

!d discord.Role.mention

unkempt canyonBOT
sick birch
#

All mentionables have a .mention property

mint walrus
#

I’ll pay someone 20$ to recreate this discord bot (I have screenshots of the commands and what they are suppose to do)

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

harsh orbit
#

when you insert any bot token in it the bot will work in some code like "autoline" or anything

dusk knoll
#

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

slate swan
#

Compare that with your line

dusk knoll
#

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!

brazen raft
dusk knoll
#

Yeah I figured that

round maple
#

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?

slate swan
#

You haven't enabled the message content intent, so you won't receive any message content

round maple
#

so just intents.messages = True?

slate swan
#

I said message content, not messages

round maple
#

oh

#

so message_content?

slate swan
#

tias

round maple
#

so yes?

slate swan
#

Try it and see

round maple
#

gives off and error

slate swan
#

Read the error and do what it says

round maple
#

i did

#

the bot has admin perms

slate swan
#

Intents are not permissions

#

Read the error again

shadow vigil
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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.

vale wing
#

For free? 😏

young dagger
#

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}%")```
slate swan
#

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

young dagger
gray edge
#

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

young dagger
#

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%")```
slate swan
hot sparrow
#

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() OkayuThonk

golden portal
golden portal
hot sparrow
uneven arch
#

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

shrewd fjord
#

What exactly doesn't work

vale wing
#

And of course, please describe what doesn't work and attach traceback if you got any

fiery cairn
#

Is discord.ui outdated?

#

Or no? For doing modals and forms and all

shrewd fjord
unkempt canyonBOT
#

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...
fiery cairn
#

Thanks

#

Just to check bc I know some are outdated and not rlly supported at all

shrewd fjord
#

Use @bot.listen() instead of @bot.event

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@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...
slate swan
fiery cairn
#

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?

fiery cairn
#

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)
final iron
#

tias

ebon island
#

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! ❤️

ebon island
#

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.

final iron
ebon island
#

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

final iron
#

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

ebon island
#

btw thank you for the response ❤️

final iron
#

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

sick birch
#

classic

final iron
#

most dedicated Pycord developer

ebon island
#

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?

final iron
#

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

unkempt canyonBOT
#

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.
sick birch
#

looks like disnake didn't change the cog system from discordpy

ebon island
#

Oh excellent! That is great news

final iron
slate swan
#

Does Pycord have a bad rep or something?

#

I only ever used dpy

ebon island
#

I looked at dpy docs and didn't see obvious slash command decorator though, did I overlook it?

final iron
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
slate swan
final iron
#

The specific decorator would be

#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@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.
ebon island
#

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

sick birch
#

or, well, an application command

#

discordpy has a container called a "command tree" that holds information about all application commands

ebon island
#

oooh interesting, so in this case application command is synonymous with what I'd consider slash command?

sick birch
#

so are context menus

ebon island
#

and command tree object stores those in a way that is communicated to discord

sick birch
ebon island
#

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?

sick birch
#

context menus aren't all that complex so no, I'm afraid

ebon island
#

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?

sick birch
#

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

ebon island
#

Cool!

#

I'm excited to give it a try, I guess it's settled, I'll be using dpy

sick birch
#

not sure if my brain is just blanking or that's the only two types of application commands, though

ebon island
#

I expect I can check documentation now that I know what I'm looking for

#

thank you very much btw! 🙂

sick birch
#

no prob, have fun

final iron
thorny summit
#

Can anyone who is familar with Python come to dm's and help me with a script? I cant send it all here 😭

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the 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.

thorny summit
#

Okay thank you here

#

I need help fixing this dropdown

slate swan
#

We need help knowing what's not working

thorny summit
#

The dropdown doesn't show

final iron
#

Selects have to be added to discord.ui.View's first, and then pass into the view kwarg

#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
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...
final iron
#

Notice how view is supposed to be an instance of discord.ui.View

thorny summit
#

Oh yeah

#
dropdown_message = await ctx.send("Choose a resource to add to your backpack:", discord.ui.View)
#

It's not this is it?

final iron
#

no

#

you need an instace of discord.ui.View, or a subclass

#

View the examples in the repo for a proper implementation

thorny summit
#

.. Sorry I don't know what any of it means 😭

unreal pilot
#

hi

#

user/server premium subscriptions

unreal pilot
#

perm banned

#

god knows why

unreal pilot
final iron
unreal pilot
#

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

unreal pilot
#

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

snow coral
#

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

golden portal
# snow coral So i made a game and it works fine, but the bot doesn’t pick up some words, i su...

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

slate swan
void mauve
#

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
        )
sick birch
void mauve
#

ok, thought I could do it with some kind of function inside the class

sick birch
#
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

vale wing
naive briar
#

Good

shrewd apex
#

sensitive area 💀

void mauve
#

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]))
unkempt canyonBOT
#
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.

void mauve
# naive briar !traceback
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'
golden portal
void mauve
golden portal
#

hmm error suggested that you passed in view into send_message, but ion see it there

#

did you changed it?

naive briar
#

It's an entirely different file

void mauve
#

so thats the problem?

naive briar
#

You didn't init the class?

void mauve
golden portal
#

the ChooseChoicesView

#

didnt call it

naive briar
void mauve
#

oh wait

#

i see lmao

#

well thanks very much for noticing

vale wing
#

👄👁️👄

spark nimbus
#

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)

vale wing
#

And what's your working directory

spark nimbus
#

asyncio.run(main())

vale wing
#

Make sure it's max bot and not root

vale wing
spark nimbus
vale wing
#

!workdir

#

Too bad there's no such tag

spark nimbus
vale wing
#

No, command line is python main.py

spark nimbus
#

i am running that with vscode

vale wing
#

Yeah and vscode does that

#

Please send what line it uses to run the project

vale wing
#

Nah bro

#

I mean from terminal

spark nimbus
#

so what do you mean by that

vale wing
#

Tbh yk what

spark nimbus
vale wing
#

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

spark nimbus
#

ok

vale wing
#

Also move main out of cogs

#

Or is it not there

#

I can't quite see

spark nimbus
#

it is not in cogs

golden portal
void mauve
spark nimbus
vale wing
#

Your venv is not configured I assume

#

Have you moved the venv

spark nimbus
#

it is the interpreter

vale wing
#

?

golden portal
void mauve
vale wing
vale wing
#

Screenshot please

spark nimbus
vale wing
#

Full

spark nimbus
vale wing
#

Mm pretty sure previous installation ended up with error

spark nimbus
#

no

#

worked fine

vale wing
#

Well there's clearly red text in your terminal

#

Don't you see

spark nimbus
#

now i see it

#
Consider using the `--user` option or check the permissions.```
vale wing
#

Also it seems you somehow tried installing it globally

spark nimbus
#

do you know how can i change this?

vale wing
shrewd apex
#

weird venv seems to be activated tho

spark nimbus
#
Consider using the `--user` option or check the permissions.``` same error
vale wing
#

Screenshot how you used pip install pls

spark nimbus
#

looked the rror

#

error
it says need admin premmisions gave the vscode and now it installed it

vale wing
#

It might be that the venv is broken if it's not newly created

spark nimbus
#

but discord is still not resolved

vale wing
#

The only possible situation when it may happen is your venv is broken and it fallbacks to global pip

shrewd apex
#

just add the --user flag when installing and give it a try

spark nimbus
#

ok 1 sec

shrewd apex
#

how did u make the venv tho?

vale wing
#

Try

  1. Killing terminal
  2. Deleting the venv and creating new via py -3.11 -m venv venv
spark nimbus
vale wing
shrewd apex
#

ah venv issue

shrewd apex
vale wing
spark nimbus
shrewd apex
#

why would someone install 3.8 after 3.11 ;-;

vale wing
spark nimbus
vale wing
#

All ML libs are stuck at 3.9 max 💀

shrewd apex
#

hmm no?

#

i used a lot of popular ones at 3.10 and 11

vale wing
#

Well at least ones I'm familiar with

shrewd apex
#

not sure which libs ur talking abt

vale wing
#

Tensorflow

shrewd apex
vale wing
#

Dunno

#

I remember struggling with tf installation cause of python version

shrewd apex
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the 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.

vale wing
#

Maybe it was directml

spark nimbus
#

thx i forgot about thtat

vale wing
#

It's client.start, not run

spark nimbus
#

ohhhhh

#

lmao i am so badd

vale wing
#

I think

spark nimbus
#

working thx

shrewd apex
left dew
#

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("-"))]
vale wing
#
if re.fullmatch(r"(?:\d+ \w+(?:, )?)+", your_input)
#

I think that's the thing

left dew
unreal pilot
#

It was a bit tricky to figure out at first with sending heartbeats and stuff

left dew
#

could you explain more?

vale wing
left dew
#

items is the list with what can be inputted e.g items = [“apples”, “bananas”….

vale wing
#

That can be done either via injecting it into regex pattern or by filtering them after searching

#

First method is more efficient imo

left dew
#
        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

vale wing
#

You are using on_message for commands processing?

#

😭

left dew
#

for what im trying to do yes

slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

['൫']
slate swan
vale wing
#

Regex moment

#

Gotta use [0-9] 😭

slate swan
left dew
#

sooooo

slate swan
#

so if this pattern was correct r"(?:\d+ \w+(?:, )?)+" use r"(?:[0-9]+ \w+(?:, )?)+" instead

left dew
slate swan
#

!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"))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 100 apples
002 | 100 bananas
left dew
#

but that doesnt check if the inputted values are correct and in the items list

slate swan
#

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

left dew
#

thats the part im having issues with, the validating part

slate swan
#

match.group("amount") is the amount and match.group("item") is the item

slate swan
#

when is the value correct

left dew
#

when the value is correct it just proceeds, if not it sends and error message

slate swan
#

why can't I get the ID of the webhook message?

vale wing
# left dew when the value is correct it just proceeds, if not it sends and error 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))
unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | False
002 | False
003 | True
004 | False
vale wing
#

Damn my regex is bad

slate swan
#

x

#

d

vale wing
#

!e

a = ["bananas", "apples"]
print(rf"(?:[0-9]+ {'|'.join(a)}[, ]*)+")```
slate swan
vale wing
#

@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)
unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | True
002 | False
vale wing
#

Can put that thing into regex101 and it will explain what each construction does

left dew
vale wing
#

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
left dew
#

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)```
vale wing
#

Just pass the whole arguments string

#

Also for god's sake use commands framework

left dew
vale wing
#

on_message hurts hard

left dew
#

its the best

vale wing
#

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

left dew
#

or is it just text

vale wing
#

No you can't, it is a string, not instance of Message

left dew
#

have a nice christmas

slate swan
#
  id = int(id)
         ^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
slate swan
vale wing
#

Please provide full traceback

slate swan
# vale wing Don't see this line anywhere in your code


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'```
unreal pilot
#

first of all

#

refrain from using builtin types are var names

#

just do _id f.e.

vale wing
unreal pilot
#

2nd, id does not have a value

unreal pilot
vale wing
#

Nah it's just that nobody cares about id function

unreal pilot
#

ik, but its still bad practice

unreal pilot
unreal pilot
#

meaning your passed id is incorrect

#

to get the admins message

vale wing
unreal pilot
#

this is where your error is at

unreal pilot
#

fetch_message didnt return a discord.Message object

#

webhookmessage*

slate swan
vale wing
unreal pilot
#

want to see how i fetch my messages which returns None?

#

for an incorrect message id

slate swan
vale wing
#

Ok good luck figuring this out 👌

unreal pilot
slate swan
#

@vale wing@unreal pilot I deleted the highlighted code and everything worked

maiden fable
#

Ig because there was another condition which wasn't being fulfilled due to an absence of else block? Idk that's what explains it

slate swan
maiden fable
#

Wait what the heck why are u tryna edit the module files.....?

unreal pilot
#

for an actual proper solution xd

#

seems like Object(self.channel.id) is None

#

very odd

unreal pilot
vale wing
#

You might have found a bug 🤯

hushed galleon
#

a bug in py-cord that is

naive briar
#

Great

hushed galleon
#

according to the git blame it looks like a 2 year old bug as well

#

remember kids, don't be a lazy type-hinter!

hushed galleon
left dew
#

what does this error mean?
TypeError: View.to_components() missing 1 required positional argument: 'self'

slate swan
hushed galleon
#

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)

left dew
#

i just forgot the brackets on my view

slate swan
#

how use self?

hushed galleon
# slate swan how use self?

that's a bug in their documentation, self is automatically given when you call the method on an Embed instance

hushed galleon
#

what about it?

slate swan
#

when edit message

hushed galleon
#

ah, you'll need to copy whatever name it had beforehand

slate swan
hushed galleon
#

yeah something like that

slate swan
lean shard
lean shard
#
  1. Since the interaction fails on my SessionAction buttons, the disable function doesn't pop off
  2. 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

shrewd vapor
#

Hello, how use Cogs and slash command inside ?

lean shard
hushed galleon
# lean shard Hello! if anyone's around, would they be willing to look at my code in https://d...

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())```

lean shard
hushed galleon
#

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

lean shard
#

interesting and slightly annoying

#

I see you using on_click, assuming that's a builtin method?

hushed galleon
shrewd vapor
#

How make slash commands in cog ?

hushed galleon
shrewd vapor
#

Oh ok ty

lean shard
shrewd vapor
#

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 ?

hushed galleon
shrewd vapor
#

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 ?
hushed galleon
#

in other words you should add the cog in setup_hook() instead

shrewd vapor
#
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 ?
hushed galleon
#

the bot.tree.sync you had earlier was correct

shrewd vapor
#

mb

hushed galleon
#

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

shrewd vapor
#

I don't need to call the function ? she call herself ?

hushed galleon
#

@bot.event is assigning the setup_hook method to your bot which lets discord.py call it automatically

shrewd vapor
#

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...

hushed galleon
#

uhh you shouldn't have to wait that long...

shrewd vapor
#

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)```
hushed galleon
#

seems fine to me, maybe try restarting discord to see if your command shows up?

shrewd vapor
#

Ok i try

#

Oh yes work ty

robust finch
#

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()```
graceful ermine
#

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)
golden portal
pale zenith
drifting arrow
#

How can I make a discordbot wait for a button press when I DM the bot?

graceful ermine
midnight oracle
#

How good and flexible is that "Pycord" library?

sick birch
midnight oracle
#

And I wanna implement that in mine, but I have no clue how to get started in the discord.py for multilingual options

sick birch
#

interesting

midnight oracle
#

I thought about a json with the text in different langs

sick birch
#

that would indeed be one way

midnight oracle
#

0.o

#

any advice xd?

hushed galleon
agile idol
#

how to do slash cmd?

blazing condor
# agile idol how to do slash cmd?

i know of 2 main ways

  • using discord.Client and manage the commanTree on your own

  • Using discord.ext.commands.Bot and using cogs to create the commands.

i would recommend using commands.Bot and cogs

blazing condor
agile idol
blazing condor
agile idol
#

helo

#

how set like this

final iron
agile idol
#

mention and auto repond

final iron
#

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

agile idol
#

icant understand

#

what code use this

final iron
#

Are you asking for the code for it?

agile idol
#

yess

agile idol
final iron
#

This is a server meant for learning. Nobody is going to spoonfeed you the code

agile idol
#

hmm

final iron
#

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

vale wing
#

As a comically large spoon feeder I confirm

unkempt canyonBOT
#
Microsoft Visual C++ Build Tools

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.

twilit nymph
#

good time to all i have a quick question .... is yt_dlp better than yt_dl for music functions in adiscord bot ?

slate swan
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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)
pale zenith
twilit nymph
cinder mauve
#

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

sick birch
#

we don't recommend using ChatGPT if you're new, by the way

cinder mauve
# sick birch feel free to ask any specific questions you may have here

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

vague junco
#
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?

fast musk
#

looks to be the correct format. Is there an error that is causing your exception clause to kick in?

vague junco
fast musk
#

yup. I tend to like to use discord's error handlers instead of try/excepts in the command handlers though

fast musk
#

yeah

#

that is just a personal preference though

#

The code will work as is

vague junco
fast musk
#

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 😄

vague junco
#

Hehe

graceful ermine
sick birch
graceful ermine
final iron
#

You can just use the round function

graceful ermine
drifting arrow
#

How do i setup a "wait for button press" event?

#

i've tried several different things and nothing works ;-;

hushed galleon
unkempt canyonBOT
#

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()```
hushed galleon
#

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

drifting arrow
#

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? 🤔

sick birch
#

each button has it's own function so it should be pretty easy

midnight oracle
#

kinda long number

slate swan
#

Read the message again, it's exactly what they asked for

midnight oracle
#

oh xd

void mauve
#

Guys, does Modals support discord.ui.Select?

slate swan
#

No

#

!d discord.ui.TextInput

unkempt canyonBOT
#

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.
slate swan
#

Only that

void mauve
#

I see

#

can I make autocompletion for text input?

slate swan
#

No

void mauve
#

well thats sad

slate swan
#

Can set a default value and placeholder, that's it

void mauve
#

thanks

candid flume
#

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?

golden portal
candid flume
# golden portal 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()

golden portal
golden portal
# candid flume 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:'

candid flume
#

i wanted to delete the channel that has been created after joining

golden portal
#

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

candid flume
golden portal
#

you can just avoid that entirely by casting to str to get the name

candid flume
#

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

golden portal
#

what code did you tried?

candid flume
#

literally just passing category=id in the tempchan = await after.channel.clone(name=f'{member.name}\'s Channel')

golden portal
candid flume
#

gotcha

#

appreciated very much, thank you

golden portal
#

welcome

candid flume
# golden portal 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?

golden portal
candid flume
#
@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

golden portal
#

the if statement is still error prone here str(after.channel.name), should just be str(after.channel)

candid flume
#

ah, i see sorry read the previous statement wrong, 3 am atm ahah

golden portal
#

oke, incase you miss it in the docs

tepid dagger
#

how do you check if a discord.Member isi a bot

midnight oracle
#

How do i send two messages in one Interaction?

#

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:

slate swan
#

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

unkempt canyonBOT
#
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**.
fiery girder
#

how can i fix this

#

i need to check the user if its same but it is not letting me do it

slate swan
#

!d discord.ui.Button

unkempt canyonBOT
#

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.
slate swan
#

Has no user attribute

fiery girder
#

its a class view

#

but i want to check if the interaction is from a specific user

#

how do i check that then

slate swan
#

I'd be a good idea to show your code

fiery girder
#

yea sure

#

oh it gliched again wait lemme do the fix

#

@slate swan ?

slate swan
#

No need to double ping, not your 24/7 support agent

fiery girder
#

ok jeez

slate swan
#

Switch interaction and button

fiery girder
#

?

unkempt canyonBOT
#

examples/views/confirm.py line 30

async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
fiery girder
#

oh interaction comes first

slate swan
#

Could've guessed by the error saying your interaction is a Button and not an Interaction

old vine
#

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!'
slate swan
#

And, where are you stuck?

#

We don't code for you, we help with your errors etc.

old vine
#

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

slate swan
#

!e

print(len("Question 3: Users from how many countries are on our Discord server?"))
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

68
slate swan
#

The max length of the label is 45 characters

old vine
#

!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?))```
slate swan
#

I literally already did it, why flooding the channel with nonsense

old vine
#

pyprint(len("How many members did our r/IGCSE subreddit gain in 2023?"))

slate swan
#

Your label for question 3 is like 68 characters long, it should be max 45

young dagger
#

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)```
spark nimbus
#

how can i check in a server if there is a channel named for example:"random-channel-name"

fading marlin
#

You can use utils.get and Guild.text_channels

slate swan
pale zenith
#

Utils.get is better though

slate swan
#

yes

young dagger
pale zenith
#

Or similar. You may need to add extra checks depending on what you wanna do

young dagger
pale zenith
#

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.

hushed galleon
# midnight oracle But I'm getting this error: ``` INFO - bot : Inicialidado com...

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)

young dagger
sick birch
# young dagger 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

young dagger