#discord-bots

1 messages · Page 366 of 1

spice seal
#

Bro made the hardest exam easier than walking 🤓

latent pier
#

Where i find that?

viscid hornet
crisp glacier
latent pier
#

I've better alternates

crisp glacier
spice seal
#

927257448568467516 user id
One message I'd 1239541748909342892

mild token
#

How can I get the logging of d.py i want to keep my logs in specific format?

spice seal
crisp glacier
#

damn you got me

spice seal
#

I'm the roast pro tbh stop it...

unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

latent pier
#

!d discord.utils.setup_logging

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.

New in version 2.0.
mild token
#

Ty

spice seal
# crisp glacier damn you got me

I have passed out of
University Of Swears and Slurs
And this is my rank
#02
And my results
Slurs Minor - A+
Slurs Major - A+
Swears Minor- A-
Swears Major - A+

viscid hornet
viscid hornet
spice seal
#

I'm also in mobile

latent pier
#

I have alternates

crisp glacier
mild token
#

@latent pier another thing I want to ask if I just use the logging lib it will automatically will be colored like d.py logs or I need to use client instance?

viscid hornet
mild token
latent pier
#

I wish i had

slate swan
spice seal
#

Guys whoever thinks replit sucks

React with 🤓

mild token
#
2024-05-13 17:58:35 INFO     discord.client logging in using static token
INFO:discord.client:logging in using static token
2024-05-13 17:58:45 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 64b7df91e7d44ae30ac36be4ad941a50).
INFO:discord.gateway:Shard ID None has connected to Gateway (Session ID: 64b7df91e7d44ae30ac36be4ad941a50).
Logged in as Test#4384 (ID: 1237358593230241792)

i imported logging and this happening now instead of 1 now its 2 logs

slate swan
#

its normal

#

atleast the logs

mild token
spice seal
#

Guys is there any api which makes a image with author avatar and username with title Winner

mild token
slate swan
#

how are you loading them

spice seal
#

Any good api for that?

slate swan
mild token
# slate swan how are you loading them
    def load_cog(self, file_path):
        module = importlib.import_module(file_path)
        for name, obj in inspect.getmembers(module):
            if inspect.isclass(obj) and issubclass(obj, commands.Cog):
                asyncio.run(self.add_cog(obj(self)))
                logging.info(f'Loaded {name} Cog')

finite salmon
viscid hornet
viscid hornet
finite salmon
#

alr bro

shrewd apex
#

just use the setup_hook 💀

viscid hornet
finite salmon
#

cope

slate swan
#

PepePoint @viscid hornet

viscid hornet
spice seal
slate swan
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
mild token
#

cogs getting loaded but logs are getting suppressed somewhere

slate swan
#

use this to load cogs

finite salmon
#

fortunately

spice seal
#

Lol

#

Someone help me with this api

mild token
spice seal
slate swan
shrewd apex
#

also did u set a log_level which may cause other or lower log levels to be surpressed

mild token
shrewd apex
#

the default dpy logging is prolly warning or errors

mild token
#

Oh

shrewd apex
#

where ur using info

slate swan
#

!d discord.utils.setup_logging

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.

New in version 2.0.
shrewd apex
#

^^

mild token
#
2024-05-13 18:04:29 INFO     discord.client logging in using static token

i thought this line bcz of this line

shrewd apex
#

how do u start the bot using run or start?

slate swan
#

Run prob

mild token
shrewd apex
#

aight

slate swan
#

axo probably lurking and waiting to send a documentation link squint

mild token
#

already sent

shrewd apex
#

axo needs to take a mental health break 🙏

mild token
#

Initial setup of discord bot is pain

#

If someone have to write from scratch

viscid hornet
viscid hornet
slate swan
viscid hornet
slate swan
mild token
#
2024-05-13 18:49:50,647 INFO Shard ID None has connected to Gateway (Session ID: 7c255f658799526dea0d56402930f454).
2024-05-13 18:49:50,647 INFO Shard ID None has connected to Gateway (Session ID: 7c255f658799526dea0d56402930f454).
2024-05-13 18:49:52,682 INFO 2024-05-13 18:49:52 logger.py Logged in as Test#4384 (ID: 1237358593230241792)
2024-05-13 18:49:52,682 INFO 2024-05-13 18:49:52 logger.py Logged in as Test#4384 (ID: 1237358593230241792)

getting double logs for some reason

#

i just wanted 1

viscid hornet
latent pier
viscid hornet
latent pier
latent pier
#

Logging code?

slate swan
viscid hornet
#

just look at this

#

(this is running the benchmark on a better pc - mine had a longest time of 950 seconds 💀)

spice seal
#

hi

#

what the fridge is going on tbh

viscid hornet
spice seal
#

yea i have an issue

viscid hornet
#

@slate swan absolute joke 💀

spice seal
#

wats a variable in python?

#

idk

viscid hornet
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

spice seal
#

anything about python

viscid hornet
#

we can tell

#

you clearly don't know anything about manners either

spice seal
#

jk jk i was trolling lol sorry

viscid hornet
#

"trolling"

latent pier
viscid hornet
viscid hornet
latent pier
latent pier
viscid hornet
young dagger
#

What is different between

users = await collection.find().to_list(length=None)

for user in users:

and

async for user_data in collection.find():
latent pier
#

Thinking

latent pier
young dagger
quick gust
young dagger
quick gust
#

No like a list? Set? Dictionary?

#

what datatype is collection?

young dagger
fast osprey
#

Probably better served in the db channel, nothing discord related here

latent pier
#

Isn't it dictionary

shrewd apex
young dagger
young dagger
latent pier
young dagger
viscid hornet
#

link is here 😭

#

hi mr umbra

wanton current
#

it's revan

viscid hornet
spice warren
#

Even though this is highly offtopic for the current channel (which was already mentioned)

The async iterator will let you exit early if you have a condition you need to be met. E.g. async for x in y: if x.id == ....: return or similar

The former operation is colloquially known as "flattening" will give you all results at once, which if the collection is large, is an expensive operation.
I doubt you're in that territory yet, but there you go.

Please move to #databases for any future questions on the matter, or open a dedicated help thread

shrewd apex
latent pier
shrewd apex
#

usually if ur iterating and performing some operation or calculation on the result set and u dont really need all of them

latent pier
#

it's just asynchronous version of for loop 🤣

#

In simple words

#

Other than that no difference

mild token
#
class UsefulEmbeds(commands.Cog):
    def __init__(self,bot:commands.bot) -> None:
        self.bot = bot
    def failure_embed(self,title: str = None, desc: str = None):
        embed = Embed()
        embed.color = Color.red()
        embed.description = desc
        embed.title = title
        embed.timestamp = datetime.now()
        return embed

    def success_embed(self,title: str = None, desc: str = None):
        embed = Embed()
        embed.colour = Color.green()
        embed.description = desc
        embed.title = title
        embed.timestamp = datetime.now()
        return embed

    async def send_logs(self,channel_id):

i dont want to make it cog is it possible to get the bot instance without inhering command.bot? i want to fetch one channel for that i need bot instance

spice warren
spice warren
spice warren
mild token
spice warren
#

You're in charge of defining the constructor so I don't see why not

mild token
#

it will be attached to same bot instance right?

spice warren
#

So long as you pass it to it, yes

mild token
latent pier
spice warren
#

The "no difference" is misinformation since it is pretty different.

latent pier
#

Ok i understand my bad not to write everything in single message

mild token
shrewd apex
#

sure

spice warren
#

Try it :)

mild token
shrewd apex
#

i would make them static methods tbh

latent pier
shrewd apex
#

and pass bot as param

mild token
mild token
#

which will be repetative

shrewd apex
#

hmm u can have the user embeds class as an attribute for the bot then i suppose

mild token
shrewd apex
#

otherwise u would either need some global instance of the useful embed class or u would need to initialize it everytime either ways

spice warren
# latent pier I meant other than that there's no difference in both

You're missing the point entirely to defend yourself out of ego.

Please do not give misinformation to people in the channel.

There is a very clear different between an async iterator and a non-async iterator.
Do not tell people there isn't, which is just wrong.

Instead, don't mention it at all, and if someone asks the difference, explain it, and if you don't know that difference then defer to someone who does, rather than say the incorrect thing and lead people astray.

mild token
fast osprey
#

Normalize admitting when you don't know something, or when you know it's a guess YotsubaPray

spice warren
shrewd apex
#

time for staticmethods just coz i like it grouped lol

#

and the useful embed class itself dosent need to maintain any state

mild token
spice warren
#

Staticmethods it is :)

mild token
young dagger
#

TypeError: can't subtract offset-naive and offset-aware datetimes

await unverified_collection.insert_one(
                    {"user_id": member.id, "timestamp": member.joined_at})
if (member.joined_at - user_data['timestamp']).total_seconds() > 300:
#

Why can't I compare member.joined_at with member.joined_at > 300

#

🤔

#

I mean they should be the same format

latent pier
# young dagger Which one is more appropriate to use?

for loop iterates through a collection in a synchronous way which means this waits for each iteration to complete before moving on to the next task

And on other hand async for should be used to transverse an asynchronous iterator within coroutine, It enables concurrent execution of tasks by processing items concurrently, potentially yielding results as soon as they become available without waiting for each iteration to complete

young dagger
#

What about if (member.joined_at.replace(tzinfo=None) - user_data['timestamp']).total_seconds() > 300:

#

They are both giving me the same timestamp

#

Why are print(member.joined_at.replace(tzinfo=None)) and print(user_data['timestamp']) giving me the same timestamp?

latent pier
spice warren
#

Why are you stripping the timezone?

young dagger
latent pier
young dagger
#

on_member_join

#

Then I run a task to compare

spice warren
#

.replace(tzinfo=None) is stripping the timezone, why?

young dagger
#

Because of MongoDB

spice warren
#

The solution here is to make the other timezone aware, not the other way around
Right, I see, and mongo strips timezones? All the more reason it's not great

spice warren
#

Okay so the alternative solution is to instead store the timestamp as the int, not the datetime itself
You'll have an integer to work with rather than potentially messing up your datetime

young dagger
#

OOHHH my bad

spice warren
#

Then when you want to use this for comparison you can use datetime.datetime.fromtimestamp(..., tzinfo=datetime.UTC) and you'll have an aware datetime to do your dt math with too

young dagger
#

member.joined_at will always be the same

latent pier
#

It's value won't change

young dagger
#

Brah

latent pier
#

Unless left and joined then it'll be assigned new value

spice warren
#

dt = datetime.datetime.fromtimestamp(12738912739812, tzinfo=datetime.UTC)

then you can do like

dt > other_datetime and whatnot

latent pier
#

datetime.timestamp() returns value in float right? @spice warren

#

He can save it

spice warren
#

That was my original solution, yes

young dagger
spice warren
#

stripping the timezone from a datetime can give inaccurate results, e.g. a time/date that doesn't actually match what you has

#

that's why the preference is to add the timezone rather than subtract it

young dagger
#

And the timezone would change

#

datetime.timestamp() is locally

spice warren
#

No datetime.datetime.timestamp() is relative to that datetime

young dagger
#

Cause I'm confused

spice warren
young dagger
spice warren
#

Member.joined_at is a datetime.datetime
.timestamp() is a method of that datetime that returns a float representing the time in seconds since Jan 1st 1970 for that datetime

young dagger
spice warren
#

Not with mongo, otherwise we wouldn't be having this issue haha

young dagger
#

True

latent pier
#

But why does he need to save member.joined_at when it'll always be same and it is a direct attribute of a discord.Member 🗣️

spice warren
#

Unknown

mild token
#
class UsefulEmbeds:
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    def failure_embed(self, title: str = None, desc: str = None):
        embed = Embed()
        embed.color = Color.red()
        embed.description = desc
        embed.title = title
        embed.timestamp = datetime.now()
        return embed

    def success_embed(self, title: str = None, desc: str = None):
        embed = Embed()
        embed.colour = Color.green()
        embed.description = desc
        embed.title = title
        embed.timestamp = datetime.now()
        return embed

    async def send_logs(self, channel_id):
        print(channel_id)
        _channel = self.bot.get_channel(channel_id)
        print(_channel)
        await _channel.send("check check")
@app_commands.command(name="command-1")
    async def my_command(self, interaction: discord.Interaction) -> None:
        """ /command-1 """
        await UsefulEmbeds.send_logs(1239551237704122368)
        await interaction.response.send_message("Hello from command 1!", embed=UsefulEmbeds.failure_embed("check", "check"), ephemeral=True)

what i am doing wrong why channel obj i am not getting

#

for some reason even print also not working

spice warren
#

You are using them like staticmethods but did not define them as such

latent pier
mild token
#

dont know why i didnt got any error

spice warren
#

If you overrode your CommandTree.on_error you may have done so incorrectly

latent pier
viscid hornet
spice warren
#

They want staticmethods not a stateful class

viscid hornet
#

^^

spice warren
#

So there's a lot of reworking to be done here

spice warren
#

She made a CommandTree example?

mild token
#
import discord
import traceback
import sys
from discord.ext import commands


class CommandErrorHandler(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        """The event triggered when an error is raised while invoking a command.
        Parameters
        ------------
        ctx: commands.Context
            The context used for command invocation.
        error: commands.CommandError
            The Exception raised.
        """
        if hasattr(ctx.command, 'on_error'):
            return

        cog = ctx.cog
        if cog:
            if cog._get_overridden_method(cog.cog_command_error) is not None:
                return

        ignored = (commands.CommandNotFound, )
        error = getattr(error, 'original', error)

        if isinstance(error, ignored):
            return

        if isinstance(error, commands.DisabledCommand):
            await ctx.send(f'{ctx.command} has been disabled.')

        elif isinstance(error, commands.NoPrivateMessage):
            try:
                await ctx.author.send(f'{ctx.command} can not be used in Private Messages.')
            except discord.HTTPException:
                pass

        elif isinstance(error, commands.BadArgument):
            if ctx.command.qualified_name == 'tag list':
                await ctx.send('I could not find that member. Please try again.')

        else:
            print('Ignoring exception in command {}:'.format(
                ctx.command), file=sys.stderr)
            traceback.print_exception(
                type(error), error, error.__traceback__, file=sys.stderr)

spice warren
#

This does not handle slash command errors

mild token
#

i just need to add slash right?

spice warren
#

No

#

This is handled in CommandTree.on_error, so if you have not overriden it yourself then you're not using the library's logging

spice warren
#

Not on the CommandTree class

#

Hence prefixing it with CommandTree.

#

!d g discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).

The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.

To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command) should be used.
mild token
#

then ctx.command will also change right?

#

as i am using slash command

spice warren
#

The default implementation is sufficient so long as you use the library's logging

#

ctx does not matter, your above codeblock is irrelevant

#

That is for ext.commands NOT application commands

mild token
#

@spice warren so i now is there any different method of on_command_error?

spice warren
#

No that has not changed

#

How do you start/run your bot? Is it Bot.start(), or?

spice warren
#

This enables logging by default, do you change any of the logging parameters?

mild token
spice warren
#

I have found why you are having issues then, please show me your Bot.run() line and remove any tokens that may be present

mild token
#
from loguru import logger
from datetime import datetime


logger.add("logfile.log", level="INFO",
           format="{time} {level} {message}", rotation="500 MB")


discord_logger = logger.bind(source='discord')

discord_http_logger = logger.bind(source='discord.http')




def get_timestamp():
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")



def log_message(log_level, message):
    timestamp = get_timestamp()
    formatted_message = f"{timestamp} {message}"
    logger.opt(depth=1).log(log_level, formatted_message)
spice warren
#

you may wanna call discord.utils.setup_logging() and then look at the source of the method to adapt your logging situation correctly

#

You're not getting key items in logs

mild token
#
class MyBot(commands.Bot):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(command_prefix='!', help_command=None, intents=intents)

    async def setup_hook(self):

        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)

    async def on_ready(self):
        log_message('DEBUG', f'Logged in as {self.user}(ID: {self.user.id})')
        print('------')

    def load_cog(self, file_path):
        module = importlib.import_module(file_path)
        for name, obj in inspect.getmembers(module):
            if inspect.isclass(obj) and issubclass(obj, commands.Cog):
                asyncio.run(self.add_cog(obj(self)))
                log_message("INFO", f'Loaded {name} Cog')

    def load_all_extensions(self):

        directory = Path('bot/ext')
        for item in directory.glob('*.py'):
            if item.stem.startswith('_'):
                continue
            self.load_cog(f"afw_bot.ext.{item.stem}")

    def run(self, *args, **kwargs):
        self.load_all_extensions()
        try:
            super().run(*args, **kwargs)
        except Exception as e:
            log_message('CRITICAL', f"Login Failed\nReason: {e}")


def main():
    intents = discord.Intents.default()
    intents.members = True
    intents.message_content = True
    bot = MyBot(intents=intents)
    bot.run(BOT_TOKEN, log_handler=None)
spice warren
#

log_handler=None is why you're not getting any errors showing, lol

#

You'll need to override the error handling methods to use your handler stuff

mild token
mild token
spice warren
#

Because the library will do logging but so will your setup

spice warren
mild token
#

big error popped finally, i am happy now 😭

mild token
#
import discord

from discord import Interaction
from discord.ext import commands

class CommandErrorHandler(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        """The event triggered when an error is raised while invoking a command.
        Parameters
        ------------
        ctx: commands.Context
            The context used for command invocation.
        error: commands.CommandError
            The Exception raised.
        """
        if hasattr(Interaction.command, 'CommandTree.on_error'):
            return

        cog = ctx.cog
        if cog:
            if cog._get_overridden_method(cog.cog_command_error) is not None:
                return

        ignored = (commands.CommandNotFound, )
        error = getattr(error, 'original', error)

        if isinstance(error, ignored):
            return

        if isinstance(error, commands.DisabledCommand):
            await ctx.send(f'{ctx.command} has been disabled.')

        elif isinstance(error, commands.NoPrivateMessage):
            try:
                await ctx.author.send(f'{ctx.command} can not be used in Private Messages.')
            except discord.HTTPException:
                pass

        elif isinstance(error, commands.BadArgument):
            if ctx.command.qualified_name == 'tag list':
                await ctx.send('I could not find that member. Please try again.')
        else:
            print('Ignoring exception in command {}:'.format(
                ctx.command), file=sys.stderr)
            traceback.print_exception(
                type(error), error, error.__traceback__, file=sys.stderr)

can i pass Interaction to on_command_error?

spice warren
#

This is not how you do this at all

#

Let me explain:

In your Bot constructor there's a parameter for tree_cls, you pass in a type (a Class) of a CommandTree subclass for your bot to use.

Since you want to override Logging for it, you need to make a CommandTree subclass, which overrides the on_error method to handle your logging and whatnot

You then pass this class to the aforemention tree_cls parameter

You don't patch it like you're trying above

mild token
mild token
spice warren
#

No

#

Strongly advised to not do that

mild token
#

oh so without cog it will get triggered?

spice warren
#

No?

#

Sorry I'm not following your thought process here

Cogs have nothing to do with CommandTree

mild token
#

@spice warren i have to pass this on_command_error to tree cls right? and on_command error will be cog listner too?

fast osprey
#

There is no "passing" here. You implement on_error in the CommandTree subclass

#

That should all be declared inside that subclass, and then you would tell the bot the new CommandTree subclass you want it to use

mild token
#

oh so i just need to implenet on_error and then pass it to tree_cls and bot will keep listening right?

fast osprey
#

I don't think the word "pass" means what you think it means here

#

The on_error doesn't go anywhere. It's just implemented inside the subclass you make

mild token
#
from discord.ext.commands import Bot

custom_tree = CustomCommandTree()

bot = Bot(command_prefix="!", tree_cls=custom_tree)

this is what i meant

#

that customCommandTree is error handler

fast osprey
#

tree_cls wants a class

#

not an instance of that class

mild token
#

ok

#
from discord.ext.commands import CommandTree

class CustomCommandTree(CommandTree):
    async def on_error(self, event_method, *args, **kwargs):
       pass

and this will be custom tree

fast osprey
#

on_error has a very specific signature

#

you can't ask for other parameters that the library isn't going to give it

mild token
#

ok btw i am implementing in right way right other than this?

fast osprey
#
  • on_error only receives (self, interaction, error)
  • you're passing an instance of a commandtree, not a class that inherits it
  • really depends on the implementation you make
wanton current
#

also commands.CommandTree Thonk

white citrus
#
class RadioDropdown(nextcord.ui.View):

    def __init__(self, options):

        super().__init__()
        self.options = options
        self.page_number = 1
        self.options_per_page = 25
        self.button_back = self.children[0]
        self.button_next = self.children[1]
        self.SelectRadio = SelectRadio([], self.button_back, self.button_next)
        self.add_item(self.SelectRadio)
        self.update_select()

    def update_select(self):
        start_index = (self.page_number - 1) * self.options_per_page
        end_index = start_index + self.options_per_page
        options_page = self.options[start_index:end_index]
        self.SelectRadio.options = options_page

    def update_select_radio_options(self, options):
        self.options = options
        self.update_select()

    @nextcord.ui.button(label="<< Prev", style=nextcord.ButtonStyle.secondary, disabled=True)
    async def r_previous_page(self, button: nextcord.Button, inter: nextcord.Interaction):
        if self.page_number > 1:
            self.page_number -= 1
            self.update_select()
            self.button_back.disabled = self.page_number == 1
            self.button_next.disabled = False
            await inter.response.edit_message(view=self)

    @nextcord.ui.button(label="Next >>", style=nextcord.ButtonStyle.secondary)
    async def r_next_page(self, button: nextcord.ui.Button, inter: nextcord.Interaction):
        total_pages = (len(self.options) - 1) // self.options_per_page + 1
        if self.page_number < total_pages:
            self.page_number += 1
            self.update_select()
            self.button_back.disabled = False
            self.button_next.disabled = self.page_number == total_pages
            await inter.response.edit_message(view=self)```
#
class SelectRadio(nextcord.ui.Select):
    def __init__(self, options, button_back, button_next):
        super().__init__(placeholder="Choose a radio", min_values=1, max_values=1, options=options)
        self.options = options
        self.button_back = button_back
        self.button_next = button_next

    async def callback(self, inter: nextcord.Interaction):
        return print("YAY")```
#

Error

Traceback (most recent call last):
  File "C:\VSCode\Python\Lib\site-packages\nextcord\ui\view.py", line 386, in _scheduled_task
    await item.callback(interaction)
  File "c:\VSCode\Antonio-Beta\modules\voice\view.py", line 49, in next_page
    await inter.response.edit_message(view=self)
  File "C:\VSCode\Python\Lib\site-packages\nextcord\interactions.py", line 1065, in edit_message
    await adapter.create_interaction_response(
  File "C:\VSCode\Python\Lib\site-packages\nextcord\webhook\async_.py", line 200, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options.8: The specified option value is already used```
mild token
#
from discord.app_commands import CommandTree
from discord import app_commands
class CustomCommandTree(CommandTree):
    async def on_error(self, interaction, error):
        ignored = (app_commands.CommandNotFound, )
        error = getattr(error, 'original', error)
        if isinstance(error, ignored):
            return

        elif isinstance(error, app_commands.NoPrivateMessage):
            try:
                await interaction.author.send(f'{interaction.command.name} can not be used in Private Messages.')
            except discord.HTTPException:
                pass

        elif isinstance(error, app_commands.BadArgument):
            if interaction.command.qualified_name == 'tag list':
                await interaction.response.send_message('I could not find that member. Please try again.')

        else:
            print('Ignoring exception in command {}:'.format(
                interaction.command.name), file=sys.stderr)
            traceback.print_exception(
                type(error), error, error.__traceback__, file=sys.stderr)

this seems correct?

fast osprey
white citrus
#

There are no duplicates

fast osprey
#

How?

white citrus
fast osprey
#

I mean the error and discord aren't lying to you

white citrus
mild token
#

This client already has an associated command tree. this error i am getting when i try

    async def setup_hook(self):
        CommandErrorHandler(self)
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)
spice warren
#

Bot already has a command tree. this is why I told you to use the tree_cls kwarg in the Bot constructor, remember?

white citrus
viscid hornet
#

and then give us some

#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

mild token
spice warren
#

You have some errors, yes, like interaction.author

mild token
fast osprey
spice warren
#

You appear to have just copy pasted your ext.commands handler which isn't very good

#

Since that handler does weirdly specific things in an elif that just aren't relevant

#

Try running the code, you'll see the errors

mild token
#

my commands are guild specific it wont trigger error : (

spice warren
#

Remove the irrelevant code...?

Please run it, I don't want to pick apart every little issue. You shouldn't have copy pasted the ext.commands one, so you'll just need to debug on your own a bit

mild token
fast osprey
#

Yup, and you'll want to log it out every time it gets changed (which seems to be the issue, not when it's sent initially)

white citrus
fast osprey
#

Every time you are modifying the active options on a select and then resending it

#

You have some path where you are winding up with duplicate options

fast osprey
#

Up to you to do some debugging to figure that out

white citrus
fast osprey
#

How are you checking?

white citrus
fast osprey
#

Code?

white citrus
# fast osprey Code?
class RadioDropdown(nextcord.ui.View):

    def __init__(self, options):

        super().__init__()
        self.options = options
        self.page_number = 1
        self.options_per_page = 25
        self.button_back = self.children[0]
        self.button_next = self.children[1]
        self.SelectRadio = SelectRadio([], self.button_back, self.button_next)
        self.add_item(self.SelectRadio)
        self.update_select()

    def update_select(self):
        start_index = (self.page_number - 1) * self.options_per_page
        end_index = start_index + self.options_per_page
        options_page = self.options[start_index:end_index]
        self.SelectRadio.options = options_page

    def update_select_radio_options(self, options):
        self.options = options
        self.update_select()

    @nextcord.ui.button(label="<< Prev", style=nextcord.ButtonStyle.secondary, disabled=True, row=1)
    async def r_previous_page(self, button: nextcord.Button, inter: nextcord.Interaction):
        if self.page_number > 1:
            self.page_number -= 1
            self.update_select()
            self.button_back.disabled = True
            self.button_next.disabled = False
            await inter.response.edit_message(view=self)

    @nextcord.ui.button(label="Next >>", style=nextcord.ButtonStyle.secondary, row=1)
    async def r_next_page(self, button: nextcord.ui.Button, inter: nextcord.Interaction):
        total_pages = (len(self.options) - 1) // self.options_per_page + 1

        if self.page_number < total_pages:
            self.page_number += 1
            self.update_select()
            self.button_back.disabled = False
            self.button_next.disabled = True
            await inter.response.edit_message(view=self)```
fast osprey
#

Where is the print?

white citrus
slim bloom
#

@fast osprey

white citrus
# fast osprey Where is the print?
    def update_select(self):
        start_index = (self.page_number - 1) * self.options_per_page
        end_index = start_index + self.options_per_page
        options_page = self.options[start_index:end_index]
        self.SelectRadio.options = options_page
        print(options_page)``` here
slim bloom
#
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, aiohttp

color_lace = discord.Color.from_rgb(60, 161, 224)

class Autopfp(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
        self.send_pfp.start()

        @tasks.loop(minutes=1)
        async def send_pfp(self):
            return # programing....```
mild token
#
elif isinstance(error, app_commands.MissingAnyRole):
            await interaction.response.send_message(f'{error} missing role')
You are missing at least one of the required roles: 'Library Devs'

how can i get the role name? from my error handler? its working correctly just need the role name

mild token
dusk dagger
mild token
fast osprey
#

But 99 times out of 100 you shouldn't be using this check to begin with, when the integrations UI exists to role lock commands

slim bloom
fast osprey
#

You nested that inside your init

slim bloom
fast osprey
#

yes

mild token
quick gust
#

The loop function needs to be outside your init

blissful badge
#

Having a weird issue with my self-hosted bots (VirtualBox, Windows 10 VM) and I don't know if anyone here has any ideas.

I only started experiencing this issue the last few months. My bots will go through the regular


discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

INFO discord.gateway Shard ID None has successfully RESUMED session```
cycle and they used to be fine about waking back up themselves but lately they just die and I have to manually interact with the command line running them to get them back up.

I've done everything I can think of to make sure the VMs are staying fully awake but they keep going to sleep. Happy to provide code but its happening on all my bots, several of which have entirely different codebases.

Any advice would be appreciated.
fast osprey
viscid hornet
#

why not either:

  1. move the headers to be a bot attribute so you can use it in whatever cog you're using
  2. move the headers into command1.py
white citrus
mild token
#

But 99 times out of 100 you shouldn't be using this check to begin with, when the integrations UI exists to role lock commands can u explain a bit more @fast osprey on this if u dont mind : )

fast osprey
#

the values have to be unique

fast osprey
white citrus
fast osprey
#

Your second list. The value https://streams.ilovemusic.de/iloveradio15.mp3 is in there twice

mild token
white citrus
#

Also my fried was tired

viscid hornet
#

whats the error you were getting?

latent pier
viscid hornet
#

wait so you're importing command1 into bot.py

#

but expecting it to work the other way around?

latent pier
#

Eh?

#

Quite opposite

slim bloom
viscid hornet
latent pier
slim bloom
#

code: ```py
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, aiohttp

color_lace = discord.Color.from_rgb(60, 161, 224)

class Autopfp(commands.Cog):
def init(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
self.send_pfp.start()

    @tasks.loop(minutes=1)
    async def send_pfp(self):
        print("Funcionando...")``` error: ```Cog error: autopfp: Extension 'src.cogs.autopfp' raised an error: AttributeError: 'Autopfp' object has no attribute 'send_pfp'``` how can fix?
slim bloom
latent pier
#

It's a task 🗣️

slim bloom
slim bloom
timber dragon
#

Move it outside the __init__

slim bloom
timber dragon
#

or remove self from it and start it like send_pfp.start()

timber dragon
latent pier
#

send_pfp function is inside __init__ function

slim bloom
timber dragon
#

Move that to after the function

#

I would recommend moving it outside the init

viscid hornet
#

and everything else in the loop - move that an indent backwards

timber dragon
#
# outside the class
def foo(...):
    ...

class Foo:
    def bar(self):
        # inside a method <- you, bad
        def foo():
            ...

    # in the class <- good
    def foo(self):
        ...
slim bloom
#

gg

#
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, aiohttp

color_lace = discord.Color.from_rgb(60, 161, 224)

@tasks.loop(minutes=1)
async def send_pfp():
    print("Funcionando...")

class Autopfp(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
        send_pfp.start()```
#

@viscid hornet Is it still okay?

viscid hornet
#

that wasnt what i meant

#

@timber dragon does it look... decent at the very least?

slim bloom
viscid hornet
#

fair enough

slim bloom
timber dragon
#

That works too if you don't need it to be part of the class shrug

slim bloom
#

@viscid hornet

#

im stupid

#

now work

#
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector

color_lace = discord.Color.from_rgb(60, 161, 224)

class Autopfp(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))

        @self.bot.event
        async def on_ready():
            self.send_pfp.start()

    @tasks.loop(minutes=1)
    async def send_pfp(self):
        print("Funcionando...")
        try:
            cursor = self.database.cursor()
            cursor.execute("SELECT guild_id, channel_id FROM autopfp")
            results = cursor.fetchall()

            for guild_id, channel_id in results:
                guild = self.bot.get_guild(guild_id)
                if guild:
                    channel = guild.get_channel(channel_id)
                    if channel:
                        webhooks = await channel.webhooks()
                        if not webhooks:
                            webhook = await channel.create_webhook(name=self.bot.user.name)
                        else:
                            webhook = webhooks[0]

                        await webhook.send("skibidi", username=self.bot.user.name, avatar_url=self.bot.user.avatar.url)```
viscid hornet
slim bloom
#

Should I implement aiohttp so that it sends the webhook with aiohttp or should I leave it like that?

viscid hornet
#

@slate swan

viscid hornet
slim bloom
slim bloom
slate swan
slim bloom
viscid hornet
slim bloom
#

but if I add aiohttp or not?

latent pier
slim bloom
latent pier
#

Or you need it in your code?

slim bloom
slim bloom
#

?

slim bloom
#

@viscid hornet

#

code: ```py
random_member = random.choice(guild.members)
avatar_url = random_member.avatar.url

                    embed = discord.Embed(color=color_lace)
                    embed.set_image(url=avatar_url)
                    await webhook.send(embed=embed, username=self.bot.user.name, avatar_url=str(self.bot.user.avatar_url))``` error: ```Error: 'ClientUser' object has no attribute 'avatar_url'```
viscid hornet
timber dragon
#

Consider using..display_avatar

wanton current
#

soheeeeeeeeeeeeb

finite salmon
#

sohe

slate swan
#

soheap stab

blazing beacon
#

sostack

wanton current
#

sostackoverflow

slim bloom
wanton current
#

it will never be None

slim bloom
#

thx

slim bloom
#
import discord
from discord.ext import commands
from discord import app_commands

color_lace = discord.Color.from_rgb(60, 161, 224)

class Banner(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="banner", description="Muestra el banner de una persona")
    @app_commands.describe(user="el usuario a mostrar")
    async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
        try:
            user = user or interaction.user

            embed = discord.Embed(color=color_lace)
            embed.set_image(url=user.banner.url)
            await interaction.response.send_message(embed=embed)

        except Exception as e:
            await interaction.response.send_message(f"Error: {e}", ephemeral=True)

async def setup(bot):
    await bot.add_cog(Banner(bot))```
#

has no atributte .url

wanton current
#

code?

slim bloom
#
import discord
from discord.ext import commands
from discord import app_commands

color_lace = discord.Color.from_rgb(60, 161, 224)

class Banner(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="banner", description="Muestra el banner de una persona")
    @app_commands.describe(user="el usuario a mostrar")
    async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
        try:
            user = user or interaction.user

            embed = discord.Embed(color=color_lace)
            embed.set_image(url=user.banner.url)
            await interaction.response.send_message(embed=embed)

        except Exception as e:
            await interaction.response.send_message(f"Error: {e}", ephemeral=True)

async def setup(bot):
    await bot.add_cog(Banner(bot))```
#

wait

slim bloom
wanton current
#

there's your problem

slim bloom
slim bloom
#

@viscid hornet pls

vapid parcel
#
Traceback (most recent call last):
  File "/mnt/games-auto/PythonProjects/UniBot-Rev/.venv/lib/python3.11/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/mnt/games-auto/PythonProjects/UniBot-Rev/.venv/lib/python3.11/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'nickedit' raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```

```py
        elif isinstance(error, commands.CommandInvokeError):
            if isinstance(error.original, discord.Forbidden):
                member = ctx.message.mentions[0] if ctx.message.mentions else None

                if member:
                    if ctx.author.top_role < member.top_role:
                        error_embed = ErrorEmbed(
                            title="Error",
                            description="You cannot perform this action due to role hierarchy.",
                        )
                        await ctx.send(embed=error_embed, ephemeral=True)

                    elif ctx.guild.me.top_role <= member.top_role:
                        error_embed = ErrorEmbed(
                            title="Error",
                            description="I cannot perform this action due to role hierarchy.",
                        )
                        await ctx.send(embed=error_embed, ephemeral=True)

                    else:
                        error_embed = ErrorEmbed(
                            title="Error",
                            description="I don't have the necessary permissions to perform this action.",
                        )
                        await ctx.send(embed=error_embed, ephemeral=True)```
#

This part of my error handling should handle that error if im not wrong..?

viscid hornet
#

!paste it for me so i can see syntax on phone

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.

viscid hornet
slim bloom
#

url no atribbute

viscid hornet
#

!d discord.User.banner

unkempt canyonBOT
#

property banner```
Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
vapid parcel
viscid hornet
vapid parcel
#

That was done by jiggly GoofySkull

#

Actually, I know why he did it I think, because we are using Hybrid

viscid hornet
#

ohh ok i see

vapid parcel
#

You can use ephemeral with ctx

#

if hybrid

viscid hornet
#

!d discord.ext.commands.CommandInvokeError.original

unkempt canyonBOT
vapid parcel
#

I am just trying to understand why the error handling is not working properly..? Cuz It used to work I thought lmao

#

Unless jiggly fucked it up, cuz I haven't touched it since jiggly did whatever he did 😭

viscid hornet
#

does it miss the command invoke error completely?

#

also i think discord.Forb is its own separate error to CIE

vapid parcel
#

to see if it would just give an error for when I tried to change my nick name with my bot, which should return last level

viscid hornet
#

i meant for the error

slim bloom
#

@viscid hornet

#
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, time

color_lace = discord.Color.from_rgb(60, 161, 224)

class Autopfp(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
        time.sleep(1)
        self.send_pfp.start()

    @tasks.loop(minutes=1)
    async def send_pfp(self):```
#

alr

lyric solar
#

is anyone alive

#

@viscid hornet are u alive❓

latent pier
lyric solar
#

how do i sync bot.tree.command

#

like

#

globally not guild specific

latent pier
lyric solar
outer violet
#

i have this code here where im trying to make it evaluate code if the code block starts with ``` or ```py. so far doing ``` works but ```py doesnt and its giving this error:

NameError: name 'py' is not defined
Traceback (most recent call last):
  File "/Users/st1xkz/bobert/bobert/plugins/admin/eval.py", line 189, in mention_eval
    await fn()
  File "<ast>", line 2, in __bobert_eval
NameError: name 'py' is not defined

heres the code: https://pastes.dev/xAoiG9RKzn

#

wait nvm i fixed it

slate swan
#

How do I catctch fish in python

lucid mirage
# slate swan How do I catctch fish in python
import random

def fish():
    # Fish types and their probabilities
    fish_types = ["salmon", "trout", "bass", "catfish"]
    probabilities = [0.4, 0.3, 0.2, 0.1]

    # Catch a fish based on probabilities
    fish_index = random.choices(range(len(fish_types)), weights=probabilities)[0]
    return fish_types[fish_index]

def main():
    print("Let's go fishing!")
    while True:
        input("Press Enter to cast the line...")
        caught_fish = fish()
        print(f"You caught a {caught_fish}!")
        if input("Do you want to keep fishing? (yes/no): ").lower() != "yes":
            print("Thanks for fishing with us!")
            break

if __name__ == "__main__":
    main()
#

provided by chat gpt 💯

naive briar
#

!rule 10 ducky_wizard

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

lucid mirage
# unkempt canyon

Sure, I can guide you through creating a simple fishing game in Python.

First, you'll need to decide on the rules and mechanics of your game. Here's a basic outline:

Setting up the game: Define the environment, such as the lake or river where the fishing will take place.

Casting the line: Allow the player to cast their fishing line into the water.

Catching fish: Simulate the process of catching fish. You can have different types of fish with varying probabilities of being caught.

Displaying the catch: Show the player what fish they caught.

Repeat or end the game: Ask the player if they want to keep fishing or end the game.

Here's a simplified version of how you could implement this in Python:

lucid mirage
#

python is full of serious bussnies men/women

sick birch
finite salmon
#

There are chances it can spread misinformation

drifting arrow
rugged shadow
drifting arrow
#

You don’t understand lol.

#

If you’re taught in school that Ireland is a fake country, you will spread that information. It’s not your fault, it’s what you were taught. You may eventually learn it’s real but that’s beyond the point, you were taught wrong. That’s the same with ai. It is taught wrong information because we are feeding it wrong information, it’s not its fault.

#

It can only spread what it knows and what it might know is misinformation put on the internet by us

#

Your lack of understanding and of math is only due to your inability to learn, not the books fault. But if the book told you that 1+1 is 5 you might learn that. You might eventually teach it to others. But it isn’t your fault it’s the books

naive briar
#

They can just make stuff up, in simple terms

slate swan
mild token
#

i have to check for some stuff everytime before bot starts should i keep those stuff under on_ready or some other event?

slate swan
#

setup_hook event would be recommended as its called only once

#

I dont really know, I think both events are called when bot is ready, not before

mild token
naive briar
naive briar
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
naive briar
mild token
#

hmmm

#

looks like on_ready should be the one i should look into

#

i want to setup the persistent view for 2 embeds without triggering the command

#

both will have buttons for interaction

slate swan
#

yeah then you should use setup hook

mild token
finite salmon
#

Can someone help as to why isnt discord.errors.Forbidden getting caught in the error handler? This only arises when someone uses a slash command of my bot and it requires to edit a message it sent

class ErrorHandler(commands.Cog):
    def __init__(self, bot: Bot):
        self.bot = bot

    @discord.Cog.listener()
    async def on_ready(self):
        print(f"{Path(__file__).name} cog is ready.")

    @commands.Cog.listener()
    async def on_application_command_error(
        self, ctx: discord.ApplicationContext, error: discord.DiscordException
    ):
        print(error)
        print(error.args)
        print()
        
        if isinstance(error, discord.errors.Forbidden):
            print("forbidden", error.code)
            print(error.response)
            print(error.status)
            print(error.text)
            if error.code == 50001:
                try:
                    await ctx.author.send(
                        embed=QuickEmbed(
                            f"I'm missing access to the channel {ctx.channel.mention}.",
                            error=True,
                        )
                    )
                except (discord.Forbidden, discord.HTTPException):
                    pass
#

and this is the error

Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-1ae31f094207752942515d267d455739' coro=<View.on_timeout() done, defined at C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\ui\view.py:364> exception=Forbidden('403 Forbidden (error code: 50001): Missing Access')>
Traceback (most recent call last):
  File "C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\ui\view.py", line 378, in on_timeout
    m = await message.edit(view=self)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\message.py", line 1528, in edit
    data = await self._state.http.edit_message(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\http.py", line 367, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
finite salmon
#

but for some reason on_application_command_error isnt even being called

#

im using pycord btw

finite salmon
#

no

#

none of them get printed

shrewd apex
#

u sure that cog is loaded?

finite salmon
#

yeah

#

the on_ready gets triggered

finite salmon
shrewd apex
#
@commands.Cog.listener()
    async def on_application_command_error(
        self, ctx: discord.ApplicationContext, error: discord.DiscordException
    ):
        print("I am in") # <--- can u add something like this to check if it works?
        print(error)
        print(error.args)
        print()
shrewd apex
#

views error handling is different

finite salmon
#

oh

shrewd apex
#

it dosent come under application command handler

#

u need to check inside that

finite salmon
#

oh alr

#

ty

shrewd apex
#

np

mild token
#

suppose i am taking data from modal and then sending it to a api incase api takes long time for response after how many minute interaction will fail?

naive briar
naive briar
#

!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...
nova vessel
#

What is the Redirect URi and how do I set it up?

mild token
#

!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.
mild token
#

if i use the message kwargs it will be automatically be converted to public thread?

#

is there a way so i can add role to a private thread?

shrewd apex
drifting arrow
#

Omg. I just got what Kwargs means! It’s key word arguments!

shrewd apex
#

noice

mild token
#

i want to add roles to it

shrewd apex
mild token
drifting arrow
shrewd apex
#

hmm dont see anything related to adding roles in threads, doubt thats allowed

mild token
shrewd apex
#

u can ping

mild token
#

then might be allowed to add role or i am coping 😭

shrewd apex
#

but no way to explicitly allow only a particular role from what i see

viscid hornet
#

when you ping a role it acts as a multi ping

mild token
#

means?

shrewd apex
#

just test it out

drifting arrow
#

Just create a new channel that has the roles and permissions you want and put the thread there lol

viscid hornet
mild token
viscid hornet
mild token
#

alright

drifting arrow
#

Guys

viscid hornet
drifting arrow
#

You are overthinking it. New channel limited to perms. Put thread onto said channel

#

:D

mild token
#

i am using private thread

viscid hornet
mild token
viscid hornet
#

👌

mild token
#

@drifting arrow private thread will work like this, it will not use channel role perms

latent pier
drifting arrow
latent pier
slate swan
#

axo stab

nova vessel
#

How do I setup the Redirect URi for my bot?

viscid hornet
mild token
#

what meant by channel override? in app integration of server settings?

latent pier
drifting arrow
mild token
#

and bot dont change those setting if i restart right?

drifting arrow
#

Channel override changes the settings in the channel not bot

mild token
latent pier
#

Bot's integration overrides?

latent pier
#

If you meant integration app overrides from the server settings

mild token
#

this thing

#

if i add this in channel overirde this command will not be shown there?

latent pier
#

If you disallow it

mild token
#

ok so in simple terms i can remove that command from there

latent pier
#

Yes

mild token
#

if something is not there means it will be shown in every channel right?

latent pier
#

I guess so

#

There's a option to select all channels

mild token
#

what will happen like if i have 2 role and they are opposite of each other like one allows to send message and other dont which will take precedence

naive briar
#

The higher one

latent pier
latent pier
mild token
naive briar
#

Yes

latent pier
viscid hornet
#

ray i saw that

tawdry vector
#

How to check if a embed contains a specific word or not

shrewd apex
tawdry vector
#

if "rare catch detected" in msg.embeds.title.lower():

tawdry vector
shrewd apex
#

afaik a message can have upto 5 embeds i think

tawdry vector
#

I see hold on leeme check

#

@shrewd apex look like it's a new issue

vivid lynx
shrewd apex
#

ratelimited

vivid lynx
shrewd apex
#

not really its just repl.it shared ip system

vivid lynx
#

it used to be but not anymor

shrewd apex
#

it never was

vivid lynx
shrewd apex
#

i prefer digital ocean, hetzner etc

vivid lynx
shrewd apex
#

u need a credit card tho afaik and if u dont mind about data security

tawdry vector
shrewd apex
#

oracle dosent really have the best reputation for data safety practices

shrewd apex
tawdry vector
#

I see

vivid lynx
vivid lynx
shrewd apex
#

its not free, nothings free almost everything has a clause or price attached lol

#

those are cheaper alternatives

#

especially the arm vms

vivid lynx
#

welp fadfddsf

fast osprey
#

Why would someone pay their own money to run something for you, a rando, forever.

tawdry vector
#

List don't have attribute length??

shrewd apex
#

or if ur feeling fancy msg.embeds.__len__()

tawdry vector
#
  @commands.Cog.listener()
  async def on_message(self, msg):

    

    if msg.author == self.bot.user or len(msg.embeds) == 0:
      return

    

    if "rare catch detected" in msg.embeds[0].title.lower() :   
      
      await self.bot.get_channel(rare_channel_id).send(msg.content)
      await self.bot.get_channel(rare_channel_id).send("hi")

    
    elif "shiny catch detected" in msg.embeds[0].title.lower():
      
      await self.bot.get_channel(shiny_channel_id).send(msg.content)

    else:
      print("nothing")
#

I don't get it

shrewd apex
#

title of the embed is None

#

meaning the embed dosent have a title, u might wanna do print(msg.embeds[0].to_dict()) to see contents of the embed

vivid lynx
latent pier
mild token
#

can i get names of all the thread private/public of a channel?

viscid hornet
unkempt canyonBOT
viscid hornet
#

im so smart

mild token
latent pier
viscid hornet
mild token
viscid hornet
viscid hornet
latent pier
#

Returns all the threads that you can see.

mild token
viscid hornet
#

your_thread.name

viscid hornet
mild token
# viscid hornet

yeah i get that i am not saying i dont know i am looking for efficient handling

latent pier
viscid hornet
viscid hornet
#

no more mr nice guy

mild token
latent pier
viscid hornet
mild token
viscid hornet
#

or if you wanna search all threads for the name, use utils.get: py utils.get(your_text-channel.threads, name = 'the string')

#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
viscid hornet
mild token
#

i forgot about utils existance

viscid hornet
#

@latent pier you stink 🗣️

latent pier
#

Daydreaming

viscid hornet
latent pier
viscid hornet
latent pier
viscid hornet
mild token
#

if i try to send message in archived channel , channel will get auto unarchived?

shrewd vapor
#

Heyo anyone can help me with this error please ? Its for a bot who make a announcment when a new product or restock is made on the taylorswift-store.fr

2024-05-14 14:36:42 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 453a32f612f9574a037d597dd2f9f235).
INFO:discord.gateway:Shard ID None has connected to Gateway (Session ID: 453a32f612f9574a037d597dd2f9f235).
Logged in as Restock#5326
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): taylorswift-store.fr:443
DEBUG:urllib3.connectionpool:https://taylorswift-store.fr:443 "GET //products.json?limit=250 HTTP/1.1" 200 None
INFO:__main__:Taylor Swift Store FR Has Been Cached (37 Products)
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): taylorswift-store.fr:443
DEBUG:urllib3.connectionpool:https://taylorswift-store.fr:443 "GET //products.json?limit=250 HTTP/1.1" 200 None
WARNING:__main__:Taylor Swift Store FR 'int' object is not subscriptable```
viscid hornet
shrewd vapor
#

Yes i think because on Taylor Swift discord they do this

#

I have just take the js code and translate in py

naive briar
#

Translate how?

shrewd vapor
#

i have ask ChatGPT because i'm not good in js

viscid hornet
#

its their website and its their service

shrewd vapor
#

No

#

Its not the official discord

#

Its a discord for the Swifties

naive briar
viscid hornet
naive briar
#

Ah, it's not official then

shrewd vapor
#

He do merch announcement, music and others things

#

The bot is used in r/Taylor Swift discord and Swifties discord and maybe more because its explained how to start the bot on ubuntu

viscid hornet
#

im gonna say this isnt tos

#

@naive briar what do you think

naive briar
#

It's suspicious, honestly

#

Anyway, gotta go

shrewd vapor
#

I just want French Swifties can know when we get a restock or a new product on the french store because everytimes we don't know and everythings is out of stock in 2 minutes

viscid hornet
#

!paste @shrewd vapor put your code here and send us the link

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.

shrewd vapor
latent pier
viscid hornet
#

gpt translated from js

shrewd vapor
#

haha

#

yes because i hate js

viscid hornet
#

do you know any python

shrewd vapor
#

yes, i just don't really have check the code

#

I work on multiple things

latent pier
mild token
#
check_thread_exists = discord.utils.get(await interaction.client.fetch_channel(REGISTER_REP_CHANNEL_ID).threads, name=thread_title)

interaction.client.fetch_channel(REGISTER_REP_CHANNEL_ID).threads, name=thread_title)
AttributeError: 'coroutine' object has no attribute 'threads'

why???

latent pier
mild token
#

!d discord.TextChannel.threads

unkempt canyonBOT
mild token
#

text channel should have this

#

fetch_channel gives text channel right?

latent pier
mild token
#

then why its erroring out

meager rock
#

it's a coroutine, you should be awaiting it

latent pier
#

interaction.client?

meager rock
#

oh nvm you are

mild token
#

discord.util is not coroutine

latent pier
mild token
latent pier
#

That's what he said

meager rock
#

here's your issue

await fetch_channel(...).threads
``` means 
You're awaiting .threads ```py
(await fetch_channel(...)).threads
``` is what u need
mild token
#

oki

#

ty

latent pier
#

make it little simple and get a channel variable

channel = await bot.fetch_channel()
mild token
meager rock
#

^ i would also suggest to use bot.get_channel(...) or await bot.fetch_channel(...) if you have cache enabled

latent pier
#

^^

#

That's better option

#

if get_channel doesnt return channel it'll pass onto fetch which will make a api call

meager rock
#

i subclass my Bot class and make a getch function to implement this, just for sake of comfort

onyx flame
#

‘’hi’’

meager rock
#

😭 wow

latent pier
onyx flame
#

‘Hello’

latent pier
onyx flame
#

Hello

vivid lynx
#

i developed a new bot

#

in python

#

it is op

meager rock
#

!d disnake.Client.getch_user

unkempt canyonBOT
#

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

Tries to get the user from the cache. If it fails, fetches the user from the API.

This only propagates exceptions when the `strict` parameter is enabled.
vivid lynx
meager rock
latent pier
vivid lynx
#

i made abot i will showcase it now

latent pier
vivid lynx
#

its highly skidded tho

meager rock
#

it's just 2 lines of code so

vivid lynx
meager rock
vivid lynx
meager rock
#

Wait they were rewriting it

vivid lynx
#

MY BOT OPPP

latent pier
meager rock
#

it's nice but the codebase lowkey sucks

latent pier
meager rock
#

in the end the library you're able to work with is the best one for you 😊

vivid lynx
#

Successfully Injected trojan.exe ( this is a prank guys dont get scared )

latent pier
#

Dude is self boting

vivid lynx
shrewd vapor
#

nice selfbot, this is against discord tos

latent pier
meager rock
#

🤣 recorded, this is going to the mods.

vivid lynx
shrewd vapor
#

yes recorded and sended to discord

vivid lynx
latent pier
vivid lynx
meager rock
shrewd vapor
#

don't worries, they respond in ~4h everytimes for me

vivid lynx
latent pier
#

I got a screenshot

vivid lynx
#

seems like someone from dat country got angry :<

latent pier
#

Seems like 14 yo kid to me

pale zenith
#

Y'all are just feeding the troll rather than ignoring them lol

vivid lynx
latent pier
#

Self boting caught 📸

vivid lynx
#

YOOOOO :DDDDD

vivid lynx
pure hill
latent pier
#

Ayye Seedhe Maut 🤣

vivid lynx
pure hill
meager rock
latent pier
#

Bro's 1v3 rn

vivid lynx
latent pier
meager rock
#

don't understand what buddy, your first message in the channel was "any girls here?" !?

vivid lynx
#

ok here is a suggestion , from this message lets stop fighting

pure hill
#

😈 Are you scared lil buddy

vivid lynx
mild token
#

is there any way to restore the interaction if my process take more time?

vivid lynx
pure hill
#

casual way to have me slide in your dms, i refuse

#

im not

vivid lynx
mild token
latent pier
meager rock
pure hill
lyric sphinx
unkempt canyonBOT
#
Nuh-uh.

No documentation found for the requested symbol.

meager rock
#

Wtf is this bot high?

latent pier
#

Tf?

#

Wait

mild token
#

👀

vivid lynx
meager rock
#

nvm it's me

lyric sphinx
#

!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...
meager rock
#

!d discord.Interaction.response returns an interaction response object

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

latent pier
#

!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...
meager rock
#

And this^

mild token
#

ok so i just need to add defer after response and then send_message right?

lyric sphinx
mild token
#

oh so interaction.defer.response.send_message?

meager rock
#

you'll have to edit_initial_response after you're done with the stuff in your code to respond again

lyric sphinx
latent pier
#
async def test(interaction: nextcord.Interaction):
    await interaction.response.defer()
    await asyncio.sleep(10) # Doing stuff
    await interaction.followup.send("My actual content", ephemeral=True)

Example

mild token
#

got it

#

woops

pale zenith
latent pier
#

Woops

#

My bad

mild token
#

i mean in followup will it work?

latent pier
mild token
pale zenith
# mild token i mean in followup will it work?

It's actually a bit nuanced.

If this is a button interaction, and you didn't defer(thinking=True), then you can set ephemeral=True in the followup.

For command interactions (and button interactions with thinking set to True), then the defer(ephemeral=...) will be used for the first followup, since all it's doing is editing the message rather than sending a new one.

For subsequent followup messages, then the ephemeral you pass to followup will always be respected.

mild token
latent pier
meager rock
#

@glad cradle I'm starting the rewriting tonight, if you have ideas related to design choices and stuff feel free to suggest cause I suck at it
( covering the gateway and rest handler today)

mild token
#

is there a way to archive and unarchive thread?

pale zenith
unkempt canyonBOT
#

await edit(*, name=..., archived=..., locked=..., invitable=..., pinned=..., slowmode_delay=..., auto_archive_duration=..., applied_tags=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the thread.

Editing the thread requires [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads). The thread creator can also edit `name`, `archived` or `auto_archive_duration`. Note that if the thread is locked then only those with [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) can unarchive a thread.

The thread must be unarchived to be edited.
mild token
#

tnx

#

if my bot will only stay in thread and i closed the thread then that thread is destroyed?

#

my bot not able to fetch the closed thread

#

is there any way to fetch those?

hushed galleon
unkempt canyonBOT
#

async for ... in archived_threads(*, private=False, joined=False, limit=100, before=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that iterates over all archived threads in this text channel, in order of decreasing ID for joined threads, and decreasing [`Thread.archive_timestamp`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.archive_timestamp) otherwise.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If iterating over private threads then [`manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) is also required.

New in version 2.0.
hushed galleon
unkempt canyonBOT
#

discord/state.py lines 901 to 903

if thread.archived:
    guild._remove_thread(thread)
self.dispatch('thread_update', old, thread)```
mild token
#

I am trying to check every thread of a channel if it's archived,locked or unarchived doesn't matter

#

Is there any way to do it?

hushed galleon
#

sounds like archived_threads() + channel.threads would be sufficient

mild token
#

Problem I am getting is if I close the thread and then run the code it creates new one if I don't close the thread then it adds

latent pier
#

You can zip() them

mild token
#

Closing means archived?

hushed galleon
#

yes

mild token
hushed galleon
mild token
#

And I can edit close thread right?

hushed galleon
#

on_thread_update would likely be more efficient to use than archived_threads() here, though it would be a bit less reliable...

latent pier
#

But yeah discord.utils will work

mild token
mild token
hushed galleon
#

er yeah

latent pier
#
names = ['Mukesh', 'Roni', 'Chari'] 

ages = [24, 50, 18] 


for i, (name, age) in enumerate(zip(names, ages)): 

    print(i, name, age)
hushed galleon
#

have you considered storing the thread IDs in a database so you don't have to fetch archived threads?

mild token
mild token
hushed galleon
#

i believe certain actions like adding members can't be taken until you've unarchived it

mild token
#

After that I will add the member : ) there

hushed galleon
#

ye its the same method that leonardo showed you earlier

mild token
#

I am trying to keep my code faster : ( ,so even if more people uses bot it won't be a problem

latent pier
#

Oh i see

viscid hornet
#

!d discord.Thread

unkempt canyonBOT
#

class discord.Thread```
Represents a Discord thread.

x == y Checks if two threads are equal.

x != y Checks if two threads are not equal.

hash(x) Returns the thread’s hash.

str(x) Returns the thread’s name.

New in version 2.0.
latent pier
viscid hornet
#

i was reading docs cuz i was curious on smth 😭

latent pier
latent pier
viscid hornet
viscid hornet
latent pier
latent pier
viscid hornet
#

thanks for that one

latent pier
viscid hornet
latent pier
#

What else?

slate swan
#

axo stab

viscid hornet
latent pier
mild token
#

is it possible to transfer thread from one channel to another?

viscid hornet
latent pier
mild token
viscid hornet
viscid hornet
#

oh wait thats not ray

latent pier