def load_config(self):
        """
        Load configuration from path specified by the framework.

        Configuration file is in YAML format.
        """
        config_path = efb_utils.get_config_path(self.channel_id)
        if not config_path.exists():
            raise FileNotFoundError(self._("Config File does not exist. ({path})").format(path=config_path))
        with config_path.open() as f:
            data = yaml.load(f)

            # Verify configuration
            if not isinstance(data.get('token', None), str):
                raise ValueError(self._('Telegram bot token must be a string'))
            if isinstance(data.get('admins', None), int):
                data['admins'] = [data['admins']]
            if isinstance(data.get('admins', None), str) and data['admins'].isdigit():
                data['admins'] = [int(data['admins'])]
            if not isinstance(data.get('admins', None), list) or len(data['admins']) < 1:
                raise ValueError(self._("Admins' user IDs must be a list of one number or more."))
            for i in range(len(data['admins'])):
                if isinstance(data['admins'][i], str) and data['admins'][i].isdigit():
                    data['admins'][i] = int(data['admins'][i])
                if not isinstance(data['admins'][i], int):
                    raise ValueError(self._('Admin ID is expected to be an int, but {data} is found.')
                                     .format(data=data['admins'][i]))

            self.config = data.copy()
Exemple #2
0
    def __init__(self, instance_id: Optional[InstanceID] = None):
        super().__init__(instance_id)

        # load config
        self.yaml = YAML()
        conf_path = utils.get_config_path(self.middleware_id)
        if not conf_path.exists():
            conf_path.touch()
        self.config = self.yaml.load(conf_path)

        self.filters = [self.chat_id_based_filter]

        # Mapping
        self.FILTER_MAPPING = {
            "chat_name_contains": self.chat_name_contains_filter,
            "chat_name_matches": self.chat_name_matches_filter,
            "message_contains": self.message_contains_filter,
            "ews_mp": self.ews_mp_filter
        }

        # Chat ID based filter init
        shelve_path = str(
            utils.get_data_path(self.middleware_id) / "chat_id_filter.db")
        self.chat_id_filter_db = shelve.open(shelve_path)
        atexit.register(self.atexit)

        # load other filters
        if isinstance(self.config, Mapping):
            for i in self.config.keys():
                f = self.FILTER_MAPPING.get(i)
                if f:
                    self.filters.append(f)
Exemple #3
0
 def save_config(self):
     coordinator.profile = self.profile
     conf_path = utils.get_config_path()
     if not os.path.exists(conf_path):
         os.makedirs(os.path.dirname(conf_path))
     with open(conf_path, 'w') as f:
         self.yaml.dump(self.config, f)
Exemple #4
0
def wizard(profile, instance_id):
    data = {}
    config_path = efb_utils.get_config_path(TelegramChannel.channel_id)
    if Path(config_path).exists():
        with config_path.open() as f:
            data = yaml.full_load(f)

    data['api_id'] = int(input("API id: "))
    data['api_hash'] = input("API hash: ")
    data['proxy'] = {}
    data['proxy']['protocol'] = input("Proxy protocol (http or socks5): ")
    data['proxy']['host'] = input("Proxy host: ")
    data['proxy']['port'] = int(input("Proxy port: "))

    loop = asyncio.get_event_loop()
    data_path = efb_utils.get_data_path(TelegramChannel.channel_id)
    proxy = (data['proxy']['protocol'], data['proxy']['host'],
             data['proxy']['port'])
    client = TelegramClient(f'{data_path}/{instance_id}',
                            data['api_id'],
                            data['api_hash'],
                            loop=loop,
                            proxy=proxy)
    client.start()
    print(data)
    with open(config_path, 'w') as f:
        yaml.dump(data, f)
 def load_config(self):
     config_path = efb_utils.get_config_path(self.channel_id)
     if not config_path.exists():
         return
     with config_path.open() as f:
         d = yaml.full_load(f)
         if not d:
             return
         self.config: Dict[str, Any] = d
Exemple #6
0
 def load_config(self) -> Optional[Dict]:
     config_path: Path = get_config_path(self.middleware_id)
     if not config_path.exists():
         raise FileNotFoundError('The configure file does not exist!')
     with config_path.open('r') as f:
         d: Dict[str, Any] = yaml.load(f)
         if not d:
             raise RuntimeError('Load configure file failed!')
         return d
 def load_config(self) -> Optional[Dict]:
     config_path: str = get_config_path(self.middleware_id)
     if not os.path.exists(config_path):
         raise FileNotFoundError('The configure file does not exist!')
     with open(config_path, 'r') as f:
         d = yaml.safe_load(f)
         if not d:
             raise RuntimeError('Load configure file failed!')
         return d
Exemple #8
0
    def load_config(self):
        """
        Load configuration from path specified by the framework.

        Configuration file is in YAML format.
        """
        config_path = efb_utils.get_config_path(self.channel_id)
        if not config_path.exists():
            return
        with config_path.open() as f:
            self.config: Dict[str, Any] = yaml.safe_load(f)
 def load_config(self) -> Optional[Dict]:
     config_path: str = get_config_path(self.middleware_id)
     if not os.path.exists(config_path):
         self.logger.info('The configure file does not exist!')
         return
     with open(config_path, 'r') as f:
         d: Dict[str, str] = yaml.load(f)
         if not d:
             self.logger.info('Load configure file failed!')
             return
         return d
 def load_config(self) -> Optional[Dict]:
     config_path: Path = get_config_path(self.middleware_id)
     if not config_path.exists():
         self.logger.info('The configure file does not exist!')
         return
     with config_path.open('r') as f:
         d: Dict[str, Any] = yaml.load(f)
         if not d:
             self.logger.info('Load configure file failed!')
             return
         return d
Exemple #11
0
 def __init__(self, profile: str, instance_id: str):
     coordinator.profile = profile
     self.profile = profile
     self.instance_id = instance_id
     self.channel_id = WeChatChannel.channel_id
     if instance_id:
         self.channel_id = ModuleID(self.channel_id + "#" + instance_id)
     self.config_path = utils.get_config_path(self.channel_id)
     self.yaml = YAML()
     if not self.config_path.exists():
         self.build_default_config()
     else:
         self.data = self.yaml.load(self.config_path.open())
Exemple #12
0
    def load_config(self):
        """
        Load configuration from path specified by the framework.

        Configuration file is in YAML format.
        """
        config_path = efb_utils.get_config_path(self.channel_id)
        if not os.path.exists(config_path):
            return
        with open(config_path) as f:
            d = yaml.load(f)
            if not d:
                return
            self.config: Dict[str, Any] = d
 def process_message(self, message: Message) -> Optional[Message]:
     config = yaml.full_load(
         open(utils.get_config_path(self.middleware_id), encoding="UTF-8"))
     if isinstance(message.author, SelfChatMember):
         return message
     if self.config_version != config.get('version'):
         self.logger.debug("config changed!")
         self.config_version = config.get('version')
         self.work_modes = config.get('work_mode')
     for work_mode in WorkMode:
         if work_mode.value in self.work_modes:
             if config.get(work_mode.value) and self.is_keep_message(
                     work_mode, message, config.get(work_mode.value)):
                 return message
    def __init__(self, profile: str, instance_id: str):
        print("==== etm_wizard, data mod, init", profile)
        coordinator.profile = profile
        self.profile = profile
        self.instance_id = instance_id
        self.channel_id = TelegramChannel.channel_id

        if instance_id:
            self.channel_id = ModuleID(self.channel_id + "#" + instance_id)
        self.config_path = utils.get_config_path(self.channel_id)
        self.yaml = YAML()
        if not self.config_path.exists():
            self.build_default_config()
        else:
            self.data = self.yaml.load(self.config_path.open())
Exemple #15
0
    def load_config(self):
        coordinator.profile = self.profile
        conf_path = utils.get_config_path()
        if not os.path.exists(conf_path):
            self.config = self.yaml.load(self.default_config())

            # Fill in required fields
            if "master_channel" not in self.config:
                self.config['master_channel'] = ""
            if "slave_channels" not in self.config:
                self.config["slave_channels"] = []
            if "middlewares" not in self.config:
                self.config["middlewares"] = []
        else:
            with open(conf_path) as f:
                self.config = self.yaml.load(f)
        self.load_modules_list()
    def __init__(self, instance_id: str = None):
        super().__init__(instance_id)

        storage_path = utils.get_data_path(self.middleware_id)
        config_path = utils.get_config_path(self.middleware_id)
        if not os.path.exists(storage_path):
            os.makedirs(storage_path)
        if not os.path.exists(config_path):
            raise EFBException("Filter middleware is not configured.")
        else:
            config = yaml.safe_load(open(config_path, encoding="UTF-8"))
            self.config_version = 0
            self.match_mode = config.get("match_mode")  # fuzz and exact
            if self.match_mode is None:
                self.match_mode = "fuzz"

        self.logger = logging.getLogger("xzsk2.filter")
        hdlr = logging.FileHandler('./xzsk2.filter.log', encoding="UTF-8")
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        self.logger.setLevel(logging.ERROR)
Exemple #17
0
    def __init__(self, instance_id: str = None):
        super().__init__(instance_id)
        storage_path = utils.get_data_path(self.middleware_id)
        config_path = utils.get_config_path(self.middleware_id)
        if not os.path.exists(storage_path):
            os.makedirs(storage_path)
        if not os.path.exists(config_path):
            # raise EFBException(self._("GnuPG middleware is not configured."))
            pass
        else:
            pass
            # config = yaml.load(open(config_path))
            # # self.key = config['key']
            # # self.always_trust = config.get('always_trust', self.always_trust)
            # # self.binary = config.get('binary', self.binary)
            # # self.password = config.get('password', self.password)
            # # self.server = config.get('server', self.server)
            # self.apikey = config.get('apikey', self.apikey).strip()

        # self.mappings_path = os.path.join(storage_path, "keymap.pkl")
        # if os.path.exists(self.mappings_path):
        #     self.mappings = pickle.load(open(self.mappings_path, 'rb'))

        self.chat = efbchat.SystemChat(
            middleware=self,
            # channel_name=self.middleware_name,
            module_name=self.middleware_name,
            # channel_id=self.middleware_id,
            module_id=self.middleware_id,
            channel_emoji="🤖",
            uid="__trysh.trysh__",
            # chat_name=self.middleware_name,
        )  # EFBChat()
        self.chat.channel_name = self.middleware_name
        self.chat.module_name = self.middleware_name
        self.chat.channel_id = self.middleware_id
        self.chat.module_id = self.middleware_id
        self.chat.channel_emoji = "🤖"
        self.chat.uid = "__trysh.trysh__"
        self.chat.chat_name = self.middleware_name
        # self.chat.chat_type = ChatType.System

        # self.chatMember = efbchat.ChatMember(
        #     chat=self.chat,
        #     middleware=self,
        #     # channel_name=self.middleware_name,
        #     # module_name=self.middleware_name,
        #     # channel_id=self.middleware_id,
        #     # module_id=self.middleware_id,
        #     # channel_emoji="🤖",
        #     uid="__trysh.trysh__",
        #     # chat_name=self.middleware_name,
        # )  # EFBChat()

        self.chat.channel_name = self.middleware_name
        self.chat.module_name = self.middleware_name
        self.chat.channel_id = self.middleware_id
        self.chat.module_id = self.middleware_id
        self.chat.channel_emoji = "🤖"
        self.chat.uid = "__trysh.trysh__"
        self.chat.chat_name = self.middleware_name

        self.logger = logging.getLogger("trysh.trysh")
        self.logger.log(99, f"trysh init ok v:{version}")
        # self.logger.setLevel(99)

        self.t1: threading.Thread = None
        self.t2: threading.Thread = None
        self.t1q: queue.Queue = None
        self.t2q: queue.Queue = queue.Queue()