#discord-bots

1 messages · Page 244 of 1

dry kelp
shrewd vapor
#

How to send modal ?

upbeat gust
shrewd vapor
#

i don't understand how to send

upbeat gust
#

did you read the example??

shrewd vapor
#

Yes

#
class ButtonTicket(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None
    
    @discord.ui.button(label = "Open Ticket", style = discord.ButtonStyle.green)
    async def open_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
        guild = interaction.guild
        c = discord.utils.get(guild.categories, name="TICKET")
        for channel in guild.channels:
            if channel.name == f"ticket-{interaction.user.name}":
                await interaction.response.send_message(f"You have already a ticket <#{channel.id}>", ephemeral = True)
                return

        reason = discord.ui.TextInput(
            label='Reason',
            placeholder='Reason open ticket here...',
            required=True,
            max_length=300,
        )
        reason.send_modal(interaction)
        
        interacted, result = await reason.wait()
        if not interacted:
                return
        
        ticket_channel = await interaction.guild.create_text_channel(f'ticket-{interaction.user.name}', category = c)
        overwrite = discord.PermissionOverwrite()
        overwrite.send_messages = False
        overwrite.read_messages = False
        await ticket_channel.set_permissions(interaction.guild.get_role(interaction.guild.id), overwrite=overwrite)

        await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True)

        await interaction.response.send_message(f"Your ticket is <#{ticket_channel.id}>", ephemeral = True)
        embed = discord.Embed(title="Ticket", description="Please wait support will be with you shortly.", colour=interaction.user.colour)
        embed.add_field(name="Created By:", value=f"{interaction.user.name}", inline=True)
        embed.add_field(name="Reason:", value=f"{result}", inline=True)
        embed.set_footer(text=f"{guild.name}", icon_url=interaction.user.display_avatar)
        await ticket_channel.send(f"<@{interaction.user.id}>")
        await ticket_channel.send(embed=embed)
        if database_ticket.get_channel(interaction.guild.id) is None:
            return
        channel_send = database_ticket.get_channel(interaction.guild.id)
        embed_log = discord.Embed(title = f"Ticket created by {interaction.user.name}", description = f"Reason: {result}\nChannel: <#{ticket_channel.id}>")
        await channel_send.send(embed=embed_log)```
This is my code
upbeat gust
#
        reason = discord.ui.TextInput(
            label='Reason',
            placeholder='Reason open ticket here...',
            required=True,
            max_length=300,
        )
        reason.send_modal(interaction)```

Where did you get this code? this is not how it works, please see the example
glad summit
#

Hello

shrewd vapor
#

I don't understand example bruh

upbeat gust
# shrewd vapor I don't understand example bruh

When someone explains something and you respond simply with "wdym" or "I don't understand", that is extremely unhelpful. It tells us nothing about which part you didn't understand or how we can target the explanation to help you. It roughly translates to

Please re-explain everything and pick random different words in the hopes that I get it this time.

Ask targeted questions about what you did not understand. If you didn't understand anything, split it up into individual parts and ask about one at a time specifically.

shrewd vapor
#

Bro i'm tired 4h morning here

upbeat gust
#

then sleep???

shrewd vapor
#

I try resolve my bot before

upbeat gust
#

ok

shrewd vapor
#

I break my pc

#

I don't understand how to use modal

upbeat gust
#

what dont you understand

shrewd vapor
#

How to initialise and send

#

Sry if my english is not good i'm french

upper ether
#

i wanna create a channel in which a member gets banned automatically if they send a message

#

any idea how ?

dry kelp
#

Was able to do it, But out of this how can i pull out the time the user went away? like 1 sec ago, 1 hour ago, 1 day ago, 1 month ago, 1 year ago?

upper ether
naive briar
#

Are you making spam bots?

#

That's kinda weird

upper ether
naive briar
#

No one would do it like that

naive briar
upper ether
unkempt canyonBOT
#

examples/modals/basic.py lines 70 to 75

@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):
    # Send the modal with an instance of our `​Feedback`​ class
    # Since modals require an interaction, they cannot be done as a response to a text command.
    # They can only be done as a response to either an application command or a button press.
    await interaction.response.send_modal(Feedback())```
shrewd vapor
#

ok thanks, i go sleep and i see tomorow

#

Good night

molten hare
#

!d urllib

unkempt canyonBOT
#

Source code: Lib/urllib/

urllib is a package that collects several modules for working with URLs...

shrewd vapor
#

hi

#

from discord import ui don't work

naive briar
#

That explains nothing

#

Send the traceback or something, not just It'S nOt WoRkInG

vale wing
#

You can check its source on my github

shrewd vapor
#

I don't have traceback is just don't recognize

vale wing
shrewd vapor
#
class ButtonTicket(discord.ui.Modal, title = "Ticket"):
    def __init__(self):
        super().__init__()
        self.value = None
    
    reason = discord.ui.TextInput(
            label='Reason',
            placeholder='Reason open ticket here...',
            required=True,
            max_length=300,
        )
    buttons = [{"label": "Open Ticket"}]

    async def on_submit(self, interaction: discord.Interaction):
        guild = interaction.guild
        c = discord.utils.get(guild.categories, name="TICKET")
        for channel in guild.channels:
            if channel.name == f"ticket-{interaction.user.name}":
                await interaction.response.send_message(f"You have already a ticket <#{channel.id}>", ephemeral = True)
                return
        ticket_channel = await interaction.guild.create_text_channel(f'ticket-{interaction.user.name}', category = c)
        overwrite = discord.PermissionOverwrite()
        overwrite.send_messages = False
        overwrite.read_messages = False
        await ticket_channel.set_permissions(interaction.guild.get_role(interaction.guild.id), overwrite=overwrite)

        await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True)

        await interaction.response.send_message(f"Your ticket is <#{ticket_channel.id}>", ephemeral = True)
        embed = discord.Embed(title="Ticket", description="Please wait support will be with you shortly.", colour=interaction.user.colour)
        embed.add_field(name="Created By:", value=f"{interaction.user.name}", inline=True)
        embed.add_field(name="Reason:", value=f"{reason}", inline=True)
        embed.set_footer(text=f"{guild.name}", icon_url=interaction.user.display_avatar)
        await ticket_channel.send(f"<@{interaction.user.id}>")
        await ticket_channel.send(embed=embed)
        if database_ticket.get_channel(interaction.guild.id) is None:
            return
        channel_send = database_ticket.get_channel(interaction.guild.id)
        embed_log = discord.Embed(title = f"Ticket created by {interaction.user.name}", description = f"Reason: {reason}\nChannel: <#{ticket_channel.id}>")
        await channel_send.send(embed=embed_log)

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)```
How can i get the output modal named reason for put in on_submit ?
vale wing
#

You need to from discord.ui import Thing or import discord and then refer by discord.ui.Thing

shrewd vapor
#

ok

naive briar
vale wing
radiant bough
#

How do I get the permissions required by bot and user to run x command?

slate swan
#

For the user, it's entirely up to you - though common sense says that to use a ban command the user should have the ban members permission.

formal basin
#
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
     await interaction.response.defer()
     await interaction.channel.purge(limit=amount)
     await interaction.followup.send(f"deleted {amount} messages")
``` this doesnt work properly
slate swan
#

Coolio, "don't work" is vague

formal basin
#

Like it doesn’t purge

#

It just sends the message

slate swan
#

Can anyone help??

rugged shadow
slate swan
#

How? (im new)

radiant bough
slate swan
#

Hi new

slate swan
#

Getting the permissions of the user for the current channel?

#

You have ctx.author.guild_permissions available

radiant bough
slate swan
#

Probably better to get a global error handler for that then

#

Then you check if the error is instance of MissingPermissions or BotMissingPermissions

#

There you will have the missing_permissions attribute available

crude geyser
#

Hello how to make the commands of his bot discord appear in the corresponding commands - quick commands in Python?

vale wing
unkempt mauve
vale wing
#

!d discord.Role.mentionable

unkempt canyonBOT
unkempt mauve
#

ohhh thanks

echo lagoon
#

Made me write code on phone on dpy server, only to find it's already solved .-. Else was gonna mention the same thing..

Only came here by chance tbh

thin raft
#

don't name variables ilke keywords

dry kelp
#

If 1 users goes afk it will stop working till the afk user returns

slate swan
#

Error pretty much says all

swift acorn
#
class initialapplybutton(View):
    def __init__(self):
        super().__init__(timeout=None)
        
    @button(label="Apply", style=discord.ButtonStyle.green, custom_id="3")
    async def initialapplybutton(self, interaction: discord.Interaction, button: Button):
        await interaction.response.send_message("""**PLEASE NOTE!**

In order to start your application, you will need to join our Creator Applications Discord server. Please only join the server if you are SERIOUS about applying and will actually apply!

If you join the server and don't submit an application, you will be **permanently banned** from our official Stumble Guys Discord servers and you won't be able to apply to our Content Creator Program in the future.

If you have read this and would like to proceed to apply, please click on the ✅ below this message.""", ephemeral=True, view= confirminvitebutton())

Hello, I wanted to ask how I can add another button to this other than the confirminvitebutton?

slate swan
#

Create a view

swift acorn
#

How 😅

slate swan
#

confirm.py has 2

#

tic_tac_toe.py has 9

swift acorn
#

ah okay got it so a button in the same class instead of a whole new class

#

I was doing that

#

Tysm it works

native grove
#

This seems like the best place for this
Is it against TOS to write an application that changes my prescence based on what song im listening to on youtube music?
if not, what would be the proper way to set the rpc?

echo lagoon
plucky sun
#

how to set perms to channel: role = interaction.guild.get_role(1106962573145940070) await interaction.channel.set_permissions(role, read_messages=False) read_messages=False not work 😦

#

HELP

#

@vocal snow

slate swan
#

You probably want to use overwrites

oak warren
#

wait nvm

#

yea you use overwrites

vale wing
#

!pypi discord-rich-presence seems like an easy lib to use for presence

unkempt canyonBOT
vale wing
plucky sun
vale wing
#

That's usually the case

oak warren
#

read the example ?

plucky sun
#

yes

oak warren
#

i mean its pretty explanatory

#

you edit channel and add the overwrites dict to the overwrites parameter

slate swan
#

Sometimes searching on your own is useful, especially when learning

vale wing
slate swan
#

why my clear command is not working?

lean harbor
#

What's the line of code which describes the / command

slate swan
#

it's suppose to delete my other clears

formal basin
#
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
     await interaction.response.defer()
     await interaction.channel.purge(limit=amount)
     await interaction.followup.send(f"deleted {amount} messages")```
#

this doesn't work

#

it sends the message but doesn't purge anything

lean harbor
#

Whats the line of code to give the slash command a description

plain pollen
#

there's a keyword-arg you can pass the @app_commands.command decorator to set it, iirc

#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
plain pollen
#

description

lean harbor
#

alright thanks

lean harbor
#

Whats this error?

#

nvm fixed sos

slate swan
#

basically i have some bot code and have it on repl, how would i make the code popup that blank website thing (something along the lines of projectname.repl.co) so i can use it to host the bot on a seperate website/VPS

#

Hey anyone here?

#

Can help me?

#

with what

slate swan
slate swan
lean harbor
#

How would you make the description be at the top and have a colon after galleon price and strong scroll price?

slate swan
#

Hmm I have made 1 mute cmd in my bot in that I have write that ctx.guild.roles(name="Muted")
And when I am running my codeit showing discord don't have any attribute guild

slate swan
slate swan
#

cause im making a bot for a discord server not a public

naive briar
slate swan
naive briar
#

Or something, definitely not a context though

slate swan
#

but like i said i need to figure out the repl link thing

slate swan
slate swan
naive briar
#

Don't try to use replit to host your bot

slate swan
slate swan
slate swan
naive briar
#

Even if you get it to work, you'd be rate limit someday

slate swan
#

i just need it running for my server lmao

slate swan
#

there is also why you should not use replit to host bot

naive briar
formal basin
naive briar
#

Forgor to unreply

naive briar
#

No, it wasn't for you

slate swan
#

alr

slate swan
# slate swan show code so we can help
@commands.command()
  @commands.has_permissions(manage_roles=True)
  async def mute(ctx, self, user:discord.Member, duration="1m"):
    mute_role = discord.utils.get(ctx.guild.roles, name="Muted")

It's that part and see last line

slate swan
# slate swan <@675507024930537473>

i just have this at the top of my code and it seems to work, if yours isnt the same that might be why

import os
import discord
from discord.ext import commands
from discord.utils import utcnow

client = commands.Bot(command_prefix="d=", intents=discord.Intents.all())
naive briar
slate swan
unkempt canyonBOT
#
Class instance

When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.

class Foo:
    def bar(self):
        print('bar')

    def spam(self, eggs):
        print(eggs)

foo = Foo()

If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.

Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').

Why is this useful?

Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.

Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.

slate swan
#

@naive briar what I have to write instead of guild ;-;

slate swan
slate swan
slate swan
slate swan
#

Wait lemme explain

slate swan
slate swan
naive briar
#

Just retry it after changing the self argument position

slate swan
#

did you fix the self not being first argument?

slate swan
lean harbor
#

@bot.tree.command(name="suggest", description="Make a suggestion")
async def suggest(ctx: commands.Context, suggestion: str):
    suggestion_channel_id = 1106959842901504060

    suggestion_channel = bot.get_channel(suggestion_channel_id)
    if suggestion_channel is None:
        print(f"Could not find channel with ID {suggestion_channel_id}")
        return

    embed = discord.Embed(title="Suggestion", color=discord.Color.blurple())
    embed.add_field(name="User ID", value=str(ctx.author.id))
    embed.add_field(name="Suggestion", value=suggestion)

    await suggestion_channel.send(embed=embed)
    await ctx.send("Your suggestion has been submitted!")

When doing /suggest it says: The interaction did not respond

Error: discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'

#

does anybody know how to fix?

slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
#

not author

#

its Interaction not Context

#

in slash commands

naive briar
lean harbor
#

confused

naive briar
#

What's so hard to understand about it

lean harbor
slate swan
lean harbor
#

although i shouldn't be laughing, i am

slate swan
#

first of all you dont get Context in slash commands you get Interaction

lean harbor
#

ok

formal basin
#

@slate swan py @client.tree.command(name="clear", description="clear messages (moderator only)") @discord.app_commands.checks.has_permissions(manage_messages=True) @app_commands.default_permissions(manage_messages=True) async def clear(interaction: discord.Interaction, amount: int): await interaction.channel.purge(limit=amount) await interaction.response.defer() await interaction.followup.send(f"deleted {amount} messages") print(f"deleted {amount} messages") some reason this works

formal basin
#

order: purge, defer, followup

slate swan
#

Hey like my bot made Muted role then it have to change perms then this code will added?

for channel in ctx.guild.channels:
        await channel.set_permissions(mute_role, send_messages=False)
formal basin
lean harbor
naive briar
slate swan
slate swan
naive briar
#

It's useless now

slate swan
lean harbor
#

aight

slate swan
slate swan
slate swan
formal basin
slate swan
formal basin
#

if i take it off

lean harbor
# slate swan then show the error instead
@bot.tree.command(name="suggest", description="Make a suggestion")
async def suggest(interaction: discord.Interaction, suggestion: str):
    suggestion_channel_id = 1106959842901504060

    suggestion_channel = bot.get_channel(suggestion_channel_id)
    if suggestion_channel is None:
        print(f"Could not find channel with ID {suggestion_channel_id}")
        return

    embed = discord.Embed(title="Suggestion", color=discord.Color.blurple())
    embed.add_field(name="User ID", value=str(ctx.author.id))
    embed.add_field(name="Suggestion", value=suggestion)

    await suggestion_channel.send(embed=embed)
    await interaction.response.send_message("Your suggestion has been submitted!")

Like this?

slate swan
lean harbor
# slate swan got an answer

discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: NameError: name 'ctx' is not defined

??

slate swan
#

it says that you need to pass Member or Role object

#

Hm

slate swan
#

what type is it

naive briar
north kiln
#

Replit being replit

lean harbor
slate swan
slate swan
slate swan
lean harbor
slate swan
formal basin
slate swan
#

python just trolling

formal basin
#

makes no sense

naive briar
#

Why are you keep replying to me

slate swan
formal basin
slate swan
#

Role object

slate swan
naive briar
#

Print it or isinstance

slate swan
#

by printing its type to the console

#

Huhhhhhh 🗿

formal basin
#

oh waiit it depends on how much amount i put

#

could i do an if statement?

#

i try

#

how could i do a if statement for more than a number

#

example 5 +

shrewd apex
#

what is it for tho?

formal basin
#

but its slash

slate swan
formal basin
shrewd apex
#

oh i thought he wanted like 5 if statements

slate swan
shrewd apex
slate swan
shrewd apex
#

just a sec ill link u

slate swan
#

no i got the link

#

do i just copy it

lean harbor
#

Not sure why the bot can't find the message

error: discord.app_commands.errors.CommandInvokeError: Command 'accept' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message

code:

@bot.tree.command(name="accept", description="Accept or decline a suggestion")
async def accept(interaction: discord.Interaction, suggestion_id: int, accepted: bool, reason: str):
    suggestion_channel_id = 1106959842901504060  # Replace with the ID of the channel where suggestions were submitted

    suggestion_channel = bot.get_channel(suggestion_channel_id)
    if suggestion_channel is None:
        print(f"Could not find channel with ID {suggestion_channel_id}")
        return

    # Retrieve the suggestion message based on the suggestion ID
    suggestion_message = await suggestion_channel.fetch_message(suggestion_id)
    if suggestion_message is None:
        print(f"Could not find suggestion message with ID {suggestion_id}")
        return

    # Retrieve the user who made the suggestion
    user = suggestion_message.author

    if accepted:
        acceptance_message = f"Your suggestion with ID {suggestion_id} has been accepted.\n\nReason: {reason}"
    else:
        acceptance_message = f"Your suggestion with ID {suggestion_id} has been declined.\n\nReason: {reason}"

    # Send a direct message to the user with the acceptance/decline message and reason
    await user.send(acceptance_message)

    await interaction.response.send_message("Suggestion status updated and notification sent to the user!", ephemeral=True)

formal basin
#
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
  if amount < 2:
     await interaction.channel.purge(limit=amount)
     #await interaction.response.defer()
     await interaction.response.send_message(f"deleted {amount} messages")
     #await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
     print(f"deleted {amount} messages")
  if amount > 2:
     await interaction.response.defer()
     await interaction.channel.purge(limit=amount)
     await interaction.response.followup(f"deleted {amount} messages")
     #await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
     print(f"deleted {amount} messages")
``` it is deleting my followup msg
shrewd apex
#

!d discord.Interaction.followup

unkempt canyonBOT
formal basin
# shrewd apex !d discord.Interaction.followup
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
  if amount < 2:
     await interaction.channel.purge(limit=amount)
     #await interaction.response.defer()
     await interaction.response.send_message(f"deleted {amount} messages")
     #await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
     print(f"deleted {amount} messages")
  if amount > 2:
     await interaction.response.defer()
     await interaction.channel.purge(limit=amount)
     await interaction.followup.send(f"deleted {amount} messages")
     #await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
     print(f"deleted {amount} messages")
``` I fixed it but it is still deleting my followup message
shrewd apex
#
@client.tree.command(name="clear", description="clear messages (moderator only)")
@app_commands.checks.has_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: app_commands.Range[int, 10, None]) -> None:
    """
    Purge command to delete messages from a channel.
    
    Parameters
    ----------
    interaction: discord.Interaction
        The Interaction
    amount: app_commands.Range[int, 10, None]
        A positive integer with minimum 10 and maximum of no limit.
    """
    await interaction.response.defer()
    await interaction.channel.purge(limit=amount)
    await interaction.followup.send(f"deleted {amount} messages", ephemeral=True)
shrewd apex
#

nah

#

its not possible cuz purge happens before message is sent

#

plus followup is ephemeral

lean harbor
shrewd apex
#

a bot cannot delete ephemeral messages

formal basin
shrewd apex
lean harbor
shrewd apex
#

also put user.send in a try except

#

if user has dms closed it will raise an error

lean harbor
shrewd apex
#

!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 "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.
lean harbor
shrewd apex
#

@unkempt canyon

#

ded

shrewd apex
lean harbor
# shrewd apex .

why would i edit it? when i want to send a accepted message to the user#

shrewd apex
#

defer says to discord wait a few moments i will respond to it
edit then acts as a response to the command

#

404 rises in 2 cases the

  • ur over 3 secs in responding
  • the message was deleted
lean harbor
shrewd apex
#

yeah

dry kelp
#

Quick question

lean harbor
dry kelp
#

I built a AFK command yesterday, today i noticed an error

shrewd apex
dry kelp
shrewd apex
dry kelp
#
    @slash_command()
    async def afk(
        self, inter: disnake.ApplicationCommandInteraction, reason: str = None
    ):
        """
        Set your status to AFK.

        Parameters
        ----------
        reason: Reason for going AFK.
        """

        if reason:
            if len(reason) > 100:
                embed = report_embed(
                    False,
                    description="Limit of reason lenght is at 100 characters!",
                )
                await inter.send(embed=embed, ephemeral=True)
                return
            set_reason = reason
        else:
            set_reason = "They went to shit."

        database_guild = await fetch_db_guild(inter.guild.id)
        afk = await AfkModel.get_or_none(
            guild_id=database_guild, discord_id=inter.author.id
        )

        if afk:
            await afk.update_from_dict({"reason": set_reason})  # Update
        else:
            await AfkModel.create(
                guild_id=database_guild, discord_id=inter.author.id, reason=set_reason
            )

        if inter.author != inter.guild.owner:
            await inter.author.edit(nick=f"[AFK]{inter.author.display_name}")
        await inter.send(
            f"Set your status to AFK with reason: `{set_reason}` {format_dt(utcnow(), style='R')}"
        )
lean harbor
dry kelp
dry kelp
#
class AfkModel(Model):
    """AFK Model."""

    guild_id = OneToOneField("Bot.Guild")
    discord_id: int = BigIntField(null=False)
    reason = TextField(null=False)
    time = DatetimeField(auto_now_add=True)
#

It's a onetoonefield set to guild

#
    @Cog.listener()
    async def on_message(self, message: Message):
        user_db = await AfkModel.get_or_none(
            discord_id=message.author.id, guild_id=message.guild.id
        )

        if user_db:
            if message.author != message.guild.owner:
                await message.author.edit(nick=message.author.name)

            await message.reply(
                f"Welcome back {message.author.mention}! "
                f"You went afk - {format_dt(user_db.time, style='R')}"
            )
            await user_db.delete()

        if message.mentions:
            if message.author.id == self.bot.application_id:
                return

            user = await AfkModel.get_or_none(
                discord_id=message.mentions[0].id, guild_id=message.guild.id
            )

            if user:
                member = message.guild.get_member(user.discord_id)
                await message.reply(
                    f"**{member.display_name}** is AFK because: `{user.reason}` "
                    f"{format_dt(user.time, style='R')}"
                )
#

and my on_message is pretty simple

shrewd apex
#
await interaction.response.defer(ephemeral=True)
await interaction.edit_original_response(embed=embed)

@lean harbor

shrewd apex
#

means only 1 per table

lean harbor
# shrewd apex ```py await interaction.response.defer(ephemeral=True) await interaction.edit_or...
@bot.tree.command(name="accept", description="Accept or decline a suggestion")
async def accept(interaction: discord.Interaction, suggestion_id: int, accepted: bool, message: str):
    suggestion_channel_id = 1106959842901504060  # Replace with the ID of the channel where suggestions were submitted

    suggestion_channel = bot.get_channel(suggestion_channel_id)
    if suggestion_channel is None:
        print(f"Could not find channel with ID {suggestion_channel_id}")
        return

    # Retrieve the suggestion message based on the suggestion ID
    suggestion_message = await suggestion_channel.fetch_message(suggestion_id)
    if suggestion_message is None:
        print(f"Could not find suggestion message with ID {suggestion_id}")
        return

    # Retrieve the user who made the suggestion
    user = suggestion_message.author

    if accepted:
        acceptance_message = f"Your suggestion with ID {suggestion_id} has been accepted.\n\nMessage: {message}"
    else:
        acceptance_message = f"Your suggestion with ID {suggestion_id} has been declined.\n\nMessage: {message}"

    # Send a direct message to the user with the acceptance/decline message and reason
    try:
        await user.send(acceptance_message)
    except discord.errors.HTTPException:
        print(f"Failed to send a direct message to the user with ID {user.id}")

    await interaction.response.defer(ephemeral=True)
    await interaction.edit_original_response(embed=embed)

Like this?

shrewd apex
#

primary is unique + not null

dry kelp
shrewd apex
lean harbor
#

aight

dry kelp
#

And it's not set to pk, and on tortoise docs OneToOneField won't set it automatically to pk

shrewd apex
#

its not pk ik that the error says its a unique key

#

not primary key

lean harbor
shrewd apex
lean harbor
#

sh.

dry kelp
lean harbor
#

cough cough

shrewd apex
#

🗿

dry kelp
lean harbor
#

it doesn't work it just says Galleon is thinking

#

discord.app_commands.errors.CommandInvokeError: Command 'accept' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message

shrewd apex
#

if it were me i would declare PRIMARY KEY (guild_id, user_id)

shrewd apex
#

its likely from this line

    suggestion_message = await suggestion_channel.fetch_message(suggestion_id)
#

whats the whole traceback

dry kelp
#

I didn't even know u can set 2 as primary keys

shrewd apex
shrewd apex
shrewd apex
dry kelp
#

but yeah i understood what u mean

shrewd apex
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
dry kelp
#

what if i use get_or_none

shrewd apex
#

its likely suggestion id is wrong

dry kelp
#

worth a try x)

lean harbor
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

lean harbor
#

thats the full code

shrewd apex
#

nah check ur message id

#

either that also make sure bot has perms to that channel

lean harbor
#

?

shrewd apex
#

whats a suggestion id lmao

lean harbor
#

how else i'm i supposed to tell the bot which one to accept?

shrewd apex
#

lmao no

lean harbor
#

?

shrewd apex
#

u cant fetch a message using that

#

fetch_message needs a message id

lean harbor
#

;-;

dry kelp
#

Asher could u help me after?

lean harbor
#

how i'm i supposed to fetch it

shrewd apex
#

if its raw sql i can write u the table

#

no idea about django sorry

dry kelp
#

using tortoise

shrewd apex
#

yeah i can

lean harbor
shrewd apex
#

write the table for it

shrewd apex
lean harbor
#

ah right

dry kelp
#

Ill dm u with the entire table, is that fine?

#

Entire model file

shrewd apex
#

@lean harbor u need to rework ur suggestion system

shrewd apex
dry kelp
#

👍

shrewd apex
#

i can however write a table sample and send it

dry kelp
shrewd apex
#
"""
CREATE TABLE IF NOT EXISTS afk (
    user_id BIGINT,
    guild_id BIGINT,
    reason TEXT DEFAULT "No reason provided.",
    PRIMARY KEY (user_id, guild_id)
);
"""
#

here is a sample

#

i generally just use asyncpg

dry kelp
#

wish it was raw, i understand ur logic tho and i get what u mean

#

but using tortoise that would be harder 😂

#

that's what creates the shema

shrewd apex
#

postgres ftw

dry kelp
lean harbor
# shrewd apex postgres ftw

asher quite question, how would i make the description be above the galleon price and strong scroll price? I'm using a database to the get the description

shrewd apex
unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
shrewd apex
#

inline property

lean harbor
shrewd apex
#

, inline=False) ?

lean harbor
#

cool thnaks

#

sorry dumb question

tulip frigate
#

what should I use to handle discord oauth application in my dashboard? Zuora ? Currently I use quart and better-ipc

sick birch
#

Usually with Auth.js

tulip frigate
#

and sending it to the api then

sick birch
#

Sending what to which API?

tulip frigate
#

sending the information of the user to the quart api

sick birch
#

Yeah something along those lines works

#

The server can also access cookies

#

So if you've got a JWT in there for instance, you have access

tulip frigate
#

alright, ill think about that, thank you very much

formal basin
#
if warns_amt == > 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)
```it says this is invalid syntax
#

how?

#

the if statement

#

the 6

meager chasm
#

== >

#

what in the world is that

formal basin
meager chasm
#

that is not valid python

formal basin
#

do you mean the "=="

meager chasm
#

<= is less than or equal to

#

>= is greater than or equal to

#

this is quite essential python knowledge you should have before making a discord bot

formal basin
#

ohhhhhhhhghhhhhhhhhhhhhhhh i understand now

formal basin
#

instead of >=

meager chasm
#

that is "greater than"

#

6 >= 6 is True but 6 > 6 is False

swift acorn
#

How do I get a message's link that makes you jump to it in discord.py?

shrewd apex
unkempt canyonBOT
swift acorn
#

thank you

plucky sun
#

code : ```@discord.ui.button(label='Save', style=discord.ButtonStyle.green, emoji=':page_with_curl:')
async def menu2(self, interaction, button: discord.Button):
role = discord.utils.get(interaction.guild.roles, id=826071242317627402)
if role not in interaction.user.roles:
await interaction.response.send_message("You are not staff. You can't save the ticket!",ephemeral=True)
return
emb = discord.Embed(colour=discord.Colour.random())
emb.set_author(name=f"Date: {datetime.datetime.now()}")
emb.add_field(name=interaction.channel.name, value=f'Saved by {interaction.user}')
transcript_channel_id = 893175113623695450
transcript_channel = bot.get_channel(transcript_channel_id)

    messages = []
    async for m in interaction.channel.history():
        messages.append(f'{m.author}: {m.content}\n')
    messages = numpy.flip(messages)
    allMessages = ''
    for msg in messages:
        allMessages += msg
    emb.add_field(name='Messages:', value=allMessages)
    emb.set_footer(text=f"{interaction.guild.name}",icon_url={interaction.guild.icon})
    await transcript_channel.send(embed=emb)
    emb = discord.Embed(colour=discord.Colour.blue())
    emb.set_author(name=f"ticket was saved by {interaction.user}")
    await interaction.channel.send(embed=emb)``` error: ```

Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\KokoG\PycharmProjects\Logger\Tests\test2.py", line 96, in menu2
await transcript_channel.send(embed=emb)
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```

#

how to fix

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.

edgy plinth
#

Im trying to use app commands and i cant find the name of the thing when do can select from a menu within the slash command, does anyone know the name of it? would be greatly apricated.

slate swan
#

Choices?

edgy plinth
#

maybe

potent spear
#

also, only the async for loop is needed...

smoky sinew
#

is it possible to make the library use a custom subclass of InteractionResponse

smoky sinew
#

choices and literal are best for options that don't change while your program is running, and autocomplete is better from data that is dynamic such as data you get from a database

potent spear
hushed galleon
#

afaik only a few classes get that sort of treatment, the rest of dpy's models cant be replaced without modifying the library directly

smoky sinew
#

hmm there should be an API to manage model classes

potent spear
#

orrrr you're having an XY problem

hushed galleon
#

wouldnt play well with typehints, e.g. Client.users returns list[User] which would be incorrect if you replaced the User model

smoky sinew
#

doesn't user include everything extending it

smoky sinew
potent spear
hushed galleon
#

from the type checker's perspective you're only allowed to use the API provided by User, even if it was a subclass at runtime

shrewd apex
#

fork dpy

potent spear
#

ah yes, and make breaking changes while doing so 🙂

shrewd apex
#

i dont have much issues with dpy except i dont like its slash command impl and perhaps access or a few more additional lower level events

hushed galleon
#

ive tried using generic typehints for models in a separate library of my own, but it didnt help at all and i ended up repeating all the typehints + type ignores

shrewd apex
shrewd apex
#

works 100%

hushed galleon
#

if you really wanted to change the API i think forking is the most reasonable choice, but of course that's harder to maintain than making some wrapper class or functions for stuff you need

shrewd apex
#

true

hushed galleon
shrewd apex
#

once u fork with major changes u have walked a path of no return

shrewd apex
hushed galleon
#

hm how does disnake handle that

shrewd apex
#

has this issue tracking it

shrewd apex
#

based on view components

hushed galleon
#

oh is that it? dispatching some function based on a static custom id? why would using a view be an issue?

shrewd apex
#

apparently saves memory for small views

shrewd apex
#

thats one another bad experience i have had was previously during developement they left a memory leak which they only found out after a few months

#

with the views

hushed galleon
#

oh wait did disnake actually implement a convenient API for having state in custom id?

shrewd apex
#

i spent so much time messing with gc

smoky sinew
hushed galleon
shrewd apex
#

yeah but with the view lib handles gateway events that dosent happen stateless

#

u gotta do it urself

hushed galleon
#

i dont get what you mean

shrewd apex
#

with views the lib stores more method calls attributes and data in short

#

not that much of a difference but yeah slight memory saving

hushed galleon
#

for the first statement persistency is different from dynamic custom ids, persistent views have existed for a while but afaik dynamic ids havent escaped dpy's bikeshedding phase

hushed galleon
shrewd apex
hushed galleon
shrewd apex
#

imma go sleep now

#

4 am here ae_PepeSleepy

#

gn

hushed galleon
#

gnighty

hushed galleon
smoky sinew
#

yes

#

that would be much better

gusty flax
#

I need help with one of my parameters for creating an automod rule.

#

the trigger parameter.

plain pollen
#

what about it? yknow people can't know to fix the exact problem till u say it :P

gusty flax
#

Im reading the docs and it is referencing a AutoModRuleTriggerType

#

so I passed it that, but it isn't the AutoModTrigger type that they are asking for

plain pollen
#

it looks like AutoModRuleTriggerType is just an enum for specifying what sorta filter it is exactly

#

and the docs for AutoModTrigger seem to specify which params are actually important for each trigger type

smoky sinew
gusty flax
gusty flax
#

Yeah wait, there isn't a rule arg.

smoky sinew
#

it's an argument to AutoModTrigger

#

!d discord.AutoModTrigger

unkempt canyonBOT
#

class discord.AutoModTrigger(*, type=None, keyword_filter=None, presets=None, allow_list=None, mention_limit=None, regex_patterns=None)```
Represents a trigger for an auto moderation rule.

The following table illustrates relevant attributes for each [`AutoModRuleTriggerType`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoModRuleTriggerType "discord.AutoModRuleTriggerType")...
smoky sinew
#

also i meant type

gusty flax
plain pollen
gusty flax
#

Oh. Yes, I tried passing it in, but I got another error.

#

ill send it

gusty flax
# smoky sinew also i meant type
Traceback (most recent call last):
  File "C:\Users\hgold\PycharmProjects\lang_bot\venv\lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "C:\Users\hgold\PycharmProjects\lang_bot\lang\ext\cogs\automod.py", line 14, in spam
    await interaction.guild.create_automod_rule(name="Spam",
  File "C:\Users\hgold\PycharmProjects\lang_bot\venv\lib\site-packages\discord\guild.py", line 4024, in create_automod_rule
    actions=[a.to_dict() for a in actions],
  File "C:\Users\hgold\PycharmProjects\lang_bot\venv\lib\site-packages\discord\guild.py", line 4024, in <listcomp>
    actions=[a.to_dict() for a in actions],
AttributeError: '_EnumValue_AutoModRuleActionType' object has no attribute 'to_dict'```
#
@group.command(name="spam")
    async def spam(self, interaction: Interaction, enabled: bool) -> None:
        await interaction.guild.create_automod_rule(name="Spam",
                                                    event_type=AutoModRuleEventType.message_send,
                                                    trigger=AutoModTrigger(type=AutoModRuleTriggerType.spam),
                                                    actions=[AutoModRuleActionType.block_message], enabled=enabled)
plain pollen
#

i think it wants actions to be of type AutoModRuleAction, rather than AutoModRuleActionType

smoky sinew
#

oh hm you can just pass AutoModRuleAction()

gusty flax
#

Oh shoot ur right, I didn't realize there was a differnet error message.

plain pollen
#

(and looking at the d.py source, the type actually gets decided by which kwargs you pass)

gusty flax
#

Oh wait yeah I read that like a couple of hours ago.

#

If I want it to block the message, I think u just don't provide any params right?

plain pollen
#

seems that's how you do it yeah

smoky sinew
#

huh that's kind of a weird default

#

why doesn't it just default to[AutoModRuleAction()] then

gusty flax
#

Aight got it to work.

limpid sinew
#
@bot.listen('on_message_edit')
async def on_message_edit(before, after):
            if "swear word" in after.content:
                await message.delete()
#

I'm pretty new to python, how would I fix this so that when a message is edited to a certain word, the message is deleted?

pine nexus
#

ok new problem pertaining to async functions

#

so I set up a function which basically counts until it reaches a set value

#

problem is, this is at the end of an iterated function

#

and the function doesn't move on to the next iteration

gusty flax
#

Also, how can I add a description to the params in a slash command?

slate swan
unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
gusty flax
#

kk tysm

limpid sinew
smoky sinew
#

oh it should be after.delete then

pine nexus
#

ok so my bot is iterating a function and the function ends with an async function. The async function is preventing the iteration from ending and starting the next

#

how can I run the async function while still moving to the next iteration

slate swan
#

!e ```py
import asyncio

async def fn_taking_time():
await asyncio.sleep(5)
print("time taking")

async def other_fn():
print("other")

fns = [fn_taking_time(), other_fn()]

async def main():
for coro in fns:
asyncio.create_task(coro)

asyncio.run(main())

unkempt canyonBOT
#

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

other
drifting arrow
#

how will this new change to discord names affect discordpy?

slate swan
#

they'll probably just remove the .discriminator attribute after deprecating it to return 0 for a while

limpid sinew
#
import discord

def run_discord_bot():
    TOKEN = '**************************'
    client = discord.Client()

    client.run(TOKEN)

@bot.listen('on_message_edit')
async def on_message_edit(before, after):
            if "swear word" in after.content:
                await after.delete()

What do i need to do to define bot?

slate swan
#

!d discord.ext.commands.Bot

and you shouldnt have both client and bot instances

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
vale wing
slate swan
#

Hey can anyone tell me why this error is coming??????

vale wing
#

Remove the brackets after @bot.event

slate swan
#

Ok

shrewd apex
shrewd apex
naive briar
#

I mean, why do you need to remove the on before the event name

idle lantern
#

how do i bypass a global check for some commands?

shrewd apex
#

i thought on was removed 😔 i am too lazy to open source

naive briar
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 "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
naive briar
#
@bot.listen('on_message')
async def my_message(message):
    print('two')

pithink

#

It's personal preference, I guess

shrewd apex
#

perhaps

#

is there an enum for the events

vale wing
#

!d disnake.Event

unkempt canyonBOT
#

class disnake.Event(value)```
Represents all the events of the library.

These offer to register listeners/events in a more pythonic way; additionally autocompletion and documentation are both supported.

New in version 2.8.
vale wing
#

Disnake best

north kiln
#

trying to implement ui stuff and got flashbacks from when I first started trying slash commands

slate swan
#

Hey can anyone help me in this error?

#

@vale wing can you help me

north kiln
#

why use timeout_for?

#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
slate swan
#

Hmm

#

I tried this

#

But ....

slate swan
#

@north kiln hey can you explain it please I dont get it

north kiln
#

what needs to be explained

#

what do you want to do

#

show your code

rustic onyx
#

is on_message the only way to listen to messages? I'm interested in messages from only one channel.

vocal snow
#

yes, on_message will listen to messages from all visible channels

#

there's no way for a single channel listener, just use an if statement

rustic onyx
#

okay, so now I've another question if you dont mind, how can I know what decorator to use, I'm in a cog

#

and standard @bot.event wont work

vocal snow
#

!d discord.ext.commands.Cog.listener

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
rustic onyx
#

thanks, worked 🙂

rustic onyx
#

is it possible to get the channel id with the name channel

#

cause on message - message.channel gives you the name of the channel

#

not the id

rustic onyx
#
    async def on_message(self, message):
                
        if message.author == self.bot:
``` isnt this enough to avoid message recursion?
#

cause it doesnt seem to work

meager chasm
#

what's inside the if statement?

rustic onyx
#

return

naive briar
#

No full code moment

rustic onyx
#

mb

naive briar
rustic onyx
#

avoiding recursion

#

if the bot is the author, I want to ignore the message by returning

slate swan
#

from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash

#

i installed it many times

#

i updated too

naive briar
slate swan
#

someone can help?

rustic onyx
#

if message.author == self.bot:
this condition is not met

slate swan
naive briar
#

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

``import discord
from discord.ext import commands
from discord_slash import SlashCommand

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

bot = commands.Bot(command_prefix='!', intents=intents)
slash = SlashCommand(bot, sync_commands=True)

@bot.event
async def on_ready():
print(f'Zalogowano jako {bot.user.name}')

@slash.slash(name="hello", description="test")
async def przywitaj(ctx):
await ctx.send('witaj! <3.')

@bot.event
async def on_slash_command(ctx):
await bot.process_commands(ctx)

bot.run('censored)``

#

where i can add it?

meager chasm
#

add what

slate swan
#

sorry, i am a beginner and i dont know very much about python

naive briar
#

You should at least have basic knowledge of Python to be comfortable with discord.py

#

Or whatever fork you maybe using

slate swan
#

ok

slate swan
naive briar
violet canopy
#

Are there any bots in this server in #bot-commands that work using Python? I’d be interested to try them out

naive briar
#

You mean, are they written in Python?

violet canopy
#

Yeah

meager chasm
#

!source

unkempt canyonBOT
violet canopy
#

I want to see what a Python bot does

meager chasm
violet canopy
#

Perfect, thanks

naive briar
#

🐈

violet canopy
#

So that bot is coded in Python, and helps the Python server 😎

echo lagoon
silent ridge
#

is it just me or do you guys also have this after discord update?

#

that discord doesn’t process the * and the _ in the text?

hushed galleon
shrewd apex
#

either that's the reason or u made some mistake with formatting

silent ridge
# hushed galleon can you share the exact text you used in your description? i cant reproduce it
  embed = nextcord.Embed(
    title="Verification BirdSupply",
    description=
    "By clicking the verify button down below you agree that: \n \n - You agree with  [#1054496495937794149](/guild/267624335836053506/channel/1054496495937794149/) \n - When trying to mislead us, we will ban you. \n - You follow the rules of discord [ToS](https://discord.com/terms). \n \n **The password to enter the server is __birdsupply__**",
    color=0x2f3136)
  embed.set_footer(text="Make sure to verify yourself within 1 day, else you will get kicked!", icon_url="https://cdn.discordapp.com/icons/1000710577716469820/535923a1c6dc11930b821a3ef0e82167.png?size=4096")
  await verificationChannel.send(embed=embed, view=view)```
silent ridge
golden portal
#

just remove the space between \n and **The password

silent ridge
#

lol

#

thanks

golden portal
#

tried every single configuration to repro that tbh

blazing flint
#
@app_commands.command(name="move", description="Moves the inputted number of messages to the inputted thread.")
@app_commands.describe(number="The number of messages to move.")
@app_commands.describe(thread="The name of the thread to move the messages to.")
async def move(interaction: discord.Interaction, number: int, thread: str):```

If my commands are formatted like this, how should I be auto syncing in setup_hook?
#

I havent coded bots in a while

#

I am trying to make one with out cogs

sick birch
blazing flint
#

I make bots global

#

is just calling client.tree.sync() in setup_hook enough

sick birch
#

Yeah should just be a await bot.tree.sync() then
However be advised these may take up to one hour to propagate

sick birch
#

You're good then

blazing flint
#

@client.event
async def setup_hook():
await client.tree.sync()

blazing flint
#

Are you sure I am doing it right

sick birch
#

Yeah like I mentioned global commands take up to an hour to propagate

slate swan
#

That's old, nowadays it's instant

sick birch
#

Oh is it?

slate swan
#

Took up to an hour few years ago

blazing flint
#

yeah that's what happened with my other bots

#

I was using files to organize my commands in

sick birch
#

Try syncing it to a specific guild, then

blazing flint
#

and cogs

#

I guess I will just do thaat

sick birch
#
async def setup_hook():
  guild = discord.Object(id=123)
  client.tree.copy_global_to(guild=guild)
  await client.tree.sync(guild=guild)
#

iirc

slate swan
#

Also you can use describe with commas and describe multiple parameters in a single decorator

blazing flint
#

oh

round jewel
#

is there a max amount of parameters for a slash command?

north kiln
#

25

round jewel
#

alr thanks

slate swan
#

gather doesnt process in order @shrewd apex

blazing flint
#

I have a list of messages

#

Is it possible to move them to a thread

north kiln
#

at most is the bot sending the same messages in a thread I guess

#

you can't really "move" them

blazing flint
#

I though there was a way

shrewd apex
#

time to scroll

slate swan
#

how can i check has role in ctx?

#

i only know how to do that in tree

#

@commands.check_has.role(role id)

#

like that?

thin raft
slate swan
thin raft
#

yup

velvet sierra
#

someone know why i'm getting the error: 'NoneType' object has no attribute 'url'?

server = bot.get_guild(123456789...)
embed = discord.Embed(title='...')
embed.set_author(name='...')
embed.set_thumbnail(url=server.icon.url)
#

sounds like i cant set the icons of guilds as thumbnails of embeds anymore

vocal snow
#

!d discord.Guild.icon

unkempt canyonBOT
vocal snow
#

Optional[Asset]

slate swan
#

how to make bot remove role

#

in @eternal girder

sick birch
unkempt canyonBOT
#

await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate swan
#

kk ty

slate swan
#

not defined

#

oh nvm

#

mb im dumb

#

await discord.Member.remove_roles(role_name)

#

it dont remove the role

north kiln
#

You don't directly use discord.Member.remove_roles

#

You use it on a member object

slate swan
slate swan
north kiln
#

Whose roles are you removing?

#

Did you pass it on your command?

unkempt mauve
slate swan
#

named "alt"

slate swan
#

role_name = ("alt")

unkempt mauve
#

consider showin full code tho

unkempt mauve
slate swan
north kiln
#

You are deleting a role?

#

!d discord.Role.delete

unkempt canyonBOT
#

await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Deletes the role.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
unkempt mauve
#

he is removing

slate swan
#

didnt work

#

with the role id

jovial cape
#

Is there a channel where I can advertise my Python to Rust discord bot translation service?

slate swan
#

its saying expired and remove from the mongo data base but it dont remove the role from the member

slate swan
north kiln
#

What's that lol

#

Why do ppl need to rewrite bots in rust

vocal snow
#

so they can be blazing fast and fearlessly concurrent !

shrewd vapor
#

Hi

jovial cape
shrewd vapor
#
@bot.tree.command(name = "add-scamlist", description = "Add user in scamlist")
async def add_scamlist(interaction, member: discord.User, reason: str):
    if (interaction.user.id == 944574924234846298):
        await interaction.response.defer()
        try:
            with open("scamlist.json", "r") as f:
                exist = json.load(f)
                identifiant = exist.get('id')
                reason_exist = exist.get('reason')
                if (member.id == identifiant):
                    embed_exist = discord.Embed(title = "Member is already in scamlist", description = f"Reason: {reason_exist}")
                    await interaction.followup.send(embed=embed_exist)
                    return
                else:
                    with open("scamlist.json", "w") as f:
                        data = {
                            "id": member.id,
                            "name": member.name,
                            "reason": reason,
                            "server": interaction.guild
                        }
                        json.dump(data, f)
                        embed = discord.Embed(title = "User add in Scamlist", description = f"{member} add in scamlist for {reason}")
                        await interaction.followup.send(embed=embed)
        except:
            embed_error = discord.Embed(title = "Error", description = "An error has occurred please try again later")
            await interaction.response.send_message(embed=embed_error)
    else:
        await interaction.response.send_message("Only owner bot can use this command")```

I search check if member.id already exist in scamlist.json but i don't know how i can check for all id in .json
jovial cape
#

If not just loop over id's and check one by one

shrewd vapor
#

Yes is ordered

jovial cape
shrewd vapor
#

{"id": 944574924234846298, "name": "icetea࿐#2752", "reason": "test", "server": "My server"}

jovial cape
#

oh alright

#

You'll need to serialize objects with id and check each

#

I'd recommend pre serializing objects and creating a list with the ids

#

Then doing user_id in id_list

shrewd vapor
#

How to create a list ?

vocal snow
#

[] or list()

shrewd vapor
#

How i can while in json for get only all id ?

jovial cape
#

You can use a set as well

vocal snow
#

do you want to get all IDs from your JSON file?

shrewd vapor
#

yes

vocal snow
#

if so, just use a for loop and append the id key of each item to a list

#

a list comprehension would be a short way of doing it

#
[item["id"] for item in data]
shrewd vapor
#

Oh i see

#

I try

vocal snow
#

if you haven't used list comprehensions before it might be better to stick to a normal for loop to avoid confusing yourself

formal basin
#

yo would this work l = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "] blockedwords = ["idiot", f"i{l}d{l}i{l}o{l}t", "dum", f"d{l}u{l}m", "stupi", f"s{l}t{l}u{l}p{l}i", "fat", f"f{l}a{l}t", "sucker", f"s{l}u{l}c{l}k{l}e{l}r", "loser", f"l{l}o{l}s{l}e{l}r", "nerd", f"n{l}e{l}r{l}d"]

north kiln
#

Why would it

formal basin
north kiln
#

Unless you want to block
'i[q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]d [q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]i [q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]o [q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]t'

thin raft
#

import string left the chat

formal basin
formal basin
shrewd vapor
#

How i can all info for one id in my .json ?

#

{"id": 944574924234846298, "name": "icetea࿐#2752", "reason": "test", "server": "My server"}

glad cradle
blazing flint
shrewd vapor
#
@bot.tree.command(name="remove-scamlist", description="Remove user in scamlist")
async def remove_scamlist(interaction, id: str, reason: str):
    if interaction.user.id == 944574924234846298:
        await interaction.response.defer()
        try:
            with open("scamlist.json", "r+") as f:
                scamlist_data = json.load(f)

            if id in [entry["id"] for entry in scamlist_data]:
                scamlist_data = [entry for entry in scamlist_data if entry["id"] != id]
                
                json.dump(scamlist_data, f, indent=4)

                embed_remove = discord.Embed(title="Member is removed from scamlist", description=f"Reason: {reason}")
                await interaction.followup.send(embed=embed_remove)
                guild_id = interaction.guild.id
                if database_scamlist.get_channel(guild_id) is None:
                    return
                channel_send = database_scamlist.get_channel(guild_id)
                embed_rm = discord.Embed(title = "User remove in ScamList", description = f"<@{id}> is removed in ScamList")
                embed_rm.add_field(name = "Reason:", value = f"{reason}")
                channel_send.send_message(embed=embed_rm)
            else:
                embed = discord.Embed(title="Member not found in scamlist", description=f"ID: {id}")
                await interaction.followup.send(embed=embed)
        except:
            embed_error = discord.Embed(title="Error", description="An error has occurred, please try again later")
            await interaction.followup.send(embed=embed_error)
    else:
        await interaction.response.send_message("Only the bot owner can use this command")```
#

2023-05-23 20:57:22 ERROR discord.app_commands.tree Ignoring exception in command 'remove-scamlist'
Traceback (most recent call last):
File "/home/container/otrobot.py", line 503, in remove_scamlist
scamlist_data = json.load(f)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 3 column 2 (char 8)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 524, in remove_scamlist
await interaction.response.send_message(embed=embed_error)
File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 751, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'remove-scamlist' raised an exception: InteractionResponded: This interaction has already been responded to before

slate swan
#

This interaction has already been responded to before

#

This interaction has already been responded to before

shrewd apex
slate swan
#

!d discord.Interaction.followup

unkempt canyonBOT
shrewd vapor
#

Yes i have see i have changed

shrewd apex
#

do a followup or edit it

shrewd vapor
#

error with json i need help

slate swan
#

It's not a JSON error though

shrewd vapor
#

Traceback (most recent call last):
File "/home/container/otrobot.py", line 503, in remove_scamlist
scamlist_data = json.load(f)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 3 column 2 (char 8)

During handling of the above exception, another exception occurred:

slate swan
shrewd vapor
#

Its error json

#

{

}{"id": 1108857720100114434, "name": "Azalee", "reason": "test", "server": "\ud83c\udf19\u30fbMoonGen"}
Bruh

#

He write after }

slate swan
#

Also next time use a pastebin to send your super long traceback wow

shrewd vapor
#

Yes sry lol

slate swan
#

And you'll need to make it a list

#
[
    { 
        "blah": "blah"
    },
    {
        "bleh": "bleh"
    }
]
shrewd apex
shrewd vapor
#

Ok i go see

shrewd apex
#

i mean usually with quotes and stuff pretty neat as a formatter my go to is this and one more site called jsoncrack for visualization purposes

shrewd vapor
#

Ok thanks

formal basin
#
 with open('blocked words.txt') as blockedwords:
      if msg in blockedwords.read():
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)

 ```my bot is deleting embeds
shrewd vapor
#
@bot.tree.command(name = "add-scamlist", description = "Add user in scamlist")
async def add_scamlist(interaction, member: discord.User, reason: str):
    if (interaction.user.id == 944574924234846298):
        await interaction.response.defer()
        try:
            with open("scamlist.json", "r+") as f:
                exist = json.load(f)
                identifiant = exist.get('id')
                reason_exist = exist.get('reason')
                if identifiant in [item["id"] for item in exist]:
                    if (member.id == identifiant):
                        embed_exist = discord.Embed(title = "Member is already in scamlist", description = f"Reason: {reason_exist}")
                        await interaction.followup.send(embed=embed_exist)
                        return
                else:
                    data = {
                        "id": member.id,
                        "name": member.name,
                        "reason": reason,
                        "server": interaction.guild.name,
                    }
                    json.dump(data, f)
                    f.write(f",")
                    embed = discord.Embed(title = "User add in Scamlist", description = f"{member} add in scamlist for {reason}")
                    await interaction.followup.send(embed=embed)
                    guild_id = interaction.guild.id
                    if database_scamlist.get_channel(guild_id) is None:
                        return
                    channel_send = database_scamlist.get_channel(guild_id)
                    embed_log = discord.Embed(title = "New user in ScamList", description = f"<@{member.id}> is added in ScamList")
                    embed_log.add_field(name = "Reason:", value = f"{reason}")
                    channel_send.send_message(embed=embed_log)
        except:
            embed_error = discord.Embed(title = "Error", description = "An error has occurred please try again later")
            await interaction.followup.send(embed=embed_error)
    else:
        await interaction.response.send_message("Only owner bot can use this command")```
If you can help me i don't have traceback
slate swan
#

That is because you eat the entire error

slate swan
#
except Exception as e:
    print(e)

Then you'll get an error in the console with your try/except

shrewd vapor
#

'list' object has no attribute 'get'

polar coyote
#

check if the msg is an embed @formal basin

polar coyote
shrewd vapor
formal basin
polar coyote
polar coyote
formal basin
shrewd vapor
#

Get id in my json for check if member i try enter in scamlist exist already or not with ID

formal basin
polar coyote
glad cradle
formal basin
slate swan
#

embeds definitely will be a list of embed objects, redundant check

slate swan
shrewd vapor
polar coyote
#

but yeah that is far more efficient

glad cradle
polar coyote
#

and then you can access these dictionaries to get your ID

slate swan
#

not really

#

A structure like

[
    { 
        "a": "a"
    },
    {
        "a": "b"
    }
]

is totally valid JSON, and what they have iirc.

You will not have a dict for that, they'll have to make key:value in the JSON before

glad cradle
polar coyote
slate swan
#

And that's what they don't do

polar coyote
glad cradle
slate swan
#

They try list.get(...) thinking it's a key:value when it's a list

formal basin
formal basin
polar coyote
formal basin
polar coyote
formal basin
# polar coyote yeah
@client.listen("on_message")
async def coolmessage(message):
 if message.author.id == client.user.id:
        return 
 message.content

 
 embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
 

 
 msg = message.content.lower()
 with open('blocked words.txt') as blockedwords:
      if msg in blockedwords.read():
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
      if message.embeds:
        pass
      ```
shrewd vapor
#

Bruh my bot write this in json

[
    
]{"id": 1108857720100114434, "name": "Azalee", "reason": "test", "server": "\ud83c\udf19\u30fbMoonGen"},```
#

he don't write in []

#

he write after

polar coyote
formal basin
#

ok

polar coyote
shrewd vapor
#

I don't want use database for the moment

polar coyote
#

this isn't formatted correct but you get the idea

shrewd vapor
#

My code need a big update for only use database

formal basin
formal basin
polar coyote
formal basin
shrewd vapor
formal basin
# polar coyote because you're returning message.content
Traceback (most recent call last):
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 191, in coolmessage
    if msg in blockedwords.read():
UnboundLocalError: local variable 'msg' referenced before assignment```im getting this error when a embed is sent.
slate swan
#

error says it all

formal basin
slate swan
#

Also return message.content makes no sense

#

Just return and that's it

thin garden
#

Yoo, I'm trying to get my bot to tag another bot(it's a music bot) to play something, it does return the message. But the other bot doesn't accept it. Is it possible to do something like this, or not possible at all?

slate swan
#

No

thin garden
#

I see.

slate swan
#

Most bots ignore messages from other bots in case you're wondering why

thin garden
#

Yeah, was making sure. Tyty

terse rivet
#

can someone pls help me with my discord bot i am trying to make a music bot and it joins vc but it just doesn't play any audio

meager chasm
earnest tendon
#

Evening lads im struggling with adding cogs to my bot. Am i alright to send the entire code here or do you require it in a codedump? Thanks 🙂

meager chasm
#

If it's small you can send it directly here

earnest tendon
#

of course lad.. so in the "main.py" file ive just got "bot.load_extension('MathCog')"... at the bottom the "mathcog.py" ive set it up as def setup(bot): bot.add_cog(MathCog(bot))"

smoky sinew
meager chasm
earnest tendon
meager chasm
#

Loading extensions and adding cogs is done asynchronously in 2.0+

smoky sinew
earnest tendon
smoky sinew
#
@bot.event
async def setup_hook() -> None:
    await bot.load_extension("mathcog")
earnest tendon
#

im sorry im new to all this lad.. give me a second to try and process 🙂 appreiciate you all

shrewd vapor
#

How to make the commands visible only to people with permissions ?

shrewd vapor
#

ban, kick and others

smoky sinew
#

slash commands prefix commands

earnest tendon
#

I am sorry, im struggling with this. so what code do i need to have inside the cog and which code do i need to have inside the main.py file. Sorry if its a stupid question 🙂 thanks

shrewd vapor
#

slash command

smoky sinew
unkempt canyonBOT
#

@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member 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 "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 "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
shrewd vapor
#

I check already if he have permission just i search for people don't have permission he can't see the command

earnest tendon
#

okay danke 🙂

north kiln
#

!d discord.app_commands.Command.default_permissions

unkempt canyonBOT
#

The default permissions that can execute this command on Discord. Note that server administrators can override this value in the client. Setting an empty permissions field will disallow anyone except server administrators from using the command in a guild.

Due to a Discord limitation, this does not work on subcommands.

slate swan
#

can someone help me turn this tool into a discord bot?

#

I love "this tool", lots of information CLe_FeelsThumbsUpMan

formal basin
#

Why is it sending like this

golden portal
#

use random.choice

formal basin
#

This is deleting random embeds

vocal snow
unkempt canyonBOT
#

@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
vocal snow
#

message.content.lower() would be an empty string if there is no content (like when an embed is sent)

vocal snow
#

Yeah, it's an empty string

vocal snow
formal basin
plain pollen
#

well, yeah, if the message doesn't have any text, then the check will be True, leading to the message's deletion

vocal snow
#

The if statement executes because an empty string is always in a non empty string, hence the message is deleted

vocal snow
#

How would you ensure that the string is not empty?

formal basin
vocal snow
#

Right, but which condition would you check?

formal basin
#

Or no string

vocal snow
#

The correct way would be to split the text into a list of strings

#

Have you used str.split() before?

formal basin
formal basin
plain pollen
#

don't you wanna be checking whether any of the blocked words are in the message, rather than if the message itself is in the list of blocked words? since otherwise, your filter won't be catching any blocked words within a longer sentence, anyway

cosmic axle
#

Hello, any free hosting site for bots?

formal basin
#

What do I do?

vocal snow
formal basin
formal basin
#

Like

Word1
Word2
Word3

formal basin
plain pollen
#

so roughly, you wanna do something like:

  • take those words, and split them up into a list of each individual word (using something like .split("\n"))
  • for each of those words, check to see if its contained within the message
  • if any word is, then take whatever actions you want to deal with it
    if you wanna be efficient, that first step could be something that's done once when your bot is starting up, rather than every time the command is ran, but it'll work either way
lucid galleon
#
Traceback (most recent call last):
  File "f:\mlenv\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "f:\mlenv\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "f:\mlenv\lib\asyncio\base_events.py", line 719, in call_soon
    self._check_closed()
  File "f:\mlenv\lib\asyncio\base_events.py", line 508, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
``` how to fix this?
naive briar
#

Is that the whole traceback

lucid galleon
lucid galleon
# robust fulcrum Can you show your code?

@client.event

async def on_ready():
    print(f'{client.user} has connected to Discord!')
    print(f'{client.user.id}')
    print(f'{client.user.name}')
    print(f'{client.user.discriminator}')
    
@client.event
async def on_message(message):
    if message.author == client.user:
        return
    else:
        try:
            data = query(message.content)
            conversation = data["conversation"]["generated_responses"][0]
            await message.channel.typing()
            await message.channel.send(conversation)

        except:
            await message.channel.typing()
            await message.channel.send("I don't understand")    
        

client.run(DISCORD_TOKEN)```
robust fulcrum
lucid galleon
lucid galleon
robust fulcrum
#

So do this error creates any trouble for you?

lucid galleon
#

i guess no

robust fulcrum
#

So, go on?

#

This error is related to asyncio event loop not closed after use

lucid galleon
lucid galleon
robust fulcrum
lucid galleon
robust fulcrum
#

Hmm imma find solution to it , give me some time

north kiln
#

Don't use request

lucid galleon
north kiln
#

As it is synchronous and blocking

#

Use aiohttp