import os
import pickle
import random
import traceback
from collections import defaultdict
from telethon import utils as telethon_utils
from telethon.sync import events
from telefire.plugins.base import PluginMount
from telefire.telegram import TelegramCommand
from telefire.utils import get_url


class Action(TelegramCommand, metaclass=PluginMount):
    command_name = "auto_reply_test"

    def __call__(self, chat, reply):
        def setup():
            @self.client.on(events.NewMessage)
            async def _inner(evt):
                msg = evt.message
                try:
                    to_chat = await evt.get_chat()
                    sender = await msg.get_sender()
                    if not msg.is_reply and to_chat.username == chat or to_chat.id == chat:
                        self.helpers.messages.log(msg, to_chat, sender)
                        await evt.reply(reply)
                except Exception:
                    traceback.print_exc()
        
        
        self.set_file_handler("auto_reply_test")
        self.logger.info(f"Auto reply start for chat {chat}, reply: {reply}")
        self.run_forever(setup=setup)
