#How to add custom decorator from custom AutoShardedBot class in a cog ?

1 messages · Page 1 of 1 (latest)

worthy juniper
#

Hello, I don't know if my problem is clear from the title, but you will understand with the code :

# file ./main.py
class ShardedBot(discord.AutoShardedBot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def start(self, token: str, *, reconnect: bool = True):
        await self.setup_database()
        await self.setup_translator()
        
        # Load cogs
        for filename in os.listdir('./cogs'):
            if filename.endswith('.py'):
                bot.load_extension(f'cogs.{filename[:-3]}')
                
        await self.login(token)
        await self.connect(reconnect=reconnect)

    async def setup_translator(self):
        
        proxy = "PRIVATE"
        
        self.trad = Translator(proxy=proxy)
        print(f"=== Proxy Setup updated ! ===")
    

    def translator_handler(self, func):
        """Decorator to handle translation and rate limiting errors."""
        async def wrapper(*args, **kwargs):
            try:
                return await func(*args, **kwargs)
            except RateLimitError:
                await self.setup_translator()
                try:
                    return await func(*args, **kwargs)
                except RateLimitError:
                    raise RateLimitError("Rate limit error even after changing proxy.")
        return wrapper

bot = ShardedBot()


# file ./cogs/message_translator.py
class MessageTranslator(Cog):
    def __init__(self, bot):
        self.bot = bot

    @self.bot.translator_handler # self is not defined
    @Cog.listener()
    async def on_message(self, message):
        # Some code here

I would like to use the decorator translator_handler from my main file in my cog. How can I do that ?

oak sky
#
from .main import ShardedBot

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

    @ShardedBot.translator_handler
    @Cog.listener()
    async def on_message(self, message):
        # Some code here
#

main:


if __name__ == "__main__":
    bot = ShardedBot()
    bot.run(TOKEN)
#

@worthy juniper

worthy juniper
#

okay, I will try it, I am making the RateLimitError class in my library to be able to test this code

oak sky
#

ok

worthy juniper
oak sky
#

do ..main else

worthy juniper
worthy juniper
oak sky
#

not ..

#

but if its root just do from main import class

worthy juniper
oak sky
#

from main import class

worthy juniper
#

I tried too, and it says I am missing 2 required arguments (self and func)

oak sky
#

i didnt check ur decorator

#

im gonna make some test in a bit

oak sky
#

@worthy juniper

#

by doing like so :

#
    def test_decorator(self):
        async def wrapper(func, *args, **kwargs):
            print("ok")
            try:
                return await func(*args, **kwargs)
            except:
                print("error")
                pass

        return wrapper

#

it works fine

worthy juniper
#

I have tried on the on_ready event to raise the exception and try it, I have got this issue :

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/app/main.py", line 82, in wrapper
    return await func(*args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^
TypeError: 'ShardedBot' object is not callable

Here is the code :

    # On ready
    @translator_handler
    async def on_ready(self):
        print('===== Translator Bot is ready ! =====')
        while True:
            await self.bot.trad.detect("Bonjour comment ça va ?")
#

@oak sky

oak sky
worthy juniper
# oak sky Show me ur decorator
    def translator_handler(self):
        async def wrapper(func, *args, **kwargs):
            try:
                return await func(*args, **kwargs)
            except RateLimitError:
                print("Rate limit error. Changing proxy.")
                await self.setup_translator()
                try:
                    return await func(*args, **kwargs)
                except RateLimitError:
                    raise RateLimitError("Rate limit error even after changing proxy.")
        return wrapper
oak sky
#

Im at the restaurant I look after

worthy juniper
#

okay no problem

#

I found a way !

    @staticmethod
    def translator_handler(func):
        @wraps(func)
        async def wrapper(self, *args, **kwargs):
            try:
                return await func(self, *args, **kwargs)
            except RateLimitError:
                await self.setup_translator()
                try:
                    return await func(self, *args, **kwargs)
                except RateLimitError:
                    raise RateLimitError("Rate limit error even after changing proxy.")
        return wrapper