def fetch_dates(self, text_cmd): """ Fetch start and end dates from command string :param text_cmd: string :return: dict """ date_from = datetime.today() - timedelta(days=30) date_from = date_from.strftime(self.DATE_FORMAT) date_to = datetime.today().strftime(self.DATE_FORMAT) args = super(Campaigns, self).parse_arguments(text_cmd) count = len(args) if count == 2: try: date_from = datetime.strptime(args[0] + ' 00:00:00', self.DATE_FORMAT) except ValueError: raise CmdException("Неверный формат даты \"От\"") try: date_to = datetime.strptime(args[1] + ' 23:59:59', self.DATE_FORMAT) except ValueError: raise CmdException("Неверный формат даты \"До\"") if count == 1: try: date_from = datetime.strptime(args[0] + ' 00:00:00', self.DATE_FORMAT) except ValueError: raise CmdException("Неверный формат даты \"От\"") return {"from": date_from, "to": date_to}
def prepare_telegram_response(self, response): """ Prepare user-readable response :param response: string :return: string """ response = json.loads(response) if "error" in response.keys(): raise CmdException(response['error']) if "result" not in response.keys(): raise CmdException("При добавлении email произошла ошибка") return "Email добавлен в список"
def prepare_telegram_response(self, response): """ Prepare user-readable response :param response: string :return: string """ response = json.loads(response) if "error" in response.keys(): raise CmdException(response['error']) result = response['result'] response = "\r\n----------" \ "\r\nTotal: {}" \ "\r\n Sent: {}" \ "\r\n Delivered: {}" \ "\r\n Read unique: {}" \ "\r\n Read all: {}" \ "\r\n Clicked unique: {}" \ "\r\n Clicked all: {}" \ "\r\n Unsubscribed: {}" \ "\r\n Spam: {}" \ "\r\n----------".format( result['total'], result['sent'], result['delivered'], result['read_unique'], result['read_all'], result['clicked_unique'], result['clicked_all'], result['unsubscribed'], result['spam'] ) return response
def run(self, bot, telegram_update, user): """ Run command and send response to user :param bot: Bot :param telegram_update: TelegramUpdate :param user: TeleUser :return: void """ api = UniApi(settings.UNI_GET_PHONE_USER_TOKEN) phoneResponse = api.run("getApiKey", {"phone": telegram_update.phone}) phoneResponse = json.loads(phoneResponse) if "error" in phoneResponse.keys(): error = "Во время выполнения запроса произошла ошибка: {}" \ "\r\nУстановите API ключ с помощью команды:" \ "\r\n/setApiKye {}".format(phoneResponse['error'], '{ApiKey}') error += "" error += "" raise CmdException(error) user.phone = telegram_update.phone user.uni_api_key = phoneResponse['result']['api_key'] user.save() bot.sendMessage(telegram_update.chat_id, 'API ключ установлен')
def process_updates(self, update): """ Find acceptable command and run :param update: dict :return: void """ try: update = TelegramUpdate(update) cmd_factory = CommandFactory() user = self.fetch_or_create_user(update) cmd = cmd_factory.create_cmd(update, user) if cmd is not None: cmd.run(self.telegram_bot, update, user) return raise CmdException('Команда не найдена') except CmdException as e: self.telegram_bot.sendMessage(update.chat_id, e.args[0]) except Exception: log = logging.getLogger("bot_log") log.exception('Error on run command') self.telegram_bot.sendMessage( update.chat_id, "Во время выполнения запроса произошла ошибка") return
def prepare_telegram_response(self, response): """ Prepare user-readable response :param response: string :return: string """ response = json.loads(response) if "error" in response.keys(): raise CmdException(response['error']) results = response['result'] if len(results) == 0: return 'Кампании за данный промежуток времени не найдены' for result in results: response = "\r\nId: {}" \ "\r\nSubject: {}" \ "\r\nStatus: {}" \ "\r\nShow statistic: /campaignStats_{}" \ "\r\n----------".format( result["id"], result["subject"], result["status"], result["id"] ) return response
def fetch_campaign_id(self, text_cmd): """ Fetch campaign id from command string :param text_cmd: string :return: int """ args = super(CampaignStats, self).parse_arguments(text_cmd) if len(args) < 1: raise CmdException("Ошибка! Не указан id кампании") try: campaign_id = int(args[0]) if campaign_id <= 0: raise CmdException("Ошибка! Id кампании должно быть целым положительным числом") except ValueError: raise CmdException("Ошибка! Id кампании должно быть целым положительным числом") return campaign_id
def fetch_params(self, text_cmd): """ Fetch listId and email from command string :param text_cmd: string :return: dict """ args = super(Subscribe, self).parse_arguments(text_cmd) if len(args) < 2: raise CmdException("Ошибка! Не указан Id списка или имейл") try: list_id = int(args[0]) if list_id <= 0: raise CmdException("Ошибка! Id списка должно быть целым положительным числом") except ValueError: raise CmdException("Ошибка! Id списка должно быть целым положительным числом") return {"list_ids": args[0], "fields[email]": args[1]}
def fetch_api_key(self, text_cmd): """ Fetch API key from command string :param text_cmd: string :return: string """ args = super(SetApiKey, self).parse_arguments(text_cmd) if len(args) < 1: raise CmdException("Ошибка! API ключ является обазязательным аргументом") return args[0]
def run_api_query(self, cmd_name, params, user): """ Run query to UniSender API :param cmd_name: string :param params: dict :param user: TeleUser :return: string """ if not user.uni_api_key: raise CmdException( "Set api key first! Use \"/setApiKey {apiKey}\"") api = UniApi(user.uni_api_key) response = api.run(cmd_name, params) self.log_request_response(user, cmd_name, response) return response
def prepare_telegram_response(self, response): """ Prepare user-readable response :param response: string :return: string """ response = json.loads(response) if "error" in response.keys(): raise CmdException(response['error']) results = response['result'] if len(results) == 0: return 'Списки не найдены' text_response = "" for result in results: text_response += "\r\nId: {}, Title: {}" \ "\r\n----------".format(result["id"], result["title"]) text_response += "\r\nИспользуйте /subscribe {listId} {email} для добавления email-адреса в список" return text_response