#discord-bots

1 messages · Page 328 of 1

ocean dragon
#

maybe I have some synchronized code running or smth, i dont think so tho

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.

hushed galleon
#

is the bottom snippet exactly what you're using? if so, you haven't assigned view to the GeneratorView() instance you created inside message.edit()

shrewd apex
#

^^

ocean dragon
#

oh yeah no i just cleaned it up a bit

#

hold up

#
    @app_commands.command(name="chat", description="Chat with the bot")
    @app_commands.describe(prompt="The prompt to send to the bot")
    async def chat(self, interaction: discord.Interaction, prompt: str, stream: bool = True) -> None:
        await interaction.response.defer()

        last_edit = config.misc.message_edit_interval
        message = await interaction.original_response()
        async with message.channel.typing():
            payload = self.bot.openai_service.create_chat_completion_payload(prompt=prompt, stream=stream)
            generator = self.bot.openai_service.create_chat_completion(payload=payload)
            view = GeneratorView(bot=self.bot)
            async for content in generator:
                if view.stopped:
                    break
                if time() - last_edit > config.misc.message_edit_interval and len(content) < Utils.MAX_CHARACTERS:
                    await message.edit(content=content, view=view)
                    last_edit = time()
shrewd apex
#

u create the view but u never edited the message with the view here

ocean dragon
#

crap yeah sorry I dont have it added since it didnt work

#

but i mean when I added it it still doesnt do it so yea

shrewd apex
#

!d discord.Interaction.edit_original_response also u can use this instead of fetching the message and editing again

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.
ocean dragon
#

I need the original message for other purposes

shrewd apex
#

like?

ocean dragon
#

I have a thread feature so I need message ids and contents

#

doesnt really concern this feature tho

shrewd apex
#

might wanna debug that

ocean dragon
#
class GeneratorView(discord.ui.View):
    def __init__(self, bot: MyBot, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.bot: MyBot = bot
        self.stopped: bool = False

    @discord.ui.button(label="Stop", style=discord.ButtonStyle.red)
    async def stop_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        self.stopped = True
        self.stop()
#

yeah

shrewd apex
#

nothing wrong with the logic behind breaking out #bot-commands message the error is somewhere else

shrewd apex
ocean dragon
#

im responding to it in the slash command

#

or do I have to respond to a view as well

shrewd apex
#

all interactions need a response

ocean dragon
#

well setting the property doesnt take a long time, why would it matter

#

since I just check the property elsewhere

shrewd apex
#

in case of components u can defer then indefinitely but for slash commands is compulsory to respond

shrewd apex
ocean dragon
#

no not yet

slate swan
#

question, I have a bot that reads csv files to read and write information, but I am moving the bot to bigger server with more interactions that could be simultaneous, is it better to convert this to sqlite for performance or does anyone have any alternative recommendations

hushed galleon
slate swan
hushed galleon
# slate swan thanks, 2 follow up questions: would I be losing performance for going sqllite i...

for performance, it depends on how much traffic you're expecting to have but sqlite can be quite efficient in low-concurrency workloads

with asyncio, your program's thread needs to run an event loop constantly, but non-async libraries that take too much time to do something prevents your event loop from doing anything else, like responding to commands or keeping the bot's connection to discord alive

#

sqlite3 in particular will block the event loop if it has to do a performance-intensive query or wait for another connection to release a database lock

unreal pilot
#

why are my discord images not loading in?

#

for example this ^

#

i have this little goofy image that i wanna load in, but its not showing up

#

any imgur gif that ive uploaded thus far is not showing up

floral flax
#

I haven't been keeping up with sqlite for years, but has it ever become more than just an abstraction over simple text files? I don't know, why you'd ever want to use sqlite other than for prototyping or embedded applications. If you want to deploy an actual service, people are actually going to use, don't use sqlite

floral flax
hushed galleon
floral flax
#

This is like saying a "programming language is turing complete" it doesn't give you much information

warm copper
#

Hi guys, I want to get back working on a discord bot of mine which I stopped developing back when discord.py's developers announced it was ending, but I dont know if I should update my bot to discord.py 2 or nextcord. Can someone advice me which is the best option?

hushed galleon
floral flax
hushed galleon
vapid parcel
#

What does this error mean in discord Dev?

#

I read the full error too, still didn't really understand?

fading linden
#

a react error lmaoo

vapid parcel
#

its fixed now

tacit prawn
#

You know how you have this for discord.py? I currently know how to add parameters and everything to it, but I have one question. I have a list of string's that I want to make the options for a parameter, if that makes sense. How would I do that? Like paramName: listName ??

final iron
#

!d discord.app_commands.choices You can use this

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
tacit prawn
slate swan
#

@feral timber see how the gif command says Search for a GIF, my command just has "..."

#

I want to add a description above like the gif command.

feral timber
unkempt canyonBOT
#

src/bot/exts/dragonfly/dragonfly.py line 248

@discord.app_commands.command(name="lookup", description="Scans a package")```
slate swan
#

I think they're after descriptions for each parameter, not the command itself

final iron
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...
acoustic kernel
#

How do I add subcommands with discord interaction?

Like if I want to have /alliance create
/alliance add
/alliance kick

acoustic kernel
#

preitiate it

sturdy dragon
#

i.e ```somegroup = app_commands.Group(name="mycommandgroup", description="some commands but grouped")
@somegroup.command(name="ping:, description="ping the bot")
async def ping_slash_command(self, Interaction: discord Interaction, somearg: str):
if somearg == "subcommand"
try:
subcommandstuff
except Exception as e:
print('something broke')
elif somearg == "subcommand2"
try:
somethingelse

#

just one way to do it

naive briar
#

This isn't so "Discord bots" stuff

final iron
#

You should be creating sub commands properly

shrewd apex
#

u can use groupcogs for making subcommands

true vector
#

I have two slash commands both interactive. But one gets registered and I am able to interact with it and the other doesnt, any idea ?

#
import discord
from discord.ext import commands 
from discord import app_commands
import logging
from colorama import Fore
import random


bot = commands.Bot(command_prefix='!' , intents= discord.Intents.all())


handler = logging.FileHandler(filename='discordPY.log', encoding='utf-8', mode  = 'w')

@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('------------------------------')    
            
@bot.event            
async def on_message(message):
        print(Fore.YELLOW + f'In server: {message.guild}')
        print(Fore.GREEN + f'Message from {message.author} in channel {message.channel}: {message.content}')
        
@bot.event     
async def on_message_delete(message):
        print(Fore.YELLOW + f'In server: {message.guild}')
        print(Fore.RED + f'Message deleted from {message.author} in channel {message.channel}: {message.content}') 
@bot.event 
async def on_message_update(before, after):
    print(Fore.YELLOW + f'In server: {before.guild}')
    print(Fore.BLUE + f'**{before.author}** edited their message: \n BEFORE: {before.content} --> AFTER: {after.content}')

# Commands

@bot.tree.command(name='get_word')
@app_commands.describe(output = 'Wie soll der Code sein ? ')
async def pwd(interaction: discord.Interaction, output: str): 
    await interaction.response.send_message(f'Ok, **{interaction.user.name}** der Code für die test Rolle ist jetzt: `{output}`')

# Ich will den Output in eine Liste speicher, sodass der Bot später darauf zugreifen kann

    Data = []
    Data.append(output)
    print(Data)


@bot.tree.command(name='test_role')
@app_commands.describe(input = 'Wie lautet der Code ?')
async def eingabe(interaction: discord.Interaction, input: str):
    if input in Data:
        await interaction.response.send_message(f'Ok,**{interaction.user.name}** du hast den richtigen Code eingegeben')
    else:
        await interaction.response.send_message(f'Ok,**{interaction.user.name}** du hast den falschen Code eingegeben')



bot.run('Token would be here' , log_handler=handler)
sturdy dragon
#

what does your on_ready function print for len(synced) commands?

true vector
#

Seems I took some time idk, just came back after a break and now its there.

shrewd apex
#

happened to me previously few times as well

young dagger
#

Is there any way I could make this easier?

    # Create a progress bar using custom emojis
    if progress == 0:
        progress_bar = '![bar_mixed](https://cdn.discordapp.com/emojis/1183857960540192778.webp?size=128 "bar_mixed")' + '![bar_grey](https://cdn.discordapp.com/emojis/1183855403575033937.webp?size=128 "bar_grey")' * 9
    else:
        filled_bars = int(progress * 10)
        if filled_bars == 0:
            progress_bar = '![bar_mixed](https://cdn.discordapp.com/emojis/1183857960540192778.webp?size=128 "bar_mixed")' + '![bar_grey](https://cdn.discordapp.com/emojis/1183855403575033937.webp?size=128 "bar_grey")' * 9
        else:
            progress_bar = '![bar_blue](https://cdn.discordapp.com/emojis/1183855391906484274.webp?size=128 "bar_blue")' * filled_bars + '![bar_grey](https://cdn.discordapp.com/emojis/1183855403575033937.webp?size=128 "bar_grey")' * (10 - filled_bars)
#

The idea is that the progress bar never should be completely empty

fading marlin
#

What is bar_mixed, bar_grey, and bar_blue?

hollow gazelle
#
print('Hello world!')
languid sequoia
true vector
#

how can I prevent from being rate limited ?

fading marlin
#

Don't spam API requests...?

shrewd apex
#

and dont use replit if ur using it

glad cradle
#

there's a third answer: destroy discord api and build a well working clone, your app, your choice

rapid knoll
#

how does one get a discord bot to send a private message as a reply to a message?

unkempt canyonBOT
shrewd apex
#

!d discord.Member.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**.
unreal pilot
#

where you regulate your requests

silent portal
#

is there a way to make the bot send one of these

#

instead of a normal mp3 file?

sick birch
silent portal
#

ok

slate swan
#

need ome help

tardy lagoon
#

how do you properly make http requests?

celest cliff
#

can i make a discord bot communicate with a db ? and also how to make it attach a file ?

golden portal
golden portal
#

[you need to elaborate on attach a file part]

vale wing
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
ocean dragon
#

How come I cant find any threads using this?

@tasks.loop(hours=1)
async def clear_threads(self):
    async for guild in self.bot.fetch_guilds():
        for thread in guild.threads:
            if thread.owner == self.bot.user:
                if time() - thread.created_at.timestamp() > config.misc.thread_lifetime_minutes * 60:
                    ...
tardy lagoon
golden portal
ocean dragon
#

do I have to fetch each guild after using fetch_guilds?

golden portal
unkempt canyonBOT
#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

but as said before you're best off creating your own session and stuff if what you're doing is outside the scope of the library

young dagger
celest cliff
#

and i'd like to make my bot attach the said file

golden portal
unreal pilot
#

mongo has an async driver 'Motor' very easy to use

#

so incase you dont know sql, use pymongo's 'Motor'

rugged shadow
#

mongodb users after their value turned out to be a string and not int

unreal pilot
#

as a mongodb user, i do not get it

robust fulcrum
#

tbh its good to use sql db incase you have a reson to use no sql

flat solstice
#

With Discord.py can I pass my Embed object a dict for the fields.
I have this and was hoping I could do somehting like embed[fields] or somehting instead of looping through the dict doing add_field

embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)

fields = {
  "field one name": "field one value",
  "field two name": "field two value"
}
slate swan
#

you can form an embed from dictionary but not with this style

#

it would have to be style that is set by discord

#

in this case what you have, you have to iterate over dict to add those fields

flat solstice
#

oh so I have to convert the entire embed to a dict.

spark nimbus
#

hello i am trying to create a wordle game and i get a weird error:

'function' object has no attribute 'to_dict' ```
the cog:
```py
import discord, random, utils
from discord import app_commands
from discord.ext import commands
from utils import generate_puzzle_embed

class wordle(commands.Cog):
    def __init__(self, client):
        self.client = client
    
    @app_commands.command(description="Play a nice game of wordle")
    async def wordle(self, interaction: discord.Interaction):
        embed = generate_puzzle_embed
        try:
            await interaction.response.send_message(embed=embed)
        except Exception as e:
            print(e)

async def setup(client):
    await client.add_cog(wordle(client))```
the utils file:
```py
import discord

def generate_blanks():
    return ":white_medium_square: :white_medium_square: :white_medium_square: :white_medium_square: :white_medium_square:"

def generate_puzzle_embed():
    embed = discord.Embed(title="A game of wordle has been started")
    embed.description = "\n".join([generate_blanks()] * 6)
    embed.set_footer("To start a new game use the command: /wordle \nTo guess reply to the message")
    
    return embed```
vocal snow
spark nimbus
vocal snow
#

did it print an exception?

spark nimbus
#

no

#

nothing

vocal snow
#

do you have an error handler (on_command_error, etc)

spark nimbus
#

no

#

never used it

#

how can i?

vocal snow
#

You don't need to, I'm just trying to figure out why you aren't seeing a traceback

#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
vocal snow
#

that might be why

spark nimbus
#

ohhh

#

the text

vocal snow
#

yep

spark nimbus
flat solstice
#

Is the first block the correct list comprehension for the below block

fields = [embed.add_field(name=key, value=value) for key, value in fields]
for key, value in fields
    embed.add_field(name=key, value=value)

This si the dict I'm working off of

embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)

fields = {
  "field one name": "field one value",
  "field two name": "field two value"
}
slate swan
#

the second block isn't building a list though

#

embed.add_field doesn't return some useful value that you store in a list

#

fields would just be a list of None values in your list comprehension

flat solstice
# slate swan the second block isn't building a list though

Oh, I'd forgotten to add some context; this is what my field dict is. This is declared outside of the loop

embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)

fields = {
  "field one name": "field one value",
  "field two name": "field two value"
}
slate swan
#

commands not working
code is not mine, someone gave me months ago, when he gave me code it was working perfect, commands working too good but then commands stop working (here is code link)
https://paste.pythondiscord.com/MNXA

slate swan
unreal pilot
#

well, ig its serverless

#

but how does that make it better for discord bot projects

solar path
slate swan
# unreal pilot for what reason?

I've used PyMongo and Motor-Asyncio and I feel that most bots lend themselves well to a relational-style database system, given that every discord object can be stored via it's unique ID. I also think that the Mongo Python drivers leave something to be desired in terms of documentation/type annotations. And they introduce an unnecessary dependency on mongoDBs services for the bot to function.

#

unless you have a specific need for storing stuff in mongo's JSON-style documents I'd usually just recommend just using SQL and an on-disk database

unreal pilot
#

you keep your explanation too abstract

#

in case of relational-style, that is what mongo uses as well

#

a document, as you know

slate swan
#

no mongo is non-relational

unreal pilot
unreal pilot
#

if i were to have a

#

object_id in my non relational db

flat solstice
shrewd apex
#

!d discord.Embed.add_field

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
ocean dragon
flat solstice
slate swan
unkempt canyonBOT
#

@before_loop```
A decorator that registers a coroutine to be called before the loop starts running.

This is useful if you want to wait for some bot state before the loop starts, such as [`discord.Client.wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready).

The coroutine must take no arguments (except `self` in a class context).

Changed in version 2.0: Calling [`stop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.stop) in this coroutine will stop the loop before the initial iteration is run.
ocean dragon
shrewd apex
#
embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)

fields = {
  "field one name": "field one value",
  "field two name": "field two value"
}
for k, v in fields.items():
   embed.add_field(name=k, value=v)
#

this is sufficient no need for any unecessary comps

flat solstice
#

Thanks Asher

ocean dragon
#

can I delete multiple threads with 1 request?

#

also is there no way to create a thread from a message that is private? I'd like if it was possible to create threads for users so that it doesnt flood the channel thread list

cloud dawn
shrewd apex
#

i feel threads have lost value since forum channels came out

cloud dawn
shrewd apex
hushed galleon
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.

New in version 2.0.
ocean dragon
#

do private theads have a starter_message

hushed galleon
#

apparently not

shrewd apex
#

just send an embed with message jump link

hushed galleon
# hushed galleon apparently not

starter_message is also None when a user creates a private thread, which is kind of weird because discord's UI requires you to send a "Starter Message"

#

but i guess starter_message only applies to threads created from an existing message, i.e. what the Start Thread from Message endpoint does

ocean dragon
#

Too bad 😕 Would've been good for what I'm doing

hushed galleon
ocean dragon
#

Hmm maybe, I'd like if the prompt message was visible somewhere in the thread, technically possible with webhooks but would prolly look weird

#

not that the message is visible in public threads either, but it's in the original message

hushed galleon
ocean dragon
#

oh multi-line input would be nice, I didnt know bots had modals, ig I could try that

hushed galleon
#

!d discord.ui.Modal has an example

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...
languid sequoia
#

What package should I use for doing voice macro commands?

final iron
languid sequoia
# final iron What are voice macro commands

Pretty much just commands that execute when the bot hears a voice in a vc, I’ve seen it done before and it looks pretty cool, I’m just not sure where I should start with making something like that.

#

Or at least I think that is how the bots I’ve seen work, I’m not certain though.

final iron
#

When it actually hears a voice, or when there’s any output from a user in a voice channel?

languid sequoia
#

Output

final iron
#

I don’t believe discord returns is_talking or similar

graceful basin
#

hey, i'm trying to work on a project involving discordpy with others, if you are interested please dm me!!!

unborn ether
#

Hey I was wondering, is there any framework to develop discord bot text based games? I only found https://pypi.org/project/DiscordGame/ which doesn't seem developed anymore. I am now working on a bot game that's based on text commands and reactions, but it's becoming spaghetti code. If there isn't such a framework I was thinking about developing one..

warm copper
#

can someone help me with my code? The kick command isnt working and I dont know why

#

the code on the right is the moderation file

upbeat otter
final iron
#

lol no

final iron
upbeat otter
#

no not really

#

they aren't even loading the extensions

#

no wait

#

ok my bad

#

but that would work too

warm copper
#

ok

#

tysm

void mauve
#

How can I pass client object to other files? It appears if I make client object global and use in another scope it says that I can't do that as loop is already running:

async def main():
    logging.basicConfig(level=logging.INFO)

    async with create_pool(
        host=HOST,
        port=PORT,
        user=USER,
        password=PASSWORD,
        database=DATABASE_NAME,
    ) as pool:

        async with TicketBot(
            db=pool,
            initial_extensions=load_cogs(),
            command_prefix='!',
            intents=discord.Intents.all()
        ) as client:
            await create_db()
            await client.start(token=bot_token)
void mauve
fading marlin
#

What "other files"?

void mauve
#

as I need to use bot.fetch_guild

fading marlin
#

Any chance you could send your code?

void mauve
#

yea

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @void mauve until <t:1702578352:f> (10 minutes) (reason: newlines spam - sent 105 newlines).

The <@&831776746206265384> have been alerted for review.

cerulean geyser
#

!unmute 399163302455803904

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @void mauve.

fading marlin
#

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

cerulean geyser
#

Please use paste services for longer code snippets

#

otherwise the bot will mistake you for a spammer

void mauve
#

ok thanks\

void mauve
shrewd apex
unborn ether
shrewd apex
#

what all features are u looking for as a framework

#

serialisation and game state i can see happening with some database adapter not sure about the others

unborn ether
# shrewd apex what all features are u looking for as a framework

Apart from managing the game state, things like translations, dialogue flows (do you know Disco Elysium? It was a dialogue heavy game, but implementing such thing is not easy), DnD style games, character customization so easy manipulation with mutable attributes, asset library and oh well I guess I'm looking for a game engine but instead of some vulkan/opengl/directx rendering, it will work with discord input (be it text, reaction, modals, it'd be up to the developer)

#

but yeah I am making my game and it feels like a chore reimplementing building blocks that could be done generic in some library

#

especially the dialogue flow, you need to keep the state of the dialogue and know what the user is replying to, then you get the branching and you don't want to see my code

shrewd apex
#

dialogue flow imo is mostly customisable to each use case and at the end these are just a bunch of callbacks atleast as far i use (interactions) which edits the view further

unborn ether
#

So in conclusion there wouldn't be much benefit to having something like that you think?

ashen notch
#

Are ephemeral embeds a thing?

fading marlin
#

Yes

ashen notch
#

Sweet. Thanks.

cloud dawn
#

Buttons. Modals and even custom formats like invite embeds etc.

ashen notch
#

Oh huh

#

Didn't know that was possible

#

The buttons and modals I mean

cloud dawn
#

Would be a nice update for the Python bot, an ephemeral help command with buttons :)

ashen notch
#

Currently doing an update to the voice verify thingy with a persistent button. I wouldn't mind working on (or having others work on) overhauling things to be more interactions based. Not 100% what the feeling is on that, though

shrewd apex
ashen notch
#

We do have slash commands for the tag system

cloud dawn
#

Yea especially hybrid since then the old option still persists.

ashen notch
#

Oh fair, I forgot about hybrid

shrewd apex
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
shrewd apex
#

for this? ^^

#

it would be cool to have it for the above as the other alternative is to go to the docs if u forgot the attributes

cloud dawn
ashen notch
#

I know for mod and admin stuff, it'd take a while for me to get used to using the slash commands

#

Been doing the regular commands for so long

#

Actually the discussion about the hybrid commands might be worth bringing up in #community-meta

cloud dawn
ashen notch
#

How much work do you have to do to convert?

ashen notch
shrewd apex
#

@commands.command to @commands.hybrid_command

ashen notch
#

That's... much less work than I thought it would be

shrewd apex
#

its pretty less

cloud dawn
shrewd apex
ashen notch
#

I guess that makes sense

cloud dawn
ashen notch
#

I think in our case most of that is managed through redis and scheduling

#

Yeah, they're setup as separate scheduled tasks and checked on

#

All that routes through here

cloud dawn
ashen notch
#

Consistent tracking and logging for anything we have to schedule

shrewd apex
#

one simple example say u have bunch of tasks fired on startup for a specific task say caching but this task was cancelled or aborted u would want to clear up ur bg tasks as well to prevent resource wastage

quasi depot
#

Is there any free tournament bot?

final iron
final iron
hard nest
#

yo guys, im trying to host a bot that uses selenium, but it seems like applications like replit wont work with it as obviously it cant really open an app in a online environment, does anyone have any solutions or free/cheap hosting they know will work with this kinda thing

hard nest
#

ight

lean shard
#

Hello! I'm looking to see if anyone's up to chat with me about approach for a discord dnd bot. I'll be tracking sessions attended and points earned. This would be for folks who aren't tech savvy, so it has to be kind resilient to garbage

sick birch
lean shard
#

How do you safely do a database for this kind of application?

final iron
#

What would you consider unsafe?

sick birch
lean shard
#

Something that crashes if multiple people are using it, crashing if it handles ususal text (i know i can use placeholders in sqlite3 for that part) and poor error explainations

lean shard
sick birch
#

boils down to good data modeling and normalization

lean shard
#

How do you normalize data when you can't fully expect the inputs? Just a lot of solid error handling?

sick birch
lean shard
#

... now that I think of it, I think i'm being paranoid in that respect 😅

#

I'm expecting odd naming schemes for player names (potential characters like undescores) and character names, and then numbers for the point counting

sick birch
lean shard
#

Happy to hear that!

#

if I have just a separate computer tower running the bot, do I need to worry about a formalized service?

sick birch
lean shard
#

I know zero about postgres, so I'll have to read into it

#

I may be worrying too hard about this project, haha
Do folks do code reviews in this server?

sick birch
#

SQLite3 should work fine too. Just doesn't scale that well, if that's something you're worried about

sick birch
lean shard
#

I'll make sure I do that!

pliant mica
#

what could the problem be??

final iron
#

You shouldn't be printing that

pliant mica
pliant mica
final iron
pliant mica
pliant mica
final iron
#

Look at the expected input/output

pliant mica
#

ohh okay I see

#

thanks for pointing that out

young dagger
#

How do I use cogs? Is there an example I can see?

naive briar
#

Didcord

young dagger
rugged shadow
#

both

#

the single cog should be a fallback - like if the error was unexpected

#

otherwise you can just handle known cases in each cog themselves

slate swan
#

cog file

slate swan
#

You don't run the cog file, you run the main file

void mauve
#

How to get list of the threads in a current channel? channel.threads seems to output nothing but an empty list

    @tasks.loop(seconds=5)
    async def auto_delete_task(self):
        AUTODELETE_TIME_THRESHOLD = timedelta(seconds=10)

        guild_id = await db.select_guild(session)
        guild: discord.Guild = await self.bot.fetch_guild(guild_id)

        channel_ids = await db.select_active_channels(session)
        channels = [await guild.fetch_channel(channel_id) for channel_id in channel_ids]

        for channel in channels:

            print(channel.threads)

            for thread in channel.threads:
                last_message_id = thread.last_message_id

                if last_message_id is not None:
                    last_message = await thread.fetch_message(last_message_id)

                    print(last_message.created_at)

                    tz = timezone('Europe/Moscow')

                    time_diff = datetime.now(tz) - last_message.created_at

                    if time_diff > AUTODELETE_TIME_THRESHOLD:
                        await thread.delete()

                        print(f'Deleted: {thread.name}')    @tasks.loop(seconds=5)
lean shard
#

I'm seeing online in tutorials that you can't use client and bot.commands at the same time, but how does the discord bot connect without the client giving it a token?

brazen raft
#

The bot classes inherit from the client classes

void mauve
#

Well it gives me the desired channel object, it just doesn't retrieve threads

golden portal
#

i guess it didnt really elaborate clearly, when you do fetch_guild it is not constructed with cache, so when you do guild.fetch_channel the channel object is constructed not from the cache, so it doesnt have threads filled

void mauve
#

Oh I see

#

Thanks, I'll try that out

tepid dagger
#

how do you print only the contents of a message (using on_message event)

#

cus rn when i print the message it comes with a lot of other stuff and i want to only work with the message content

slate swan
#

!d discord.Message.content

unkempt canyonBOT
true vector
#

how do I add descriptions like this ?

#

couldnt find anything

hushed galleon
true vector
hushed galleon
#

for example: ```py
@bot.tree.command(description="Do something fancy")
async def my_command(interaction):
...

or:

@bot.tree.command()
async def my_command(interaction):
"""Do something fancy"""``` the latter i usually find more convenient, especially when documenting parameters of that command since it supports numpy/google/sphinx-style docstrings, but the former is required if you intend to translate your bot using locale_str

true vector
#

so obv, thanks

hushed galleon
#

hmm wait, auto_locale_strings= handles that so i guess technically docstrings are fine too

spark nimbus
#

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

spark nimbus
#

well, i ran into a problem in my wordle command. idk what is it tho. i only get "the application did not responde"
my cog code:

import discord, random, utils
from discord import app_commands
from discord.ext import commands
from utils import generate_blanks, generate_puzzle_embed, is_valid_word, random_puzzle_id, generate_color_word, update_embed

class wordle(commands.Cog):
    def __init__(self, client):
        self.client = client
    
    @app_commands.command(description="Play a nice game of wordle")
    async def wordle(self, interaction: discord.Interaction):
        puzlle_id = random_puzzle_id()
        embed = generate_puzzle_embed(puzlle_id)
        await interaction.response.send_message(embed=embed)
            
    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        ref = message.reffrence
        if not ref or not isinstance(ref.resolved, discord.Message):
            return
        parent = ref.resolved #check if the message replies to the embed 
        
        if parent.author.id != self.client.user.id:
            return
        
        if not parent.embeds:
            return
        
        if not is_valid_word(message.content):
            await message.reply("That is not a valid word!\nEnter a valid word of 5 letters in english only!", delete_after=5)
            await message.delete(delay=5)
            return
        
        embed = parent.embeds[0]
        
        embed = update_embed(embed, message.content)
        await parent.edit(embed=embed)
        
        try:
            await message.delete()
        except Exception:
            pass

async def setup(client):
    await client.add_cog(wordle(client))```
and this is my utils code where i have most of my functions: 
https://paste.pythondiscord.com/44JA
#

i think it is some thing with the puzzle id

#

bc since i have added that it is not working

final iron
keen yew
#

how do i start with python discord bots?

spark nimbus
final iron
final iron
keen yew
final iron
#

You’re not being very specific. What can you do with what?

spark nimbus
# final iron By what

"You have to respond to an interaction by 3 seconds" what do you mean about the 3 seconds part

final iron
#

Are you asking how to respond to an interaction?

spark nimbus
#

But what do you mean bout by the 3 sec..?

final iron
#

You have to respond to it within 3 seconds

#

3 seconds of when it was invoked

spark nimbus
#

I don't think I know what are you talking about

final iron
spark nimbus
#

I think I don't understand what I need to do...

final iron
#

That’s one solution, or you can use

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
final iron
#

This will give you 15 minutes to respond

spark nimbus
#

I don't think you hot the problem bc I didn't explained it well....
When I am using the slash command(/wordle) I get an application command fail, since I added the puzzle ID function..

final iron
#

If its failing entirely that’s a separate issue, but its most likely just taking too long

spark nimbus
#

Ohhh ok

hushed galleon
#

it doesnt look like there's any blocking code in your util functions... did you get any error in your console? have you tried putting a print statement at the start of your command to see if it's being invoked correctly?

spark nimbus
#

Thx for the help I am going to sleep I will update you later

midnight oracle
#

Can someone please tell me why this cog isn't being shown as a /???:

import discord
from discord.ext import commands 
from discord import app_commands

class Greetings(commands.Cog): 
    def __init__(self, bot) -> None: 
        self.bot = bot
    
    @app_commands.command(name = "hi")
    async def hi(self, interaction: discord.Interaction, user: discord.Member):
        await interaction.response.send_message(f"hi {user.name}")
        
        
async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(Greetings(bot))
#

In main i'm using this lo load the cogs:

@bot.event
    async def on_ready():
        logging.info(f'Inicialidado como {bot.user}')
        
        bot.tree.copy_global_to(guild = settings.GUILD_ID)
        await bot.tree.sync(guild = settings.GUILD_ID)
        
        for cog_file in settings.COG_DIR.glob("*.py"):
           if cog_file != "__init__.py":
                await bot.load_extension(f"cogs.{cog_file.name[:-3]}")
final iron
midnight oracle
#

Thanks

urban hound
#

i am facing this error, and i have no idea why i am getting it
i am not even using audiloop library

robust fulcrum
#

Guys can an Android phone be used for hosting a discord bot 24/7?

urban hound
robust fulcrum
urban hound
robust fulcrum
#

You can ignore it

urban hound
#

is there like a fix or something? that pytest ignores this warning?

robust fulcrum
#

I don't know how you can stop to show this warning, sorry

robust fulcrum
slate swan
#

Guess it

stark kite
#

import discord
ModuleNotFoundError: No module named 'discord'
how to fix it?

robust fulcrum
stark kite
#

thanks

urban hound
shrewd apex
# robust fulcrum Why not ideal?

its due to the operating system phones are based on which make development and dev related tools hard to operate on it they dont have the necessary binaries

spark nimbus
# final iron If its failing entirely that’s a separate issue, but its most likely just taking...

i have added the defer, changed nothing maybe i am a dummy that dont know how to add this correctly
code:py @app_commands.command(description="Play a nice game of wordle") async def wordle(self, interaction: discord.Interaction): puzlle_id = random_puzzle_id() embed = generate_puzzle_embed(interaction.user, puzlle_id) await interaction.response.defer(ephemeral=True) try: await interaction.followup.send(embed=embed) except Exception as e: print(e)
and the terminal is still clear

shrewd apex
spark nimbus
shrewd apex
#

does it take that long to generate the puzzles?

shrewd apex
spark nimbus
#

that is the utils ^^^

shrewd apex
#

tbh seems very likely it the puzzle generation function thats causing some error and that u dont have an error handler which causes the error to go unnoticed

#
def random_puzzle_id() -> int:
    return random.randint(0, len(popular_words-1))

can u spot the issue?

#

len(popular_words-1)

spark nimbus
shrewd apex
spark nimbus
#

the embed has been sent with the id thx

shrewd apex
#

cool

shrewd apex
#

u dont want errors like those to go unchecked makes it way harder to debug than it should be 😄

robust fulcrum
robust fulcrum
#

Ye an terminal emulator

shrewd apex
#

iirc its a bit unstable on like Androids greater than 12 or smn

#

so you should be able to download it right?

robust fulcrum
#

I am on Android 9 (pie)

shrewd apex
#

then it should be fine

robust fulcrum
#

Imma try

robust fulcrum
shrewd apex
#

any os is fine you just need to be able to run a python process well prerequisite is python should be able to run and your phone cpu dosent arbitrarily clear up the process

spark nimbus
shrewd apex
spark nimbus
shrewd apex
#

u need to register the error under the command tree if u want a global error handler

spark nimbus
#

got it working the emoji codes are not good i will change it.
thx asher, pep

tepid dagger
#

how do you check if a message contains attachments

#

and then send all the attachments that the message contains

naive briar
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

naive briar
#

!d discord.Message.attachments - check if this is empty

unkempt canyonBOT
tepid dagger
#

like if len(Message.attachments) = 0?

#

or just like

naive briar
#

Message objects, not the class

tepid dagger
#

can you just do like

#
if message.attachments:
  code
#

to check if it has attachments

naive briar
#

Yes?

tepid dagger
#

ok lol i realized i never figured out how to check if a list is empty

tepid dagger
#

how do you do this for embeds

#
await user.send(content=message.embeds[0].url) 

didn't work

#

it says that it can't send an empty message

#

why is this an empty message and how do you fix it

shrewd apex
tepid dagger
#

oh lol

shrewd apex
#

!d discord.Embed.url can be string or None basically u cannot send None or empty string as a message

unkempt canyonBOT
shrewd apex
#
await user.send(content=message.embeds[0].url or "No url present") 

u would need to modify it like this

spark nimbus
#

well its again about the wordle, i have this update embed function and i cant update the embed in the last part with the:py if guess == answer: if num_empty_slots == 0: embed.description += "\n\nPhew!" elif num_empty_slots == 1: embed.description += "\n\nGreat!" elif num_empty_slots == 2: embed.description += "\n\nSplendid!" elif num_empty_slots == 3: embed.description += "\n\nImpressive!" elif num_empty_slots == 4: embed.description += "\n\nMagnificent!" elif num_empty_slots == 5: embed.description += "\n\nWow buddy you killed it!"
that is the function:```py
def update_embed(embed: discord.Embed, guess: str) -> discord.Embed:
# Print the original description for debugging
print(f"Original description: {embed.description}")

puzzle_id = int(embed.footer.text.split()[16])
answer = popular_words[puzzle_id]
colored_word = generate_color_word(guess, answer)
empty_slot = generate_blanks()

embed.description = embed.description.replace(empty_slot, colored_word, 1)

print(f"Description after replacement: {embed.description}")

num_empty_slots = embed.description.count(empty_slot)

if guess == answer:
    if num_empty_slots == 0:
        embed.description += "\n\nPhew!"
    elif num_empty_slots == 1:
        embed.description += "\n\nGreat!"
    elif num_empty_slots == 2:
        embed.description += "\n\nSplendid!"
    elif num_empty_slots == 3:
        embed.description += "\n\nImpressive!"
    elif num_empty_slots == 4:
        embed.description += "\n\nMagnificent!"
    elif num_empty_slots == 5:
        embed.description += "\n\nWow buddy you killed it!"

# Print the final description for debugging
print(f"Final description: {embed.description}")

return embed
#

embed.description += ..... like this line what should i put instead?

slate swan
#

can-u-show-code

#

use @bot.event

here:
@client.event(replace-here-instead-of-@client.event) async def on_message(message):

#

👍

young dagger
#

Is there any way to simplify this code?

def generate_progress_bar(progress):
    bar_25 = "![bar_25](https://cdn.discordapp.com/emojis/1185598195754074295.webp?size=128 "bar_25")"
    bar_50 = "![bar_50](https://cdn.discordapp.com/emojis/1185598239198691388.webp?size=128 "bar_50")"
    bar_75 = "![bar_75](https://cdn.discordapp.com/emojis/1185598300435525663.webp?size=128 "bar_75")"
    bar_blue = "![bar_blue](https://cdn.discordapp.com/emojis/1185583736897675264.webp?size=128 "bar_blue")"
    bar_grey = "![bar_grey](https://cdn.discordapp.com/emojis/1185583748440404092.webp?size=128 "bar_grey")"

    bars = {
        2.5: bar_25,
        5: bar_50,
        7.5: bar_75,
        10: bar_blue
    }

    result = []
    remaining = progress

    for bar_value, bar_emoji in sorted(bars.items(), reverse=True):
        while remaining >= bar_value and len(result) < 10:
            result.append(bar_emoji)
            remaining -= bar_value

    while len(result) < 10:
        result.append(bar_grey)

    return ''.join(result)```
#

Working as it should, but it feels more complicated than it should

shrewd apex
young dagger
formal basin
#

@commands.Cog.listener()
    async def on_member_join(self, member):
     
        key = f'wchannelid {str(member.guild.id)}'
        key2 = f'wmessage {str(member.guild.id)}'
        exis = await self.check_exists(key)
        if exis:
          channel1 = await self.bot.redis.get(key)
          channel2 = int(channel1.decode("utf-8"))
          channel = self.bot.get_channel(channel2) or await self.bot.fetch_channel(channel2)
          message =  await self.bot.redis.get(key2)
          message1 = (message.decode("utf-8"))
          key45 = f'embed {str(member.guild.id)}'
          exis1 = await self.check_exists(key45)
          if exis1:
             embed = discord.Embed(title="", description=f"{message1.format(mention=member.mention)}")
             await channel.send(content=member.mention, embed=embed)
          else:
             await channel.send(message1.format(mention=member.mention))
             print(f"someone joined: {member.guild.id}")
     ```

2023-12-16 16:13:14 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/zagzag/vscode/zagzag/cog-folder/join-leave.py", line 61, in on_member_join
channel2 = int(channel1.decode("utf-8"))
AttributeError: 'str' object has no attribute 'decode'

hushed galleon
# young dagger Is there any way to simplify this code? ```py def generate_progress_bar(progress...

this is more suited for a #1035199133436354600 code review, but i'd probably use divmod instead ```py
def bar(progress: float) -> str:
progress = int(progress * 1000)
wholes, progress = divmod(progress, 100)
three_quarters, progress = divmod(progress, 75)
halves, progress = divmod(progress, 50)
quarters, progress = divmod(progress, 25)
empty = 10 - wholes - three_quarters - halves - quarters
return (
"4" * wholes
+ "3" * three_quarters
+ "2" * halves
+ "1" * quarters
+ "0" * empty
)

for progress in range(101):
print(bar(progress / 100), progress)```

shrewd apex
#

^^

#

was just gonna say that

hushed galleon
formal basin
young dagger
hushed galleon
#

redis seems like an odd choice for this though

formal basin
hushed galleon
#

you just call int() on the string, nothing else

formal basin
#

ok

shrewd apex
#

u can hardcode it above

young dagger
# hushed galleon this is more suited for a <#1035199133436354600> code review, but i'd probably u...

It's not working for some reason:

def generate_progress_bar(progress: float) -> str:
    # Define your emojis here
    emoji_whole = "![bar_blue](https://cdn.discordapp.com/emojis/1185583736897675264.webp?size=128 "bar_blue")"
    emoji_three_quarters = "![bar_75](https://cdn.discordapp.com/emojis/1185598300435525663.webp?size=128 "bar_75")"
    emoji_half = "![bar_50](https://cdn.discordapp.com/emojis/1185598239198691388.webp?size=128 "bar_50")"
    emoji_quarter = "![bar_25](https://cdn.discordapp.com/emojis/1185598195754074295.webp?size=128 "bar_25")"
    emoji_empty = "![bar_grey](https://cdn.discordapp.com/emojis/1185583748440404092.webp?size=128 "bar_grey")"

    progress = int(progress)
    print(progress)
    wholes, progress = divmod(progress, 100)
    three_quarters, progress = divmod(progress, 75)
    halves, progress = divmod(progress, 50)
    quarters, progress = divmod(progress, 25)
    empty = 10 - wholes - three_quarters - halves - quarters
    return (
            emoji_whole * wholes
            + emoji_three_quarters * three_quarters
            + emoji_half * halves
            + emoji_quarter * quarters
            + emoji_empty * empty
    )

@client.command(name='progress2')
async def progress2(ctx):
    # Print progress bars from 0% to 100%
    for progress in range(101):
        print(progress)
        progress_bar = generate_progress_bar(progress)
        await ctx.send(f"{progress}%: \n{progress_bar}")```
shrewd apex
#

u dont wanna send 101 messages 💀

hushed galleon
young dagger
#

I'm just testing it

shrewd apex
#

forgot

hushed galleon
#

i suggest testing your code in a console first

#

note that the unit scales in my example are different from your previous function

shrewd apex
young dagger
#

They match, I mean

hushed galleon
hushed galleon
shrewd apex
#

relatable ;-;

languid sequoia
#

How can I make a slash command option required?

sick birch
languid sequoia
#

I havent really used slash commands much, Can the options be stored in a variable?

severe sonnet
#

guys i need help with my VPS

#

i can't acess my OVH cloud VPS even with my password

#

i tried acessing via root

#

but it's not aeessing even with password

#

i even tried without password and it's not acessing

sick birch
slate swan
young dagger
#

I guess

slate swan
#

yeah but thats rather small improvement

#

i can look into the actual algorithm later

#

if that wasnt already optimized cause thats rather old message

young dagger
slate swan
#

Nah you are good joehandshake

rain burrow
#

what line of code would i write to ban people from there id

#

like !ban 991707603560300685

slate swan
#

I mean it works

final iron
#

attention to detail is great

drifting mantle
drifting mantle
#

ahh

lusty anvil
#
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

#client = commands.Bot(command_prefix=".")
__________________________________________
@client.command(pass_context=True)
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        await channel.connect()
        print(channel)

Hey, guys its been a min this is old code to a cmd I was wondering what the change was to use the same old cmd but im just not sure how to set the prefix since the change?

final iron
#

It has always been like this iirc

cloud dawn
lusty anvil
#

Im finding my way but by chance do you know the change for

in on_message
    await client.process_commands(message)
AttributeError: 'Client' object has no attribute 'process_commands'
cloud dawn
#

You'd need to change to Bot or implement slash commands or find a different way all together.

lusty anvil
#

Ah okay thank I appreciate it

ocean dragon
#

is there no way to increase modal size? it's pretty small by default

#

if max characters is 4000 that's pretty small text area for it

golden portal
#

nop frontend dev lazy issue, u can't rly change that

naive briar
#

#bot-commands

#

Okay then

young dagger
#

How can I convert the datetime for each user?
TypeError: can't compare offset-naive and offset-aware datetimes

lunar gale
#

if you are using discord.py you need to use their method in discord.Member

young dagger
#

Can't you compare utcnow with timedelta like this?

thirty_days_ago = discord.utils.utcnow() - datetime.timedelta(days=30)
        if user.get('last_activity') and user['last_activity'] >= thirty_days_ago:```
young dagger
#

So in my database the timestamp is represent as: last_activity 2023-05-22T13:55:17.114+00:00

#

When I print out thirty_days_ago it's giving me 2023-11-17 10:34:09.434256+00:00

#

But then when I grab user['last_activity'] it gives me 2023-05-22 13:55:17.114000

#

And when I do the comparison if user.get('last_activity') and user['last_activity'] >= thirty_days_ago: it gives me:
TypeError: can't compare offset-naive and offset-aware datetimes

#

I'm so confused. Can somebody help me out?

#

Should I just do discord.utils.utcnow().replace(tzinfo=None) when I do the comparison?

shrewd fjord
#

Replace tzinfo with either None or UTC

#

Uh

young dagger
glad cradle
#

!d datetime.tzinfo

unkempt canyonBOT
#

class datetime.tzinfo```
This is an abstract base class, meaning that this class should not be instantiated directly. Define a subclass of [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) to capture information about a particular time zone.

An instance of (a concrete subclass of) [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) can be passed to the constructors for [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) and [`time`](https://docs.python.org/3/library/datetime.html#datetime.time) objects. The latter objects view their attributes as being in local time, and the [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) object supports methods revealing offset of local time from UTC, the name of the time zone, and DST offset, all relative to a date or time object passed to them.
young dagger
#

And when I do print(user['last_activity']) it says 2023-05-22 13:55:17.114000

#

Btw ignore the date

#

I meant why is it not adding tzinfo by default as in the database

formal basin
#

async def get_perspective_score(self, text, type):
    # Specify the API endpoint URL and API key
      url = 'https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze'
      api_key = 'api_key'
    
    # Define the parameters for the request
      params = {
        'key': api_key
    }
    
    # Define the request body
      data = {
        'comment': {'text': text},
        'languages': ['en'],
        'requestedAttributes': {type: {}}
    }
    
    # Send the request using aiohttp
      async with aiohttp.ClientSession() as session:
        async with session.post(url, params=params, json=data) as response:
            result = await response.json()
        return result


This keeps breaking

slate swan
#

What about it is breaking?

formal basin
#

but it breaks somrtimes

slate swan
#

Do you have a traceback

formal basin
#

nope

#

It does look like its sending the request

#

I see the problem now

#
print("test")
                content = content.lower().replace("niger", "a country").replace("ass", "arse").replace("phuck", "fuck")
                modified_content = content
                type = 'PROFANITY'
                type2 = 'SEXUALLY_EXPLICIT'
                result = await self.get_perspective_score(modified_content, type)
                result = result.get('attributeScores', {}).get('PROFANITY', {}).get('summaryScore', {}).get('value', 0.0)
                result2 = await self.get_perspective_score(modified_content, type2)
                result2 = result2.get('attributeScores', {}).get('SEXUALLY_EXPLICIT', {}).get('summaryScore', {}).get('value', 0.0)
                print("test2")

                if result > 0.40 or result2 > 0.40:
#
if result > 0.40 or result2 > 0.40:

``` is not passing through
#

now its working

#

but for some reason

#

it stops working after

slate swan
#

It doesn't seem discord-specific to me so consider opening a help post or something

young dagger
#

Why am I getting a different value (without tzinfo) when I print it out?

shrewd fjord
blazing condor
#

Documentation:

Aware and Naive Objects

Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.
young dagger
# shrewd fjord Replace tzinfo with either None or UTC

The problem with timestamps is that if you host the bot over multiple servers or change to a different VPS in another location, the time zone will not be the same, and the comparison will fail. That's why I'm using discord.utils.utcnow

blazing condor
#

what're you trying to do @young dagger , i just woke up few mins ago 🥱

young dagger
#

So the time will always be the same no matter where the bot is hosted

young dagger
#

timestamp - 30 days will not be the same discord.utils.utcnow - 30 days if you change location, would it?

naive briar
#

Just change it back

young dagger
#

Because discord.utils.utcnow will always stay the same no matter where you are located

naive briar
#

If I have multiple datetime objects with different timezones, I'd just convert them all to UTC before comparing them

naive briar
#

I don't even know your codebase, so I'm not sure

blazing condor
young dagger
blazing condor
#

😆

young dagger
#

Now when I do later comparison it doesn't include tzinfo

#

And for that reason I'm getting TypeError: can't compare offset-naive and offset-aware datetimes

slate swan
#

How are you parsing it back into a date-time

young dagger
# slate swan How are you parsing it back into a date-time
users = await collection.find().to_list(length=None)
    for user in users:

        thirty_days_ago = discord.utils.utcnow() - datetime.timedelta(days=30)
        if user.get('last_activity') and user['last_activity'] >= thirty_days_ago:
            ### CODE HERE```
blazing condor
young dagger
#

Yeah, I get that now. But still I'm wondering why user['last_activity'] is showing as aware when saved as naive in the database

slate swan
#

ugh I'm not thoroughly familiar with mongodb here, sorry

blazing condor
blazing condor
#

so you need to convert it to a naive datetime in the same timezone.

young dagger
slate swan
#

!e from datetime import datetime, timedelta; print(datetime.now() >= (datetime.now() - timedelta(days=1)))

unkempt canyonBOT
#

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

True
slate swan
#

yea ..

young dagger
slate swan
#
        voicec = message.author.voice.channel
        await client.connect(voicec)

errors : Client.connect() takes 1 positional argument but 2 were given

#

Please send help

young dagger
#

Connect the bot to a voice channel on command?

slate swan
#

yea it is

slate swan
young dagger
#

Try this

voicec = message.author.voice.channel

if voicec:
    if voicec.permissions_for(message.guild.me).connect and voicec.permissions_for(message.guild.me).speak:
        voice_channel = await voicec.connect()
    else:
        await message.channel.send("No permissions.")
else:
    await message.channel.send("You need to be in a voice channel for the bot to connect.")```
slate swan
#

alright thanks

#

:0

#

IT WORKED

#

TYSM !!

young dagger
#

Good

#

No problem

slate swan
#

oh yeah, therefore I need the variable 🫡

final iron
young dagger
final iron
#

That’s not a push in the right direction though. You gave him an entire block of code without explaining why his didn’t work, or what yours is doing

blazing condor
# slate swan ```py voicec = message.author.voice.channel await client.connect...

the error is saying you gave it 2 arguments but only expected one, which is a mismatch between how the connect method is called and how it's define in the library, which in this case the Client. Connect method doesn't take channel as a parameter, which is why Beer used Voicec.connect() and i believe you could also use VoiceChannel.connect() but not entirely sure.

brittle moss
#

whats the best server location for discord bots

final iron
#

There is none

true vector
#

I have two commands where you can make a "code" for a role, if a user enters the code with a slash command they get the role. You should be able to delete the codes but I cannot figure out how to check the whole file and delete the code the user input in the slash command

#
@bot.tree.command(name='delete')
@commands.has_permissions(administrator=True)
@app_commands.describe(input_one = 'Welchen Code willst du löschen ?')
async def delete_code(interaction: discord.Interaction, input_one: str): 
    if input_one in showCodes:
        with open("codes.txt", "r") as file_input:
            with open("codes.txt", "w") as output: 
                for line in file_input:
                    if line.strip("\n") != input_one:
                        output.write(line)
    
        await interaction.response.send_message(f'Ok, **{interaction.user.name}** der Code `{input_one}` wurde gelöscht. \n Folgende Codes sind noch aktiv: `{DATA}`')
        print(DATA)
        print(f'Code {input_one} wurde gelöscht')
    else: 
        await interaction.response.send_message(f'Blöd gelaufen, **{interaction.user.name}** der Code `{input_one}` existiert nicht')
        print(f'Code {input_one} existiert nicht')
midnight oracle
#

Why if my bot has administrator permissions and all the intents allowed, It can't auto-rol new bot using the on_member_join and neither send messages to specific channels though the on_member_join??

The Cog.listener looks like this:

@commands.Cog.listener()
    async def on_member_join(self, member):
        await self.setup_role()
        await self.setup_bot_role()

        if member.bot:
            try:
                new_bot_role_name = discord.utils.get(member.guild.roles, name = self.new_bot_role_name)
                if new_bot_role_name:
                    channel = member.guild.get_channel(self.channel_id)
                    await member.add_roles(new_bot_role_name)
                    
                    avatar_url = member.avatar_url
                    name = member.name
                    
                    embed = discord.Embed(
                        colour = discord.Color.blue(),
                        title = 'A new bot has arrived',
                        description = f'Welcome to the army {name}')
                    embed.set_footer(text= f"{self.bot.user} — System")
                    embed.set_thumbnail(url= avatar_url)
                    #embed.set_image(url="")
                    channel.send(embed = embed)
            except Exception as e:
                print(f"Missing Permissions: {e}")
            
        else:
            new_member_role = discord.utils.get(member.guild.roles, name=self.new_member_role_name)
            if new_member_role:
                await member.add_roles(new_member_role)
                print(f"Se unió un usuario: {member.name}")
#

the output: Missing Permissions: 403 Forbidden (error code: 50013): Missing Permissions

true vector
#

did you do this ?

#
bot = commands.Bot(command_prefix='!' , intents= discord.Intents.all())
midnight oracle
true vector
#

hmm

midnight oracle
#

i thought it was the bot, so I created another one, and got the same error

true vector
#

check all these ?

midnight oracle
#

0.o

#

With users it works just fine

#

But not with bots

true vector
#

this is over my head xd

midnight oracle
midnight oracle
true vector
midnight oracle
tacit prawn
#

How can I run two bots at once? Like, I can't make two bots in the same file, then do clientA.run(tokenA) and clientB.run(tokenB) at the same time. What else can I do?

hushed galleon
# tacit prawn How can I run two bots at once? Like, I can't make two bots in the same file, th...

it's usually better to run both bots in separate scripts so they can't interfere with each other (like when you want to shut down one bot to update it), but if you really want to run them in one file, you can start them in separate asyncio tasks so both bots share the same event loop with each other, for example: ```py
async def main():
async with asyncio.TaskGroup() as tg: # Python 3.11+
foobot_task = tg.create_task(foobot.start(SOME_TOKEN))
barbot_task = tg.create_task(barbot.start(SOME_OTHER_TOKEN))
# Runs until both bots close themselves, or one bot raises an error,
# or the main program receives KeyboardInterrupt

asyncio.run(main())```

final iron
unkempt canyonBOT
#
Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

raw stump
#

Looking for good telegram python devs please dm me

cloud dawn
unkempt canyonBOT
#

6. Do not post unapproved advertising.

raw stump
#

Where can I post this?

cloud dawn
#

Nowhere, this Discord doesn't allow hiring.

tacit prawn
#

Anyone know why whenever I do this, it just stops working when it gets to user.roles? It doesnt give any errors, nothing. Just stops everything except the program. New role will never print

user = guild.get_member(userId) #This works perfectly fine, and gets the user
for i in user.roles:
  print("New role")
  print(i.id)

I have even tried this, and it still doesnt work. Test 1 and 2 both will print but not 3

print("Test1")
user = guild.get_member(userId)
print("Test2")
user.edit(roles=[]) #Just stops here
print("Test3")
final iron
tacit prawn
final iron
#

Await it

tacit prawn
#

Alr, one sec

final iron
#

It's a coroutine

#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
final iron
#

This function is a coroutine.

blazing condor
#

Note that simply calling a coroutine will not schedule it to be executed:

tacit prawn
#

Should I try the first method again? That I said above?

final iron
#

It is in this case

blazing condor
#

my point exactly.

final iron
# tacit prawn

get_... methods return None if the item isn't found in the bots cache

#

You'll need to use fetch_member

final iron
blazing condor
#

i was just stating that Coroutines don't run on their own just by calling them , they have to be schedule on the event loop to be executed.

tacit prawn
tacit prawn
#

Changing user to a guild.get_member() doesn't work since edit isnt a member of get_member.

tacit prawn
naive briar
#

So, is there actually an error or not?

#

Or am I misunderstanding something

tacit prawn
#

Sorry about that lol

final iron
#

Why do you have to log out and log back in

sick birch
#

probably easiest to do this with extensions

#

it has hot reloading capabilities

vale wing
#

Typical day after update rollout

safe wasp
#

Hello, when i try to do "pip install discord", i get that error while i did downoald Microsoft C++ Builds Tools

safe wasp
#

Nvm, i fixed it

dim solar
#

Which type of OS should I use for my Python discord bot

robust fulcrum
#

I guess alpine linux if available

dim solar
#

Alpine isnt available

rugged shadow
#

or rocky if you're used to Fedora

slate swan
vale wing
vale wing
#

Yeah

full cosmos
#

Hello! I have a button that always gives the "interaction failed" message within discord even though everything happens as it should. I read online, that the button needs a response even if it is just empty but all the other buttons in my code work just fine without it.

tacit prawn
slate swan
#

Is anyone aware of a bot that I can use to generate Discord conversations? Possibly one where I could enter their ID and it will simply generate the conversation using their Username + Profile Image. So I can configure the conversation before and then generate the same conversation each time?

glad cradle
vale wing
#

Snipy you haven't even completed your issue 🥱

vale wing
slate swan
vale wing
#

If you mean simulate the conversation

#

With like AI

slate swan
#

Well yeah just like creating a conversation to be screenshotted

vale wing
#

Or do you want to screenshot conversation that already exists

#

In that case it's okay

slate swan
#

So basically for example like the conversation we are having now, I want to be able to regenerate it but replace your username and avatar with something else

vale wing
#

I think there might be libraries that can render discord messages, but in case there are no you can build your custom renderer with pillow

slate swan
vale wing
slate swan
#

I did find an opensource on github which is pretty simillar to what I'm trying to achieve but like everything ever from github it doesn't run properly

vale wing
#

Could you link me that project

slate swan
#

Sure

vale wing
#

@slate swan no dms

slate swan
#

can I send links here?

#

oh yes I can

vale wing
#

The reason you can't run the code is it's not meant to be ran directly

#

It's a cog that can be loaded into main bot

slate swan
#

Holy shit I'm dumb lol do I need to go to developer portal and do all that

vale wing
#

Not even that

#

You don't have the main script

#

I can help you with tweaking that thing so it works but not rn

slate swan
#

That's fine I dont expect you to but that would be great if you could whenever you have the time

glad cradle
sly hamlet
#

Is there a way to track how many times a command is run?

naive briar
#

Add 1 to an integer in its callback

shrewd fjord
#

Like fake vouches and stuff

slate swan
#

That is not my intent for this software

naive briar
#

I don't see any use of it. At least not legitimately

slate swan
#

Content creation, being able to generate the conversations rather than typing it all out myself will be much easier

final iron
slate swan
#

hi im not sure if i use this or the help thread but im having trouble with this code

for user_id in users:
  member = interaction.guild.get_member(user_id)
  if role1 in member.roles:
    for _ in range(int(r1_entries)):
     users.append(_)
     winner = await client.fetch_user(random.choice(users))
     await msg.reply(f"Congratulations {winner.mention}! You won the giveaway! :tada:")
     users.clear()

there is a list with user ids it fetchs the user but i cant find a way to check the users roles member.has_roles() and member.roles has no attribute to it the role is defined in the async def as role1: discord.Role=None

final iron
slate swan
#

finding a method to get to check the users roles

final iron
#

discord.Member.roles returns the users roles in a list

slate swan
#

Hello, I'm still at the beginning of coding and i need some help. The bot wont respond to my "hello" command. Any ideas why? (you can js dm me i guess)

||import discord
from discord.ext import commands

TOKEN = ''

intents = discord.Intents.default()
intents.all()
intents.members = True

client = commands.Bot(command_prefix='!', intents=intents)

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
print("-----------------------------------")

@client.command()
async def hello(ctx):
await ctx.send(f'Hello {ctx.author.name}!')

client.run(TOKEN)||

#

it was a stup1d warning i fixed it 👍

midnight oracle
#

Can I limit SlashCommands usage to a certain channel? I mean, the commands will only be visible if you're in that channel. Is that possible?

final iron
#

You cannot change the visibility with your bot

midnight oracle
shrewd apex
#

yes

midnight oracle
#

how xd?

shrewd apex
#

i would suggest putting a role or perm check

midnight oracle
#

slahscommand*

midnight oracle
shrewd apex
#

yeah they have decorators for it

midnight oracle
#

0.o

#

how do i look for it

#

nevermind found it xd

midnight oracle
#

yei!

slate swan
#

I have a main file called bot.py that inits the pool connection to my database. How should I go about having a connection to the db in cogs?

#
    async def setup_hook(self):

        self.pool         = await asyncpg.create_pool(user='postgres', password='root', database='bipolar', host='localhost')
        self.db           = self.pool```
Code in `setup_hook` ^
slate swan
#

Or pass your bot object in as self.bot when instantiating cogs

slate swan
#

ctx.bot.db works

lean shard
#

Question: how do you know when to make a Help topic vs coming here to post?

slate swan
lean shard
#

👍

brazen geyser
#

hey guyss, can someone please tell me why this isnt working?

lean shard
#

It helps if you explain what the issue is vs what you expect

desert kiln
#

ok so, I'm making a bot, using cogs, but I wanna make it load all cogs in a folder [cogs], but I'm not sure how To make it do that

#

Here's what I have so far:

import discord
from discord.ext import commands
import os

TOKEN = "********"

class Nxghtmare(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix="!",
            intents=discord.Intents.all()
        )
    

Nxghtmare().run(TOKEN)```
graceful meadow
#

does anyone know how i can make a bot with slash commands? i have this code from the docs but it doesnt work

import discord

from dotenv import main

main.load_dotenv()

TOKEN = os.getenv('BOT_TOKEN')

bot = discord.Bot()

@bot.slash_command()
async def hello(ctx, name: str = None):
    name = name or ctx.author.name
    await ctx.respond(f"Hello {name}!")

bot.run(TOKEN)
print('logged into discord bot')
```the error i get says

bot = discord.Bot()
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'

ornate linden
#

I'm struggling to figure out how to use Groups within Cogs, I keep getting TypeError: Command signature requires at least 1 parameter(s)

    @commands.group(name='list')
    async def list_group():
        pass

    @list_group.command(name='duplicates')
    async def _list_duplicates(self, ctx: commands.Context) -> None:
    ...
desert kiln
ornate linden
desert kiln
ornate linden
#

sure yeah

ornate linden
#

also, use a .env to store your token instead of being in the file

desert kiln
ornate linden
#

you can have os list all of the files in the directory and run self.load_extension("cogfoldername.cogname") from inside your commands.Bot subclass on each of them

#

afaik there's no way to do it that's more automated than that

desert kiln
#

I managed to do it like that last time, I just lost my files, it would load all the cogs inside the folder

graceful meadow
ornate linden
#

I'll write a script that does it that you can drop into your subclass

desert kiln
drifting mantle
#

dpy is so behind in terms of stuff like this

ornate linden
#

@desert kiln ```py
async def setup_hook(self):

this won't play nice if you have subdirectories

cogs = os.listdir("cogfolderpath")
for cog in cogs:
self.load_extension(f"cogfolderpath.{cog}")

drifting mantle
#

especially if you are just starting i would highly suggest using something other than dpy

#

pretty sure every lib other than dpy has .load_extensions

#

so you can load a folder of cogs

ornate linden
#

is it an fstring?

desert kiln
#

I have no idea what's going on @ornate linden

ornate linden
#

uhhh

#

are your cogs working properly?

desert kiln
#

they do work properly

#

it's just not loading them correctly

ornate linden
#

try moving it into the __init__ instead of having it inside setup_hook

ornate linden
desert kiln
ornate linden
#

ah i know what's wrong

#

my bad, the fileextension shouldn't be there

#

change it to {cog[:-3]} and it should work

desert kiln
#

where do I replace that

ornate linden
#

    async def setup_hook(self):
        # this won't play nice if you have subdirectories
        cogs = os.listdir("cogs")
        for cog in cogs:
            if cog == "__pycache__":
                continue
            await self.load_extension(f"cogs.{cog[:-3]}")
#

found another problem with the pycache

#

should be good now

desert kiln
ornate linden
#

that doesn't happen automatically, you could put a print statement in the __init__ of the cog

#

or add ```py
...
continue
await self.load_extension(f"cogs.{cog[:-3]}")
print(f"Cog {cog[:-3]} loaded!")

desert kiln
#

I added that, in the cog

#

but it dosent print, when ran

ornate linden
#

sorry, the setup fn not init

desert kiln
ornate linden
#

hm

#

i don't know, but what I wrote is effectively the same as load_extension(cog1) load_extension(cog2) etc

#

I hate to say it, but it works for me..

old vine
#

so, i am trying to make this function where with a slash command, it locks the channel at the given lock time and unlocks the channel at the given unlock time.

i created the function and i even add it to the mongodb and it works fine, no error in the database part so it stores the date, but it doesn't lock the channel when lock time has been reached.

it sends a message saying "locking channel in in an minute and then it doesn't lock once the timer is finished. can you help me?

and also, i keep getting this error when i run the command.

Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x000001F2AB202470>:
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-IGCSE-Beta\lockdown.py", line 166, in Channellockcommand
    await interaction.response.send_message(f"<#{channelinput.id}> is scheduled to lock on {unixlocktime} and unlock on {unixunlocktime}", ephemeral=True)
  File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 896, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 195, in request
    raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interactio

code is in #1186487018121871361

cobalt falcon
#

Do I need C++ to do

pip install discord
normal falcon
#

seems to be sporadic but primarily non-functional. sometimes it will work and sometimes it won't and i don't know why. functions that have always worked are now doing it to me too

final iron
#

You cannot respond twice

old vine
normal falcon
old vine
final iron
#

If you have a question, send it and somebody will help if they want to

#

Many other people can help you as well

old vine
#

so, i am trying to make this function where with a slash command, it locks the channel at the given lock time and unlocks the channel at the given unlock time.

i created the function and i even add it to the mongodb and it works fine, no error in the database part so it stores the date, but it doesn't lock the channel when lock time has been reached.

it sends a message saying "locking channel in in an minute and then it doesn't lock once the timer is finished. can you help me?

calm shard
#
@client.event #for ads cards:-
async def on_reaction_add(reaction, user):
    message = reaction.message
    if await toolfn.check_if_kco(reaction, user, client, message):
        embed =toolfn.collection_cards(message, reaction)
        channel = reaction.message.channel
        await channel.send(embed=embed)
        asyncio.sleep(5)
    else:
        print("error")```
Hi, this is my half code of what I'm actually trying to build.
So, when a user reacts on a specific message with specific emoji, this will trigger, and it'll copy the message and send it in the channel as an embed but this is just half of what I tried to build.

Actually, I want the bot to hold for some time and wait for the user to edit their messages ( like for 5 seconds) and when the user edit their same message which was sent in the first place, then the bot will also save that new message content as  new variable, and then the bot will send the new message which will contain both messages ( first sent by  the user + 2nd after the message is edited)
odd path
#

And I am just trying to get mine to respond in my server chat...

astral tiger
#

message.content isnt working for some reason, anyone know why?

#

^ tryna create where i can monitor people message

vocal snow
astral tiger
#

OHHH

#

no, actually

#

that's probably my problem

#

ill check

astral tiger
#

❤️

languid sequoia
#

How do you enable message content intents? Are they the same as just the normal intents or are you talking about something different?

ornate linden
#

if I use py async for msg in channel.history(limit=None, oldest_first=True):
and a message is sent in that channel while the loop is running, will it be ignored or entered into the loop?

old vine
#

how to make the bot fetch the message id right after it sends a message?

ornate linden
#

or alternatively await ctx.send(...).id

ornate linden
slate swan
#
    @blacklist.error
    async def blacklist_error(self, error, ctx):
        if isinstance(error, commands.errors.MissingRequiredArgument):
            await ctx.send(embed=discord.Embed(description=f"> you can't blacklist nothing silly :3"))
        elif isinstance(error, commands.MissingPermissions):
            await ctx.send(embed=discord.Embed(description=f"> you don't have the required permission to do this! >:3"))```
#
    @commands.command()
    @commands.has_permissions(administrator=True)
    async def blacklist(self, ctx, word):
        async with self.db.acquire() as c:
            a = await c.fetch("SELECT blacklisted FROM servers WHERE sid = $1", str(ctx.guild.id))

            if word in list(a[0]['blacklisted']):
                await ctx.send(embed=discord.Embed(description=f"> {ctx.author.mention}: {word} is already blacklisted :3", color=self.pink))
            else:
                a = list(a[0]['blacklisted'])
                a.append(word)
                await c.fetchrow("UPDATE servers SET blacklisted = $1 WHERE sid = $2", a, str(ctx.guild.id))
                await ctx.send(embed=discord.Embed(description=f"> {ctx.author.mention}: {word} has been blacklisted :3", color=self.pink))```
#

No error gets printed, it goes into the blacklist error command (I checked with else statmeent). It just doesn't go to missing perms or missing arguments one even though both errors I've gotten are those.

#

Ping me if u know how to fix it :3

#

Hi Guys
How should I change the code to
The user who sent the message gets the role, not the user who added the reaction.

@bot.event
async def on_raw_reaction_add(payload):
    
    channel_id = 1186540419354468353  
    if payload.channel_id != channel_id:
        return

    
    emoji = '👍'
    if payload.emoji.name != emoji:
        return

   
    channel = bot.get_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    user = await bot.fetch_user(payload.user_id)

 
    role_id = 1091865008268386314  
    guild = bot.get_guild(payload.guild_id)
    member = guild.get_member(payload.user_id)
    if role_id not in [role.id for role in member.roles]:
        return

    role = guild.get_role(1091865047682261013)
    await member.add_roles(role)

    await channel.send(f'{user.mention}, You have been added to the identity group {role.name}!')```
naive briar
#

Ugh

slate swan
#

!d discord.Message.author

unkempt canyonBOT
pale cobalt
#

Hey Can Anyone help me with my discord bot i am getting so many errors

old vine
#
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x000001D4AC417460>:
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-IGCSE-Beta\F-lock.py", line 135, in Forumlockcommand
    await interaction.response.defer(ephemeral=True)
  File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 679, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 195, in request
    raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

this is the new error

#

how to solve it?

karmic shore
#

how do I get the id of a user who is mentioned in a message, regardingless if its an @ mention or the ID or their name. For example someone types "@karmic shore" or "1017915595083231283" or "heromaex"

#

the text that Im getting is ONLY that so no need to search for it

slate swan
#

You can't

#

Only the actual mentions

#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

naive briar
slate swan
#

IDs you can use a regex and then match the user

#

Name however, you'd have to look at every single word in the message and check if a user has this as username in the guild/all guilds - which is definitely not recommended

naive briar
#

Nicknames, at least

karmic shore
#

I see yea

slate swan
# drifting mantle get msg author
@bot.event
async def on_message(message):
    channel_id = 1186540419354468353 
    if message.channel.id != channel_id:
        return

    guild = message.guild
    member = message.author

    role_id = 1091865008268386314  
    role = guild.get_role(role_id)
    if role not in member.roles:
        return

    await member.add_roles(1091865047682261013)

    channel = guild.get_channel(channel_id)
    await channel.send(f'{user.mention}, You have been added to the identity group {role.name}!')```
brazen geyser
#

hey guyss, can someone tell me whats wrong with this?

shrewd apex
brazen geyser
#

i forgot that ()

#

thank you so much

shrewd apex
#

np

ashen notch
#

Anyone know if there's a way to see if a DM you send is getting caught in someone's "Message Request" pile?

#

For context, the "you've never joined voice before" notification we have for the bot will attempt to send a message to someone's DMs and if that fails, pings them in the #voice-verification channel. Needing to see if we can re-route to the channel if we're getting thrown into the Message Request pile as well

shrewd apex
#

hmm never thought about this before iirc message request happens when discord flags a dm as spam iirc

sick birch
#

IIRC that's kind of the intention if ephemeral messages

final iron
#

I agree. Ephemeral messages would be a good alternative. Discord doesn’t return the information when your message is hidden in the message requests section

final iron
ashen notch
#

I do only use ephemerals when they hit the buttom

#

And I wouldn't be able to use an ephemeral message on this since it's not being triggered from an interaction, unlike the button

vale stone
#

i have a problem i can't import discord in visual code studio how can i fix that?

brazen geyser
#

hey guyss, can someone tell me whats wrong please, its giving me this error and i dunno what am i doing wrong

sick birch
midnight oracle
#

In a DM with a user, the Bot says "Hi, press the button" and there's going to be a button, but when the user press the button I want that original message to be edited to something else, and so on. Or delete the message and send another one, to keep it clean. How can I archive that?

sick birch
unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None, suppress_embeds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by editing the original message of a component or modal interaction.
midnight oracle
ornate linden
#

How do I set up a Group in a Cog using slash commands?

#

I found GroupCog in the documentation but there's just a few commands I would like to be in a subcommand

#

I just found AppCommandGroup, is that what i'm looking for?

hushed galleon
#

@ornate linden

ornate linden
hushed galleon
#

yup thats it

#

actually an up-to-date answer about discord.py in stackoverflow >.>

final iron
#

pulled straight from umbras gist 😭

upbeat mason
#

are nsfw discord bots against tos and if so are they allowed if commands may only be executed in nsfw channels? (asking for @vapid parcel cause he's lazy!!)

upbeat mason
#

yep

vapid parcel
#

More like i just didnt wanna ask 😭

upbeat mason
#

mainly cause I wanna sleep

vapid parcel
lean shard
#

If anyone's up for it, I need a rubber duck.

I've learned how to do buttons, and I've gotten them to output values in their own function. I want that value to be accessible to the function that's calling it. The guides I'm seeing put the buttons in a class. Somehow, the class thing is not working with my brain bc I'm unsure how to get it to return a value from that class one the user has hit the button.

Is it as simple as return ClassName == "cats"?

#

It could also be that I'm still having a hard time with the class object

sick birch
lean shard
#

Would that make the result of the class equal cats?
I suppoer Im having a little trouble with the idea of getting buttons to do more complicated operations

sick birch
#

if you want to show us your code that'd be helpful

lean shard
#

It is a complete mess atm since i've gone in a few directions to try and get what I want

#

I'll give a breakdown of what I want to do:

This is for adding to a database. Users start the bot and press one of a few options [Create, Delete, Modify]. For create, they can then type in the name of a user on the server and a character they're playing to add them to the sqlite3 database. For modify and delete, they'd be able to sleect from existing player/character combos and do stuff to them

lean shard
#

I've gotta do that sleep thing, so please ping me with any replies after this point

torn sail
#

Also if ur under 18 there’s also stuff for making nsfw bots

naive briar
#

It's very self-explanatory

sick birch
desert kiln
#

I need help, I've done with before, but I lost files for it, I need help with the cogs loader, I don't mind specifying the cogs .py files, as I wanna do it like that anyways

#

Nevermind, I've managed to figure it out, but I do need help with command for reloading the cogs

rugged shadow
#

what is the API endpoint to create a channel?

brazen geyser
#

hey guyss, can someone tell me whats wrong please, its giving me this error and i dunno what am i doing wrong

blazing condor
#

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

pulsar bridge
#

Which do you guys recommend:
Discord.py, py-cord or disnake?
Used discord.py in the past, but a while ago. Didn't really like how they were implementing slash commands...