#discord-bots

1 messages Β· Page 388 of 1

young dagger
#

How can I catch all errors for AsyncIOMotorClient?

#

Motor

formal basin
#

How can I reduce Memory usage on my discord bot its in 1,040 guilds

stark ingot
#

Disabling caches that you do not need as an option. IE if you do not need to use get_member often you can disable the member cache

#

I believe that is a Bot argument

glad cradle
#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

glad cradle
#

disable this intent

formal basin
#

but i think I need it

glad cradle
#

then you can't cut on that

#

you could disable guild chunked at startup

formal basin
#

how?

glad cradle
#

uhm

#

idk if you can in d.py

stark ingot
#

even if you still use it

#

max_messages is another option but generally you dont want to disable it entirely

stark ingot
#

Im not sure, I just know there are settings you can changes to not entirely disable it but to make it take up less memory. You can find more on the docs. I have not personally used it just have seen it mentioned

formal basin
#

like how many max messages the bot can read?

glad cradle
stark ingot
#

It changes how many messages the bot is allowed to store in cache. It is set to 1000 by default

glad cradle
#

e.g 1000, only 1000 messages will be cached, if another message is cached the oldest is removed to make space for the new message

formal basin
#

ill try

#

that

stark ingot
#

It will most likely not have as much of an impact as doing stuff with members as the member counts will be much greater than 1000

stark ingot
#

No, the docs show the object that you have to pass to it which i think is just a group of settings

formal basin
#

also

#

how can I shard my discord bot

#

also

#

I get 2024-09-06 17:02:58 WARNING discord.gateway WebSocket in shard ID 0 is ratelimited, waiting 21.70 seconds this all the time it sends it like 5-10 times

#

before the bot starts up

#

Also everytime I startup my bot

#

it shows this

#

server leave server: `````` owner: None

#

in my logs

dense scaffold
#

Is it possible to allow tenor links to the discord's automod? For example triggering any other links but not the tenor gifs that discord uses.
regex = r"^(?!https:\/\/tenor\.com\/view\/[\w\-]+-gif-\d+).*" Tried this, but i receive an assertion error if i use ?! to handle negative lookahead...

#

Purpose:

  • Triggering any links, excepting tenor gifs that discord has.
slate swan
dense scaffold
slate swan
#

When selecting a GIF and sending it, it's being sent via Discord's CDN

Example:
https://images-ext-1.discordapp.net/external/MzYSek_ukQ4R35_1oaFRRODFWUYHQ4YcHaKBXv5djR4/https/media.tenor.com/tNfwApVE9RAAAAPo/orange-cat-laughing.mp4

dense scaffold
#

uh

#

Not so sure...

dense scaffold
slate swan
#

Sent that via the GIF chooser

#

ah nvm, it's not always

dense scaffold
slate swan
#

or just client sided i guess

dense scaffold
#

Do you know a proper fix for this?

#

cause discord doesn't allow ?!

slate swan
#

how do i get the little hashtag channel thing into my select menu?

#

^ like so

wanton current
#

it's an emoji

slate swan
wanton current
#

it's probably a custom emoji

glad cradle
#

!d discord.ui.ChannelSelect

unkempt canyonBOT
#

class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.

Please note that if you use this in a private message with a user, no channels will be displayed to the user.

New in version 2\.1\.
young dagger
#

datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).

#

What else should I use? What's most common to use

austere heart
wanton current
#

discord.utils.utcnow exists

young dagger
#

Which one is more recommended? datetime.datetime.now(datetime.UTC) vs discord.utils.utcnow

wanton current
unkempt canyonBOT
#

discord/utils.py line 781

return datetime.datetime.now(datetime.timezone.utc)```
sick birch
wanton current
#

is .utcnow() not obvious

sick birch
#

i feel like it could be confused with the deprecated datetime.datetime.utcnow()

wanton current
#

Β―_(ツ)_/Β―

young dagger
#

Thanks guys

#

Is there any easier way to do this?

    await self.counter_collection.find_one_and_update(
        {"_id": "case_counter"},
        {"$inc": {"count": 1}}
    )

    counter_doc = await self.counter_collection.find_one({"_id": "case_counter"})
    return counter_doc["count"]
#

I want to avoid importing ReturnDocument from pymongo

#

If possible

#

So that I can solely relay on AsyncIOMotorClient

sick birch
young dagger
sick birch
#

i don't see a way around it if you need that field

young dagger
#

I want to increase the value and return it

#

That's it

young dagger
#

Do you have any idea how I can add exceptions for the database calls? @sick birch

#

I'm using AsyncIOMotorClient

sick birch
hard kite
#

Uhm get_guild and fetch_guild will only get the guild where the bot is in right?

golden portal
#

ye

sly hamlet
#

So looking through this there seems to be an issue with annotation. I have looked at it and do not see anything that's different from any other of my files I've rewritten the annotation but still unable to figure out what's causing the error. Any thoughts?

golden portal
#

what error

#

show the error

sly hamlet
golden portal
mint pecan
#

How do i get the selected option in a SelectMenu?

sick birch
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

sick birch
#

Oh it’s values

#

!d discord.ui.Select.values

unkempt canyonBOT
mint pecan
golden portal
#

the values will always be the latest one, it gets updated as soon as it gets a new data

mint pecan
#

oh

hard kite
formal basin
#

Does not caching my members mess around with like GET member and stuff like that

formal basin
#

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

hard kite
mint pecan
#

im getting ```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: This field is required

from this select class
```py
class Select(ui.Select):
    def __init__(self, bot: commands.Bot):
        super().__init__(
            placeholder='test',
            options=[
                discord.SelectOption(label=i)
                for i, v in bot.cogs.items()
            ]
        )
        self.bot = bot

what could be the issue?

timber dragon
#

You sure that bot.cogs dict isn't empty?

dense scaffold
timber dragon
#

How?

mint pecan
dense scaffold
mint pecan
dense scaffold
#
class Select(ui.Select):
    def __init__(self, bot: commands.Bot):
        options = [
            discord.SelectOption(label=i)
            for i, v in bot.cogs.items()
        ]
        if not options:  # Ensure there is at least one option
            options = [discord.SelectOption(label='No cogs available')]

        super().__init__(
            placeholder='test',
            options=options
        )
        self.bot = bot

Still, bot.cogs.items() will return empty

timber dragon
#

options = [...] or [discord.SelectOption(...)] works too

dense scaffold
#

and also make sure that there is at least one option in the Select component.

dense scaffold
#

Won't fix they're issue, because bot.cogs.items() will be empty

#

That's what causes the HTTPException

#

Also i don't really like d.py, how they work with views, i prefer disnake.

timber dragon
#

Fallback to a list with one entry if the other list is falsey (empty)

dense scaffold
dense scaffold
dense scaffold
#

That was a fallback example to ensure there's atleast 1 option

timber dragon
#

Fair

dense scaffold
#

I believe they are trying to get they're cogs?

timber dragon
#

The class is either somehow constructed before any cogs are added or they aren't using cogs yes

dense scaffold
#

print(bot.cogs.items())
@mint pecan

mint pecan
timber dragon
#

How and where is that class constructed?

mint pecan
dense scaffold
#

It's obvious already, ensure that bog.cogs.items() it's not empty, i cannot help you with your internal code, we don't know it.

timber dragon
#

Maybe just send that code

dense scaffold
#

Oh, was the bot completely up? This could be a issue if you invoke the command before the bot being run

mint pecan
timber dragon
#

And where do you load your extensions?

mint pecan
timber dragon
#

Is this class constructed before or after that?

dense scaffold
#
class Select(ui.Select):
    def __init__(self, bot: commands.Bot):
        # only set placeholder here, leave options empty for now
        super().__init__(placeholder='test', options=[])
        self.bot = bot

    async def callback(self, interaction: discord.Interaction):
        # this will be called when the menu is interacted with.
        # lazily load options only when needed
        self.options = [
            discord.SelectOption(label=i)
            for i, v in self.bot.cogs.items()
        ]
        if not self.options:  # handle the case if no cogs are loaded
            self.options = [discord.SelectOption(label='No cogs available')]

        # now do something with the interaction and options
        await interaction.response.send_message(f'Selected cog: {self.values[0]}')
mint pecan
timber dragon
#

Mayhe construct it after the extensions are loaded?

mint pecan
#

how do i know its loaded

timber dragon
#

Why is at bot init anyways

dense scaffold
timber dragon
dense scaffold
timber dragon
#

They need to construct the class after, not print something

dense scaffold
timber dragon
#

And on_ready shouldn't be used for that anyways

#

As it can be called multiple times and while running

dense scaffold
#

????

timber dragon
timber dragon
dense scaffold
#

How is on_ready running multiple times?

timber dragon
#

Welp

dense scaffold
#

snipy here

timber dragon
#

I just said why?

dense scaffold
timber dragon
glad cradle
dense scaffold
glad cradle
#

if you want something that is called only once you should use setup_hook (d.py) or in disnake you can subclass the client that you are using and edit the start method to call a custom made method

dense scaffold
#

And it's not me having issue here, it's @mint pecan with cogs, but they use d.py

glad cradle
timber dragon
#

Thank you Snipy whoever you are that they trusted you over me lol

dense scaffold
timber dragon
#

Aha

dense scaffold
#

I didn't know this on_ready thing, never happened to log multiple twice on run

dense scaffold
#

eitherway, we don't do actions on_ready, task util ready

#

on_ready has just a log info

#

So i still don't see this being a issue

dense scaffold
timber dragon
#

Sure it's not an issue for you

#

But most people load their exts etc in it which can lead to errors

dense scaffold
#

Doesn't mean they have to keep the event

timber dragon
dense scaffold
timber dragon
#

They might construct the view in on_ready because you said that

dense scaffold
#

@mint pecan Hope you didn't understand that from my context, on_ready shouldn't be used for any actions.

glad cradle
#

It can be used for some actions, you just need to be aware of the fact that it's potentially not called once (and so don't rely on that)

dense scaffold
#

yeah not recommended

#

Would rather make a task, wait till ready

timber dragon
#

Or an if-statement with a botvar etc yes

dense scaffold
timber dragon
#

Same

glad cradle
#

I use txt files as db... we're not the same πŸ₯± /j

dense scaffold
timber dragon
#

Absolute πŸ’€ moment

dense scaffold
#

😭

glad cradle
#

/j = joking

timber dragon
#

at least use json /s

dense scaffold
mint pecan
# dense scaffold <@937926761121988668> Hope you didn't understand that from my context, `on_ready...

well i got another error when i try to pass the bot class

AttributeError: 'ProactorEventLoop' object has no attribute '_closed'
bot.help_command = views.HelpCommand(bot)
class HelpCommand(commands.MinimalHelpCommand):
    def __init__(self, bot: commands.Bot):
        super().__init__()
        self.bot = bot


    async def send_pages(self) -> None:
        select = ui.View()
        select.add_item(Select(self.bot))
        await self.get_destination().send(view=select)

class Select(ui.Select):
    def __init__(self, bot: commands.Bot):
        print(bot.cogs)
        print(bot)
        super().__init__(
            placeholder='test',
            options=[
                discord.SelectOption(label=i)
                for i, v in bot.cogs.items()
            ]
        )
        self.bot = bot
timber dragon
glad cradle
dense scaffold
mint pecan
timber dragon
#

Uh don't do that anyways

mint pecan
#

the field error remains the same

#

yet i got another one

dense scaffold
timber dragon
#

You can access your bot from self.context.bot
The help command class takes some options and that'll cause issues when the lib tries to construct it

tldr: remove the __init__

glad cradle
mint pecan
dense scaffold
#

It's a atr error from ProactorEventLoop, I don't even see it there

glad cradle
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

mint pecan
# glad cradle could you share the full traceback?
Exception ignored in: <function BaseEventLoop.__del__ at 0x0000014F9CE9D620>
Traceback (most recent call last):
  File "D:\Python\Python312\Lib\asyncio\base_events.py", line 725, in __del__
    if not self.is_closed():
           ^^^^^^^^^^^^^^^^
  File "D:\Python\Python312\Lib\asyncio\base_events.py", line 722, in is_closed
    return self._closed
           ^^^^^^^^^^^^
AttributeError: 'ProactorEventLoop' object has no attribute '_closed'
dense scaffold
#

ig they use ProactorEventLoop._closed somewhere, but it doesn't have an atr for closed

#

yep

timber dragon
#

Windows stuff and fixed in 3.12 or something iirc

glad cradle
dense scaffold
#

that's what atr error says πŸ‘€

mint pecan
dense scaffold
#

Is it possible to allow tenor links to the discord's automod? For example triggering any other links but not the tenor gifs that discord uses.
regex = r"^(?!https:\/\/tenor\.com\/view\/[\w\-]+-gif-\d+).*" Tried this, but i receive an assertion error if i use ?! to handle negative lookahead...
Purpose:

  • Triggering any links, excepting tenor gifs that discord has.
#

@timber dragon Do you know anything about this?

#

discord doesn't allow ?! chars for negative lookahead :/

#

crap

#

nobody knows 😭

timber dragon
#

Have you tried the disnake server?

#

I know regex a little bit but not discord's automod

dense scaffold
timber dragon
#

Bruh

dense scaffold
#

but snipy doesn't know for sure what discord accepts as regexes

#

I did open a post there now, hoping to get a proper reply, if someone knows how to make a negative lookahead over tenor...

timber dragon
#

Discord devs server? .gg/discord-developers

dense scaffold
#

I did not try there

#

I am not in that server from this acc, Can you send me a invite in dms?

timber dragon
#

Works

dense scaffold
#

Oh i didn't know lol

#

thanks πŸ˜„

timber dragon
dense scaffold
#

Let's see

timber dragon
dense scaffold
#

But it's a way to bypass still

#

to not use regex

#

had hope this could of been done with regex 😭

#

just realised it wont fix this issue

#

nvm

glad cradle
#

what they suggested is still regex, the solution you were looking for could have been overcomplicated

dense scaffold
#

regexing words, not an actual regex handling them all, with just 1 regex... But yeah, i tested it does work

sly hamlet
glad cradle
#

you may want str | None ? also i think you didn't got app commands quite right, they can't accept any arbitrary number of arguments (like prefixed commands) you need to define every single argument that you need in the signature, you could make some of them optional tho

main socket
#

When doing a User invite , for a discord bot. Is it pretty much just an automation tool for a discord account ?

sly hamlet
glad cradle
sly hamlet
glad cradle
#

I see

sly hamlet
young dagger
#

What is wrong?

    # Decorator to check if the action (warn, ban, kick, etc.) can be performed.
    def check_actionable(self, action_type: str):
        def decorator(func):
            @wraps(func)
            async def wrapper(ctx, member: discord.User = None, *args, **kwargs):
                if member.id == ctx.author.id:
                    await ctx.send(f"{self.x_emoji} You cannot {action_type} yourself.")
                    return
                if member.bot:
                    await ctx.send(f"{self.x_emoji} You cannot {action_type} a bot.")
                    return
                return await func(ctx, member, *args, **kwargs)
            return wrapper
        return decorator

    # Warn command
    @commands.command(name="warn", description="Warn a user.")
    @commands.guild_only()
    @commands.cooldown(1, 5.0, commands.BucketType.user)
    @check_actionable("warn")
    async def warn(self, ctx, member: discord.User = None, *, reason: str = None):```
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: Moderation.check_actionable() missing 1 required positional argument: 'action_type'

glad cradle
#

args: str | None = None

sly hamlet
slate swan
glad cradle
slate swan
glad cradle
#

you could try to find a custom emoji similar to that

slate swan
unreal flare
#
import random
import os


def get_response(message: str) -> str:
    person_message = message.lower()

    if "website" in person_message:
        return "**Official airpodgate site [censored for privacy] **"


    if "buy" in person_message:
        return "**you can purchase by opening a ticket or visiting [censored for privacy]**"


async def send_message(message, user_message, is_private):
    try:
        response = get_response(user_message)
        await message.author.send(
            response) if is_private else await message.channel.send(response)

    except Exception as e:
        print(e)


TOKEN = 'no peaking'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print(client.user, "is now running!")


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    username = str(message.author)
    user_message = str(message.content)
    channel = str(message.channel)

    if user_message[0] == '?':
        user_message = user_message[1:]
        await send_message(message, user_message, is_private=True)
    else:
        await send_message(message, user_message, is_private=False)


client.run(TOKEN)
#

hey everyone this is my current bot for my server -- I have two questions, first how can I make it so it only sends the message if I say it? and second how do I make it link to a chanel, I tried to do #buy (which is a valid chanel in my server), but it didn't work

stark ingot
stark ingot
# unreal flare ```import discord import random import os def get_response(message: str) -> st...

You can check if message.author.id is the same as your user ID
Also you can mention a channel like this #discord-bots [#discord-bots](/guild/267624335836053506/channel/343944376055103488/) where that is the channel ID.
Also in general you should probably use discord.ext.commands for creating commands instead of processing the string yourself but if this is just a small project that is up to you if you do not want to bother.

tender bobcat
#

you can obtain the channel id from message from message.channel.id

stark ingot
tender bobcat
#

ah

#

(I didn't thought it was literally a URL link but a relation between

unreal flare
tender bobcat
#

umm, how many language you mixed together?

stark ingot
#

other than your syntax being wrong yes

unreal flare
#

like this?

wanton current
#
  1. don't use parenthesis
  2. id are ints
  3. no colon after return
unreal flare
#

gotcha thanks

#

any idea on how I can get my author id?

tender bobcat
#

1273475167976423577

stark ingot
#

do you have developer mode on discord?

tender bobcat
#

here you go

unreal flare
tender bobcat
#

you would go to Setting -> Advanced -> Developer Mode

tender bobcat
#

and set it on

stark ingot
#

This article explains it all

unreal flare
#

1273475167976423577

tender bobcat
#

and right click on your user and click copy id

tender bobcat
#

tbf, where the colon come after return come from (I mean which programming language

slate swan
#

how do i return the message id of a message i sent?
await interaction.response.send_message(content=":clock3: Denying post...", ephemeral=True)

#

context: message after hitting submit on a modal

unreal flare
tender bobcat
unreal flare
#

this doesn't seem to be working -- I keep getting the error "'str' object has no attribute 'author'" does anyone mind helping me

slate swan
wanton current
#

send_message doesn't return a Message

tender bobcat
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None, poll=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
tender bobcat
#

oh, then

#

!d discord.Interaction.message

unkempt canyonBOT
slate swan
slate swan
#

damn im stupid lol i cna just edit original response since i didnt defer

unreal flare
tender bobcat
tender bobcat
#

is message discord.Message?

unreal flare
#

should I do

tender bobcat
#

provide the code

#

for more context

wanton current
unreal flare
#
import random
import os


def get_response(message: str) -> str:
    person_message = message.lower()

    if "website" in person_message:
        return "**Official airpodgate site  [privacy]**"


    if "buy" in person_message:
        return "**you can purchase by opening a ticket at #buy or visiting [privacy]**"
    
    if "exec vendor" in person_message:
        
        if message.author.id == 1273475167976423577: 
                return "test"


async def send_message(message, user_message, is_private):
    try:
        response = get_response(user_message)
        await message.author.send(
            response) if is_private else await message.channel.send(response)

    except Exception as e:
        print(e)


TOKEN = 'no peaking'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print(client.user, "is now running!")


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    username = str(message.author)
    user_message = str(message.content)
    channel = str(message.channel)

    if user_message[0] == '?':
        user_message = user_message[1:]
        await send_message(message, user_message, is_private=True)
    else:
        await send_message(message, user_message, is_private=False)


client.run(TOKEN)```
tender bobcat
#

message: str

unreal flare
#

wdym?

tender bobcat
#

it is not discord.Message, so obviously you cannot

unreal flare
#

oh I see

tender bobcat
#

look at line6

wanton current
#

also, would really recommend looking into commands framework if you're looking to create commands instead of doing all of the logic yourself

unreal flare
#

nah because I don't want it to be a command

tender bobcat
#

?

unreal flare
#

I own a server and a lot of people have issues I guess reading on how to buy -- so when they say "how do I buy" or something like that then the bot guides them there

tender bobcat
#

but it is already a command

unreal flare
#

no sorry, you might be confused -- I don't want it to be a command I just want it to reply if they say something

unreal flare
tender bobcat
#

give discord.Message to the function, not str

unreal flare
#

so

#

def get_response(message: discord.Message) -> str:
person_message = message.lower()

#

or def get_response(message: discord.Message) -> discord.Message:
person_message = message.lower()

main socket
# glad cradle wdym?

When your inviting/ adding a bot there’s an option between guild invite or user invite

tender bobcat
#

*ignore the dm/group part, it is not possible actually

hushed galleon
#

it should be, you just have to explicitly set it in your command's allowed contexts

dapper cobalt
#

is it possible to append a parameter in a command to the command's check parameters?
for illustration, this is my command's code:

@commands.command()
@has_profile()
async def profile(self, ctx, member: disnake.Member = None):

and this is my check's code:

def has_profile():
    async def predicate(ctx, member: disnake.Member = None):
        member = member or ctx.author

        data = PROFILES.find_one({"_id": str(member.id)})

        if not data:
            raise NoProfileFound(member)
        else:
            return True

    return check(predicate)

Apparently, the member in the command's parameter isn't passed to the check, so it returns member as None which is default. I want to pass the member passed in the command to the check.

glad cradle
unkempt canyonBOT
tender bobcat
hushed galleon
#

in the case of d.py, they're available with the slightly confusing names @allowed_contexts() and @allowed_installs()

#

you need both the PRIVATE_CHANNEL interaction context and the USER_INSTALL installation context for a command to be available in other DMs, after being user-installed

tender bobcat
#

hmm

#

but:

By default, contexts includes all interaction context types.
Need to check if dpy feature the toggle of options

hushed galleon
#

ergh, the discord API docs are incorrect

#

i made an issue for it a couple weeks ago discord/discord-api-docs#7108

tender bobcat
#

ah

#

!d discord.app_commands.allowed_contexts

unkempt canyonBOT
#

@discord.app_commands.allowed_contexts(guilds=..., dms=..., private_channels=...)```
A decorator that indicates this command can only be used in certain contexts. Valid contexts are guilds, DMs and private channels.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.

New in version 2\.4\.

Examples...
tender bobcat
hushed galleon
#

from my testing the defaults were always GUILDS + BOT_DM and GUILD_INSTALL

tender bobcat
#

Gonna fix my bot later and sync later

#

if I remember

#

(Would be trolling if you can use anywhere except bot dm

hushed galleon
#

the CommandTree can let you assign defaults for all commands via the allowed_contexts= and allowed_installs= parameters, though if you use a plain commands.Bot you'll have to assign to the attributes instead, which are technically undocumented

tender bobcat
#

Still just gonna use the decorator, too lazy

#

that what I do for user_install anyway

tender bobcat
# lament depot

hope they fix the feature instead of fixing the docs, but well

hollow kiln
#

How can i host discord bot in phone anyone can help me?

slate swan
#

not a good idea

zenith pilot
#

can I host a discord bot for free ?

viscid hornet
unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

slate swan
dry orbit
#

heh

#

lvl up karte raho

zenith pilot
slate swan
#

one or more

dry orbit
#

how to level up so that i can talk in vc

slate swan
#

depends the bots, servers, intents, etc.

slate swan
zenith pilot
dry orbit
#

talking here ?

slate swan
#

anywhere in the server

dry orbit
#

but no one is active here

slate swan
#

because it's a topical help channel, and there are not people needing help 24/7

dry orbit
#

hmm

#

you do coding ?

slate swan
slate swan
dry orbit
#

hehe

#

nice one πŸ˜‰

zenith pilot
#

I am newbie 😦

dry orbit
#

πŸ™‚

zenith pilot
#

in development

dry orbit
#

hehe same

zenith pilot
#

yea I can tell

dry orbit
#

development like what ?

dry orbit
zenith pilot
#

making any projects

dry orbit
#

scripting ?

dry orbit
zenith pilot
#

we should only talk about discord bot related contents here

dry orbit
#

oh

slate swan
dry orbit
#

for kali linux

slate swan
#

few days, as you can't do much with it

#

i mostly have seen it being used to automate the build and release of softwares

#

other than the basic commands e.g. ls etc. that are used every day by lots of people

dry orbit
#

!user

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

paper forge
#

can somone help me to make a moderation discord bot

shadow loom
mint pecan
#

does View class have an attribute where i can access the context/interaction?

sick birch
mint pecan
#

im getting TypeError: help_command must be a subclass of HelpCommand
trying to set custom help command

class HelpCommand(commands.MinimalHelpCommand):
    ...

bot = Bot(command_prefix=..., intents=..., help_command=HelpCommand)

how do i fix?

formal basin
#

Can a bot read very long messages?

slate swan
#

why not

golden portal
mint pecan
#

my selectmenu's callback succeeded but it still says "This interaction failed"?

stark ingot
#

How are you responding to the interaction? My guess it that you are sending a message instead of responding. Can you show your callback

stark ingot
mint pecan
#

yes

stark ingot
slate swan
drifting arrow
#

pretty sure it does anyway.

stark ingot
#

It does not because the bot has this information cached

wispy swift
#

how can i interact with a button with python?

#

Like, i put in a message id and i interact with a button

copper flume
#
0|bot      | [2024-09-08 15:49:11] [WARNING ] discord.gateway: Shard ID 0 heartbeat blocked for more than 10 seconds.
0|bot      | [2024-09-08 15:49:21] [WARNING ] discord.gateway: Shard ID 0 heartbeat blocked for more than 20 seconds.
0|bot      | [2024-09-08 15:49:53] [WARNING ] discord.gateway: Can't keep up, shard ID 0 websocket is 32.5s behind.```

My bot didn't respond for maybe 30minutes I don't know why and I got these logs
slate swan
#

You have code that is blocking your bot

copper flume
slate swan
#

It can be lots of other things

#

Those are just the most common and examples

copper flume
#

my bot had uptime for 10 days and didn't face issues but got this for 3 days of uptime

copper flume
hollow current
#
from discord.ext import commands
from discord import FFmpegPCMAudio

intents = discord.Intents.all()

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

@client.event()
async def on_ready():
    print("Bot Is Running!")

@client.command(pass_context = True)
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        voice = await channel.connect()
        source = FFmpegPCMAudio("music.wav")
        player = voice.play(source)
    else:
        await ctx.send("Error: Your aren't in a voice channel!")

@client.command(pass_context = True)
async def leave(ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send("Call Lefted")
    else:
        await ctx.send("Error: Im not in a call")


the bot joins the call but it doesnt play the music

#

i have client.run() btw but that includes the token so its not in there

paper forge
#

hello i need help with my discord bot i have lot of issue when i try to make a whitelited command so only whitelited people can use the command i cant please help me and dm me or ping

scarlet tiger
drifting arrow
#

Probably because duration_seconds is a string? Try print(type(duration_seconds)) if it's a straight number, then just do int(duration_seconds) > 1814400

young dagger
#

Already solved

#

Thanks @drifting arrow

drifting arrow
#

Alright. Thanks. Wanna share with the class what the issue was?

young dagger
drifting arrow
slate swan
#

Ho chat

#

So I user installed my bot

#

How do I use the commands

hushed galleon
# slate swan How do I use the commands

with nextcord? looking through their docs it doesnt seem like they support setting interaction and installation contexts for slash commands yet, only in master branch

slate swan
#

BREH

hushed galleon
#

you can't install both libraries together, they share the same package and will overwrite each other's files

#

or more specifically nextcord comes with both a nextcord and discord package, the latter of which is a copy to help people with migrating from dpy to nextcord

sick birch
#

Hello, your message has been deleted as it violates rule 6

stark ingot
#

And ethics doggokek

void whale
#

How do i fix this guys my nothing is happening here

swift siren
#

.rtfm

smoky sinew
#

@swift siren #bot-commands

swift siren
#

I wanna see the object for onboarding

smoky sinew
#

member.flags.completed_onboarding

void whale
#

how do i fix this sorry im new

slate swan
#

No such file

potent spear
#

You see PS written before your file path? You most likely want to get rid of that, click the + arrow on the terminal and select command prompt, that should work

potent spear
#

Yup it is definitely better, I blame myself for not knowing it better

potent spear
smoky sinew
sick birch
smoky sinew
#

and you can run all command prompt commands in power shell

potent spear
sick birch
potent spear
#

Not on pc atm πŸ˜…

sick birch
#

you should rename it to bot.py

void whale
sick birch
#

py bot.py should work

void whale
mint pecan
#

how do i check if a Command object is a group?

dense scaffold
# mint pecan how do i check if a `Command` object is a group?
@bot.command()
async def check_command(ctx: commands.Context, command_name: str) -> None:
    command = bot.get_command(command_name)
    if isinstance(command, commands.Group):
        await ctx.send(f"'{command_name}' is a group command")
    else:
        await ctx.send(f"'{command_name}' is a regular command")
young dagger
#

Can ctx.guild.icon.with_format('png').url be directly used as an emoji in Discord buttons?

dense scaffold
#

or <a:name:id> if emoji is animated

#

But you don't need animated

#

Won't work with animated, but letting you know that formats are similiar.

young dagger
dense scaffold
#

as emoji

#

I recommend uploading the emojis to the bot directly

young dagger
#

I could but then I have to do it manually

#

Thanks anyway

dense scaffold
#

You literally upload the emoji, and just use it as set in the example, i don't find it overcomplicating.

dense scaffold
young dagger
dense scaffold
#

Oh, i see your point now...

dense scaffold
#

1 moment.

young dagger
#

Sure

dense scaffold
#
async def download_guild_icon(url: str) -> BytesIO | None:
    """Downloads the guild icon from the provided URL and returns the image data as BytesIO."""
    async with aiohttp.ClientSession() as session:
        response = await session.get(url)
        if response.status == 200:
            image_data = await response.read()
            return BytesIO(image_data)
        else:
            print(f"Failed to download icon, status code: {response.status}")
            return None

@bot.command()
async def converticon(ctx: commands.Context):
    """Converts the guild's icon into an emoji and uploads it to the guild."""
    guild = ctx.guild

    if not guild or not guild.icon:
        await ctx.send("This guild either doesn't exist or has no icon set.")
        return


    icon_url = guild.icon.with_format('png').url
    image_data = await download_guild_icon(icon_url)

    if image_data:
        try:
            emoji_name = "guildicon"
            emoji = await guild.create_custom_emoji(name=emoji_name, image=image_data.getvalue())
            await ctx.send(f"Successfully created emoji: {emoji}")
            # If created add emoji id to database, You can use the emoji that way, ensure your database in case emoji gets deleted.
        except Exception as e:
            await ctx.send(f"Failed to upload emoji: {e}")
    else:
        await ctx.send("Failed to download the guild icon.")
#

@young dagger

young dagger
#

That is interesting. Thanks @dense scaffold

dense scaffold
#

No worries !

solar pollen
#

How can I make discord.py use docstring in the callback as the description?

dense scaffold
#

If your bot is interaction commands, to add description to options you can use for example:

async def example(self, inter: Whatever, user: Member, action: DefineAction) -> None:
"""This is command desc.

Parameters
----------
user: This will be user parameter desc.
action: This will be action parameter desc.
"""

@solar pollen

shrewd fjord
naive briar
#

There are two of them!

glad cradle
shrewd fjord
#

cool

dense scaffold
hearty wind
#

C:\Python312\python.exe: can't open file 'C:\Users\Owner\.cursor-tutor\%USERPROFILE%\dylanrustbot\bot.py': [Errno 2] No such file or directory
PS C:\Users\Owner.cursor-tutor%USERPROFILE%\dylanrustbot>
how do i fix guys im new

#

i have the .py

fast osprey
#

The file is just called .py...?

hearty wind
#

i cant get it bot to turn on

fast osprey
#

But your'e trying to run it as bot.py

hearty wind
fast osprey
hearty wind
#

C:\Python312\python.exe: can't open file 'C:\Users\Owner\.cursor-tutor\%USERPROFILE%\dylanrustbot\bot.py': [Errno 2] No such file or directory
PS C:\Users\Owner.cursor-tutor%USERPROFILE%\dylanrustbot>

dense scaffold
hearty wind
dense scaffold
#

Also on visual studio code you can use run without debugging from the top of vsc app

#

Try this, and lmk if it works

fast osprey
#

And what is your code?

dense scaffold
dense scaffold
hearty wind
#

brings me here

dense scaffold
#

install the first one

hearty wind
#

it is

#

has been

dense scaffold
#

Ok, now restart vsc

#

or do ctrl + shift + p and refesh cache and restart

hearty wind
#

i tried a new code and it turned on

dense scaffold
#

using the vsc run button?

hearty wind
dense scaffold
#

Let me know if you have further more issues.

teal swallow
#

Hello everyone.
If you need any help with web and AI development, please feel free to contact me.

last orchid
#

?!!?!

solar pollen
golden portal
mild token
#

what error we will get if we try to remove the user who isnt in thread?

#

or it will not give error?

fast osprey
#

Very quick try it and see exercise

dense scaffold
#

This way you can add description to your command

dense scaffold
smoky sinew
dense scaffold
#

Was showing him a change on a previous code i sent

#

I know, it's previous code i sent, just showing how to do the description

dense scaffold
#

They didn't mention at first that this was for hybrid, bot logically it's the same.

smoky sinew
dense scaffold
dense scaffold
#

This was what they said, and right after is my example.

#

Which is literally the same for hybrid, it's a 2 words change.

upper sorrel
#

anyone care to help, i am trying to get my bot to respond when certain words are said, even in the middle of a sentence. i under stand the
"If message.content.startswith('Example'): "
But it only works is if it starts with the word, Any idea?

glad cradle
#

!e
you know you can do this

print("word" in "just a normal sentence containing your word")
unkempt canyonBOT
fast osprey
#

Regex would probably be useful to learn here

glad cradle
#

yeah or that too

smoky dragon
#

Hello friends, I'm making a discord bot and I'm sure I'll have questions to ask. Just wanted to say hello there and hope yall are having a good day so far

fast musk
#

hi

fast osprey
young dagger
#

What is wrong?

        elif any(message.guild.get_channel(message.channel.id) is None for message.channel.id in message.raw_channel_mentions):
            modlog_message = "Posted an invite"
quick gust
#

Tell us, what's the error?

young dagger
#

Expected type 'collections.Iterable', got '() -> list[int]' instead

stark ingot
young dagger
stark ingot
#

Then idk

fast osprey
#

traceback?

upper sorrel
#

is there an option for the bot to pick from a list of options to reply to a word that is said?

wanton current
#

yes

upper sorrel
young dagger
fast osprey
#

That's an error message, not a traceback

young dagger
#

Do you know how to solve this error?

fast osprey
#

You should start by being able to get a traceback

young dagger
#

Well I was trying to solve the error to begin with

fast osprey
#

You solve the error by getting the traceback

#

The library by default logs the traceback. Something you are doing is interfering with that

upper sorrel
#

Ok i ran this, it shows no errors, but still does nothing when promted with "Hello" in discord.

#

i am still learning ish but i am not sure what i did wrong?

fast osprey
#

You should be getting a warning in your console

upper sorrel
#

i got nothing

fast osprey
#

Terminal

#

no idea what the hell "problems" is KEK

upper sorrel
#

Sorry, This terminal?

fast osprey
#

How are you starting the bot?

upper sorrel
#

visual studio code amt

fast osprey
#

In code

upper sorrel
#

client.run('Tokencode')

#

thats how i keep starting it

#

then control C to stop it.

#

i had some basic stuff working this morning, but not it does nothing so i was curious.

fast osprey
#

You should be getting logs from the library

#

Can you send your full code? In text, preferably, not a screenshot

#

Also which library are you using?

upper sorrel
#

import discord
import random
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True
client = discord.Client(intents=intents)

msg_list = [
'Hello! How can I help you today?',
'Good day! What can I do for you?',
'Hi there! Need any assistance?',
'Hey! What’s up?']

@client.event
async def on_ready():
print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):

if message.author == client.user:
    return


if 'Hello' in message.content.lower():
    
    response = random.choice(list)
    await message.channel.send(list)

client.run('Token')

exotic hazel
#

'Hello' would never be in the str.lower() right? It should be 'hello'

fast osprey
#

If you ran this code in dpy at least, you would get several logs in your console

upper sorrel
#

i am not sure then, guess i screwed up somewhere.

fast osprey
upper sorrel
#

its giving me no errors in any of my windows.

upper sorrel
# fast osprey ?

without sounding completely brain dead, What do you mean by library?
I was told the only thing i would need to do before doing anything is make sure i do this
import discord
import random
from discord.ext import commands

fast osprey
#

If you installed python fresh, it would not know what import discord means. You did something

#

(installed a library)

upper sorrel
#

i installed python through MS store
Then installed visual
Then started the project

#

thats all i have done in means of prep

fast osprey
#

python does not ship with a discord module

upper sorrel
#

Ok, so i would have to download the discord module?
i am assuming from discord developer page?

fast osprey
#

Someone already did on your installation if you aren't getting an error from import discord

upper sorrel
#

Ok, should i be worried?

#

it sounds worrying...

fast osprey
#

You probably followed some steps you aren't remembering. Do you know what version of python you're running through vsc? Can you run python manually on a command line?

#

That doesn't necessarily mean that's what vsc is using

upper sorrel
#

Hmmm

fast osprey
#

When you hit run on vsc, it runs some python executable

upper sorrel
#

/AppData/Local/Microsoft/WindowsApps/python3.12.exe

#

thats the first thing that shows up when hitting run

fast osprey
#

Can you run that exact exe and pass -m pip freeze, then send the output here?

upper sorrel
#

apparently not

#

-m pip freeze
File "<stdin>", line 1
-m pip freeze
^^^
SyntaxError: invalid syntax

fast osprey
#

Run it all in one line on command line

#

you're currently entering the python interpreter which you don't want

#

so exit() to get out of the interpreter, then on the command line .../python.exe -m pip freeze

upper sorrel
#

i feel like im doing something wrong here.

#

apologies

exotic hazel
#

exit()
^run that

upper sorrel
#

it closes python

fast osprey
upper sorrel
#

not sure if this means anything

fast osprey
#

It does, someone installed discord.py at some point (somewhat recently)

upper sorrel
#

ok, is there a way to delete? Restart?

#

im not quite sure what to do here.

fast osprey
#

No, that's fine, but it's odd that you don't remember doing that

#

because this doesn't happen by default

upper sorrel
#

my first time, im on bed rest and needed a hobby while i recover.

#

this hobby was suggested

fast osprey
#

It's fine, so you have discord.py installed, it should be giving you output. Do you know how to run the bot yourself via command line and not through vsc?

upper sorrel
#

i do not, i was told vsc was the most friendly way to start this project.

fast osprey
#

Some part of your setup is eating all of the library's output, which is going to make any debugging difficult

#

You can look at that if you want to. The core issue why you aren't getting this code working is that your code is not requesting the message_content intent, which is required to receive message content. https://discordpy.readthedocs.io/en/latest/intents.html has a detailed description of that concept

upper sorrel
#

Would i be better off deleting the project and starting again to clear the library's output? starting fresh if thats a thing?

fast osprey
#

It's probably something wonky with vsc to be honest. You could try running it on your own outside of vsc

#

But honestly I don't know how you'd get in that state

upper sorrel
#

ah i see.

fast osprey
#

Maybe something in the output tab? shrug

upper sorrel
#

Nothing again.

#

i will either try something else other than VSC or maybe move onto another project.

#

But Thank you for trying help figure this mess out.

fast osprey
#

Running it yourself is just going into the command line and doing .../python.exe <path/to/your/bot/file>

young dagger
#
elif any(message.guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):
fast osprey
#

You need to get a traceback to effectively debug

#

again, it is something you are doing that is removing it

young dagger
fast osprey
#

By default, when you hit an error the library will output the traceback

#

If you are not seeing a traceback, something in your code is interfering with that

fast osprey
#

So your code runs just fine?

young dagger
#

So far yes

young dagger
sick birch
young dagger
#

Yes

sick birch
#

can you paste a couple lines before and after for context

young dagger
#

The warning dissapears with async def lfg_checks(self, message):

sick birch
#

that makes sense

#

it can't warn you anymore because it doesn't know what the types of anything are

young dagger
#

So it's excepting bool back

#

The message is a discord message

#

I don't see the problem

sick birch
#

this is pycharm right?

young dagger
#

Correct

fast osprey
#

In general, ide's complain about shit all the time, really up to you if it's worth making them happy

sick birch
#

they use their own type checker which is known to be buggy at times

young dagger
#

What's so special about any(message.guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):

sick birch
#

that particular line of code seems fine to me, i'd ignore the type error

#

maybe write some tests if you want to be sure

sick birch
slate swan
#

Hello

#

i welcome anyone who wanna ask about me and techπŸ˜‹

young dagger
sick birch
#

this is readable and concise

#

i'd leave it be

#

i guess you could also do like, any(map(message.guild.get_channel, message.raw_channel_mentions))

#

to see if any of the mentions in the message are in your cache

young dagger
sick birch
#

pycharm thinks its a method for whatever reason

young dagger
sick birch
#

yeah it's the same thing there

young dagger
#

Maybe I should just remove the type hinting

#

My goal was to create a 100% warning free bot

sick birch
young dagger
sick birch
#

yes, now you can't type check anything in that function

#

the choice is obvious when it comes to not being able to type check anything in a function vs having one false warning (which can be ignored with a directive)

#

pycharm probably has some option to suppress warnings in the editor. i'd recommend running mypy or pyright for actual type checking in CI or whatever before going to production anyway

young dagger
#

It actually disappears with async def message_checks(self, message) -> bool:

sick birch
#

that's not a fix

young dagger
#

So specifying that the message is a discord.Message is a problem

sick birch
#

no, it's not

#

there is no problem here beside pycharm itself

#

the code is fine, it will work, is readable and concise

#

i am not sure what more you want to do here

young dagger
#

Thanks

#

Do you know any other Python IDE that works better with discord.py?

sick birch
#

personally i run neovim with pyright as my lsp, and also run pyright in CI so i don't get failed ci where it works locally

#

mypy by the PSF and pyright by microsoft are the two big ones

young dagger
#

Both in Pycharm

sick birch
#

πŸ€·β€β™‚οΈ like i mentioned pycharm type checker is known to be buggy at times

slate swan
#

but why need to write code differently?

upper sorrel
#

16 hours justifed for a noob such as myself.

weak iris
#

Im trying to make a basic discord bot, but im probably having issues with permission. So i clicked the Admin general permission but there is no save button. What am i missing here?

#

looks like this is just a tool to calculate the permision integer, but where do i fit that in ?

molten bobcat
#

I have experienced developers here, feel free to DM us anytime.

fast osprey
upper sorrel
#

again thank you! Also apologies for being a bit slow when trying understand what you was saying, brand new to this.

fast osprey
#

nw we all start somewhere, always feel free to ask questions

merry cliff
#

In the installation section

young dagger
#
    async def find_case(self, case_id: int) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
        collections = {
            "warnings_collection": self.warnings_collection,
            "kicks_collection": self.kicks_collection,
            "bans_collection": self.bans_collection,
            "mutes_collection": self.mutes_collection,
            "modnotes_collection": self.modnotes_collection,
        }

        for collection_name, collection in collections.items():
            case = await collection.find_one({"case_id": case_id})
            if case:
                return case, collection_name

        return None, None
#

Why am I getting Expected type 'tuple[dict[str, Any] | None, str | None]', got 'tuple[Mapping[str, Any], str]' instead

#

@sick birch Any idea about this one?

fast osprey
#

What type is case here?

young dagger
young dagger
fast osprey
#

Personally I don't bother trying to make type checkers happy shrug

dense scaffold
#

And also instead of importing Optional, you could do X | Y for annotations

dense scaffold
# young dagger Why am I getting `Expected type 'tuple[dict[str, Any] | None, str | None]', got ...
from typing import Mapping

async def find_case(self, case_id: int) -> tuple[Mapping[str, Any] | None, str | None]:
    collections = {
        "warnings_collection": self.warnings_collection,
        "kicks_collection": self.kicks_collection,
        "bans_collection": self.bans_collection,
        "mutes_collection": self.mutes_collection,
        "modnotes_collection": self.modnotes_collection,
    }

    for collection_name, collection in collections.items():
        case = await collection.find_one({"case_id": case_id})
        if case:
            return case, collection_name

    return None, None

This should resolve your issue.

dense scaffold
young dagger
#

But thank you

dense scaffold
young dagger
dense scaffold
young dagger
dense scaffold
#

It's suggested instead of dict, proper annotations for your case.

mint pecan
#

can i add aliases to a command's parameter?

merry cliff
mint pecan
vocal laurel
merry cliff
#

I dont think I know what you mean, as far as I know normal params for text commands are purely named in the code and arent used when running the command

merry cliff
#

but they said with normal ones

mint pecan
vocal laurel
fast osprey
#

Aliases are for things users type in. If they're not typing in the parameter name at all, it doesn't make sense for there to be an alias

solar bone
#

does this work bro

patent hull
thin raft
#

Are you familiar with python?

#

You should get familiar with python first

#

knowing js just the basics might be enough

wanton current
fast osprey
wanton current
worldly lava
fast osprey
#

Ironic joke lol between dpy heads

wanton current
#

what's dpy

slate swan
#
    @commands.Cog.listener()
    async def on_ready(self):
        for color_role_id in config.colors:
            color_role: discord.Role = self.bot.get_guild(config.main_server).get_role(color_role_id)
            print(color_role)
            print(color_role.members)

why is this not printing the role members? note: it does get the role successfully

slate swan
fast osprey
#

What intents are you requesting?

fast osprey
#

Also you probably don't want to do this in on_ready, that event fires repeatedly and randomly

slate swan
slate swan
wanton current
slate swan
#

wait

wanton current
#

?

slate swan
#

i always mix up fetch and get 😭

#

still doesnt say you need an intent

wanton current
#

wait nvm, i thought of something else

fast osprey
#

I believe you need the members intent to see the members of a role

slate swan
#

!e

unkempt canyonBOT
#
Missing required argument

code

slate swan
#
print(isinstance(0, (str, int))
slate swan
unkempt canyonBOT
#
Missing required argument

code

slate swan
#

!e

print(isinstance(0, (str, int))
unkempt canyonBOT
slate swan
#

!e

print(isinstance(0, (str, int)))
unkempt canyonBOT
slate swan
#

!e

print(isinstance('0', (str, int)))
unkempt canyonBOT
slate swan
#

!e

print(isinstance([0, 1], (str, int)))
unkempt canyonBOT
unique geyser
slate swan
#

oh my bad

young dagger
#

Can you use the walrus operator to assign variables like:

if (invite_match := re.search(
    r"(?:https?://)?(?:[a-zA-Z0-9-]+\.)?(discord(?:app)?\.com|discord\.gg)/(?:invite/)?([a-zA-Z0-9]+)$",
    message.content, re.IGNORECASE)):
spiral kiln
#

Can you put py await client.process_commands(message) at the start of your function instead of the last line?

sick birch
#

yeah

spiral kiln
#

ok good

#

thanks

#

my code requires this

fast osprey
#

Often when people do that, what they want is a listener rather than overriding on_message

slim bloom
#

@fast osprey one dude

slate swan
#

!e 2 +3 =

unkempt canyonBOT
# slate swan !e 2 +3 =

:x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     2 +3 =
003 |     ^^^^
004 | SyntaxError: cannot assign to expression
unkempt canyonBOT
#

:warning: Your 3.12 eval job has completed with return code 0.

[No output]
unkempt canyonBOT
#

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

5
timber dragon
#

#bot-commands exists people

slate swan
#

!e print'uwu'

unkempt canyonBOT
# slate swan !e print'uwu'

:x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     print'uwu'
003 |     ^^^^^^^^^^
004 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
slate swan
#

!e print("uwu")

unkempt canyonBOT
wanton fiber
#

!e print("code")

unkempt canyonBOT
exotic hazel
grizzled onyx
#

how can I perform each task in turn (sequentially, one after the other). I am using aiosqlite and my database is being blocked due to multiple tasks

fast osprey
#

What database/driver are you using?

#

Task loops are meant to be for background repeating things, not things you execute once with dependencies

mild token
#

is there a way to get the connection link of user , meaning whatever they have connected with their profile can i check with bot?

#

these things in my case

wanton current
#

no

mild token
#

: (

young dagger
#

What is this color called?

wanton current
#

or do you mean green

young dagger
#

The green

wanton current
#

green?

young dagger
#

No

#

This is green

wanton current
#

both are green

young dagger
#

Well it's not the same color

#

I can see they are both green

sacred vigil
wanton current
#

Medium Sea Green according to some website

#

I got #43B582

#

for the first one

young dagger
#

I know but it's should be an official Discord color

wanton current
#

these are the official discord colours

young dagger
#

There is more colors than that

stark ingot
young dagger
stark ingot
#

That is just whatever lib you are using

sick birch
#

those are simply some presets of discord.Colour class

#

the embed color can be anything, not necessarily restrained to a preset

stark ingot
#

My guess is you have teal or dark teal

young dagger
#

How can I ignore mute and deafen?

#
    if (before.channel == after.channel and
        before.self_mute == after.self_mute and
        before.self_deaf == after.self_deaf):
        return
#

This isn't really working

sick birch
young dagger
young dagger
#

Couldn't I just do:

        if before.channel == after.channel:
            return
#

@sick birch ?

sick birch
#

What are you trying to detect changes in?

young dagger
# sick birch What are you trying to detect changes in?
    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        # Ignore changes if only mute or deafen status has changed
        if before.channel == after.channel:
            return

        if before.channel is None and after.channel is not None:
            action = "joined"
            channel_name = after.channel.name

        elif before.channel is not None and after.channel is None:
            action = "left"
            channel_name = before.channel.name

        elif before.channel is not None and after.channel is not None and before.channel != after.channel:
            action = "switched from"
            channel_name = f"{before.channel.name} -> {after.channel.name}"

        # Create embed
young dagger
sick birch
#

Only issue i see is the last one might still run for other actions

#

I think before.channel != after.channel should be enough?

young dagger
#

Cannot find reference 'name' in 'None'

fast osprey
#

That's not in the code you sent

slim bloom
#
async def system_dependencies(self) -> None:
    if not os.path.isfile('requirements.txt'):
        async with aiofiles.open('requirements.txt', mode='w') as file:
            await file.write('')
            
    try:
        async with aiofiles.open('requirements.txt', mode='r') as file:
            dependencies = await file.readlines()

        dependencies = [dep.strip() for dep in dependencies if dep.strip()]

        missing = []
        for dep in dependencies:
            try:
                pkg_resources.require(dep)
            except pkg_resources.DistributionNotFound:
                missing.append(dep)
            except pkg_resources.VersionConflict:
                missing.append(dep)

        if missing:
            process = await asyncio.create_subprocess_exec(
                sys.executable, "-m", "pip", "install", *missing,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            
            stdout, stderr = await process.communicate()
            
            if process.returncode == 0:
                print(f"Dependencies installed successfully:\n{stdout.decode()}")
            else:
                print(f"Error during installation:\n{stderr.decode()}")
        else:
            print("All dependencies are already installed.")
    except Exception:
        traceback.print_exc()```
#

@fast osprey How could I improve it?

mint pecan
#

How do i mention a role in string?

hushed galleon
lost scarab
rain crystal
stark ingot
#

Back ticks on both sides `

rain crystal
#

import math

#

eijhrgfoeryov4erbvtu436n2nnnnntnerwnerw

#

ty

mint pecan
#

how do i check if a command instance is a slash command?

fast osprey
#

What does "command instance" mean here?

mint pecan
quick gust
#

I mean it depends on ur use case

fast osprey
#

command isn't a thing as far as the library is concerned. There are multiple Command classes, of which you would need to disambiguate here. Some code would probably be useful as well as what you're trying to do

fickle basalt
#

Is there a bot that does OCR?

mild token
#

is there any event which tells when member activity changes?

#

or presence

fast osprey
#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.

This is called when one or more of the following things change:

β€’ status

β€’ activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
stark ingot
#

Oops, did not see the response

young dagger
#

Is it recommended to add a class inside another class (cog)?

wanton current
#

for what reason?

young dagger
#

That is what Rapptz did

wanton current
#

Yeah, there are no nested classes?

fast osprey
#

...where do you see classes nested?

young dagger
#

Am I using the cogs incorrectly?

#

Cannot find reference 'edit_message' in '() -> InteractionResponse'

fast osprey
#

The command is outside of the cog for one

#

and for that, that's just your ide complaining

fair herald
#

C:\Users\luffy\Downloads\meowmeowmeow\cogs\music.py:65: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  bot.add_cog(Music(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog music.py: Extension 'cogs.music' raised an error: TypeError: object NoneType can't be used in 'await' expression```
#

can anyone help?

young dagger
#

Still getting same error

#

raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.verification' raised an error: TypeError: object NoneType can't be used in 'await' expression

fast osprey
#

both setup and add_cog are async in dpy as of 2.0

young dagger
fast osprey
#

Yeah, make setup an async method and await add_cog. And more generally, follow official docs and examples

young dagger
fast osprey
#

I didn't mention load_extension though Thonk

young dagger
#

Is there any downsize of using async?

fast osprey
#

I mean, add_cog is a coroutine. You need to await it.

The library also assumes when it calls setup that it is supposed to be async and awaits it, so it should be async.

young dagger
fast osprey
#

Because of some silly thing with how it fails to read that particular method from the library, it's a pretty common thing

young dagger
fast osprey
#

making a method called on_ready in a cog doesn't do anything

#

You also probably don't want to actually use on_ready anyways, given how it actually works

young dagger
#

Do you have any idea on how I can sync the old button?

fast osprey
#

What does "syncing" a button mean?

young dagger
fast osprey
#

Like make a button work after a restart?

young dagger
#

Exactly

fair herald
#

C:\Users\luffy\Downloads\meowmeowmeow\cogs\music.py:65: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  bot.add_cog(Music(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog music.py: Extension 'cogs.music' raised an error: TypeError: object NoneType can't be used in 'await' expression```
#

can anyone help?

young dagger
#

You need to async it

#

(the cog)

fast osprey
#

You don't need to edit a message, you just need to register either a persistent view or a dynamic item. And you should do this once, not in on_ready

fair herald
formal basin
#

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers')) this is only working for 1 server

#

Also this is running everythime i run the bot @bot.event async def on_guild_remove(guild): channel = bot.get_channel(channel_id) await channel.send(f"server leave server:{(guild.name)} owner: {(guild.owner)}") await botlist_client.setStats(len(bot.guilds), 1) await bot.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers'))

#

it sends this:

server leave server: `````` owner: None

golden portal
formal basin
real rampart
#

anyone here worked with lavalink?

real rampart
formal basin
#

not because someone kicked my bot

real rampart
#

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

u have these?
and do u have channel_id defined

formal basin
#

channel_id is defined

#

its sending it in the channel

#

but also

#

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers')) why is this only showing in one server

#
@bot.event
async def on_ready():
     print("bot online")
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers'))
     bot.add_view(VerifyButton())
     upload_json_to_discord.start()
     await botlist_client.setStats(len(bot.guilds), 1)
     print(f"{len(bot.guilds):,} servers")```
fast osprey
#

You shouldn't be doing any of this in on_ready

formal basin
fast osprey
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.