def init(): """ Creates tables if they do not exists """ if not Chat.table_exists(): Chat.create_table() if not Metrika.table_exists(): Metrika.create_table() if not Metrika_tokens.table_exists(): Metrika_tokens.create_table() if not Users.table_exists(): Users.create_table() if not Github_repositories.table_exists(): Github_repositories.create_table() data = { 'url': TELEGRAM_CALLBACK_URL } if not CConfig.CERTIFICATE: query = 'https://api.telegram.org/bot%s/setWebhook?%s' % (CConfig.API_TOKEN, urlencode(data)) result = requests.get(query) else: query = 'https://api.telegram.org/bot%s/setWebhook?%s' % (CConfig.API_TOKEN, urlencode(data))
def callback(): """ GET oauth token from Yandex Metrika API """ code = request.args.get('code', '') chat_id = request.args.get('state', '') access_token = '' msg = '' if code and chat_id: try: s = requests.post('https://oauth.yandex.ru/token', data={'code': code, 'grant_type': 'authorization_code'}, headers={'Content-type': 'application/x-www-form-urlencoded'}, auth=(CConfig.MODULES['metrika']['ID'], CConfig.MODULES['metrika']['PASS'])) access_token = s.json()['access_token'] metrikaAPI = MetrikaAPI(access_token, '', chat_id) new_token = Metrika_tokens.create(app_id=CConfig.MODULES['metrika']['ID'], chat_id=chat_id, token=access_token) new_token.save() Handler.start(chat_id) except Exception as e: print(e) return "Error: %s" % e return msg
def delete(self, chat_id, token_id, counter_id): try: token = Metrika_tokens.get(Metrika_tokens.id == token_id) try: counter = Metrika.select().where((Metrika.counter_id == counter_id) & (Metrika.chat_id == chat_id)).get() counter.delete_instance() counter_name = CConfig.CACHE['metrika_%s_%s' % (token_id, counter_id)] send_to_chat("Готово! Сайт <%s> отключен от модуля." % counter_name, chat_id) except Metrika.DoesNotExist: send_to_chat("Сайт не найден.", chat_id) except Metrika_tokens.DoesNotExist: send_to_chat("Ошибка токена <%s>." % token_id, chat_id)
def start(chat_id): # TODO: change tokens multi. try: token = Metrika_tokens.select().order_by(Metrika_tokens.id.desc()).where(Metrika_tokens.chat_id == chat_id).get() buttons = Handler.get_counters(token, "start") send_object_to_chat("Теперь выберите сайт, статистику которого хотите получать.\n", json.dumps({ 'inline_keyboard': buttons }), chat_id) except Metrika_tokens.DoesNotExist: send_to_chat("Для подключения счетчика, вам нужно авторизовать бота. " \ "Для этого, пройдите по ссылке и подтвердите доступ к счетчику. \n\n" \ "https://oauth.yandex.ru/authorize?response_type=code&client_id=%s&state=%s\n" % (CConfig.MODULES['metrika']['ID'], chat_id), chat_id) return
def add(self, chat_id, token_id, counter_id): # TODO: Params as hash id in cache try: token = Metrika_tokens.get(Metrika_tokens.id == token_id) try: counter = Metrika.select().where((Metrika.counter_id == counter_id) & (Metrika.chat_id == chat_id)).get() send_to_chat("Счетчик <%s> уже прикреплен к данному чату." % counter.counter_name, chat_id) except Metrika.DoesNotExist: counter_name = CConfig.CACHE['metrika_%s_%s' % (token_id, counter_id)] metrika = Metrika.create(oauth_token=token.token, counter_id=counter_id, chat_id=chat_id, counter_name=counter_name, client_id=CConfig.MODULES['metrika']['ID']) metrika.save() send_to_chat("Готово! Сайт <%s> успешно подключен." % counter_name, chat_id) except Metrika_tokens.DoesNotExist: send_to_chat("Ошибка токена <%s>." % token_id, chat_id)
def metrika_stop(self, chat_id): try: token = Metrika_tokens.get(Metrika_tokens.chat_id == chat_id) counters = Metrika.select().where(Metrika.chat_id == chat_id) if len(counters): buttons = [] buttons_row = [] for counter in counters: buttons_row.append( {'text': counter.counter_name, 'callback_data': "/metrika_%s%s#%s" % ("stop", token.id, counter.counter_id)}) CConfig.CACHE['metrika_%s_%s' % (token.id, counter.counter_id)] = counter.counter_name if len(buttons_row) == 2: buttons.append(buttons_row[:]) buttons_row = [] if len(buttons_row): buttons.append(buttons_row[:]) send_object_to_chat("Выберите сайт, который хотите отключить.\n", json.dumps({ 'inline_keyboard': buttons }), chat_id) else: send_to_chat("Подключенных счетчиков не найдено.", chat_id) except Metrika_tokens.DoesNotExist: send_to_chat("Токен не найден.", chat_id)