def create_session(chat: Chat) -> Session: active_session = get_active_session(chat) if active_session is not None: raise BotBackendLogicException("Chat already has active session.") active_session = Session(chat=chat) active_session.save() return active_session
def on_inline_query(query: tg.InlineQuery): telegram_user_id = query.from_user.id query_id = query.id query = query.query if len(query) == 0: txt = t('bot.inline.switch_pm_text') bot.answer_inline_query(query_id, [], switch_pm_text=txt, switch_pm_parameter='start') return try: session = Session.get_by_query_token(query) except: bot.answer_inline_query(query_id, [], switch_pm_text=t('bot.inline.switch_pm_text'), switch_pm_parameter='start') return if session is None or session.chat.telegram_id != telegram_user_id: bot.answer_inline_query(query_id, [], switch_pm_text=t('bot.inline.switch_pm_text'), switch_pm_parameter='start') return photo = tg.InlineQueryResultCachedPhoto( '%s - %s' % (str(session.id), str(query_id)), session.telegram_photo_file_id) bot.answer_inline_query(query_id, results=[photo])
def webhook_update(self, chat_id): logger.info("Webhook update, chat id {}.".format(chat_id)) if request.method == 'HEAD': return "OK" try: session = Session.get(Session.chat_id == chat_id) except Session.DoesNotExist: logger.error("No session was found for chat_id {}.".format(chat_id)) abort(404, 'No session with that chat id is found') data = request.json if not data: logger.error("No json was found in update of chat_id {}.".format(chat_id)) abort(400, 'Request must contain json data') try: id_model = data["model"]["id"] except (KeyError, TypeError): logger.error("No .model.id field was found in update of chat_id {}.".format(chat_id)) abort(400, '.model.id field is required') for h in session.hooks: if h.board_id == id_model: hook = h break else: # Trello will automatically delete the webhook, # when they recieve status 410. # Source: https://developers.trello.com/apis/webhooks logger.error("No webhook was found for update of chat_id {}.".format(chat_id)) abort(410, 'Such hook does not exist') trello_session = self.app.session(session.trello_token) try: action = trello.Action.from_dict(trello_session, data['action']) except (KeyError, TypeError) as e: logger.error( "Could not parse action json in update for chat_id {}: {}.".format( chat_id, repr(e))) abort(400, '.action object is invalid') try: msg = self._action_to_msg(action) except RuntimeError: return "OK" queue = self.get_message_queue(chat_id, action.board) queue.enqueue(msg) return "OK"
from bot import settings from bot.models import Session, User from datetime import datetime from pyproj import Geod import csv import os import os.path import requests session = Session() def edit_json_api(): """Функция получающая JSON информацию с API, и возвращающая требуюмую информацию в нормальном виде для рабты представленных функций бота""" result = requests.get(settings.ROCKET_LAUNCH_API).json()['result'] launch_info = [] for item in result: name_mission = item['name'] provider = item['provider']['name'] vehicle = item['vehicle']['name'] location = item['pad']['location']['name'] start_time = item['win_open'] if start_time is not None: start_time = datetime.strptime(start_time, '%Y-%m-%dT%H:%MZ') else: start_time = 'Неизвестно'
def set_session_combined_photo_file_id(session: Session, file_id: str): session.telegram_photo_file_id = file_id session.save()
def set_session_telegram_message_id(session: Session, telegram_message_id: int, sent_at: datetime): session.control_telegram_message_id = telegram_message_id session.control_telegram_message_sent_at = timezone.make_aware(sent_at) session.save()
def change_output_mode(session: Session, output_mode: str): session.output_mode = output_mode session.save()
def change_mode(session: Session, mode: str): session.mode = mode session.save()
def finish_session(session: Session): if session.state == Session.States.FINISHED: raise BotBackendLogicException("Session is already finished.") session.state = Session.States.FINISHED session.photo_set_finished_at = now() session.save()
def cancel_session(session: Session): if session.state == Session.States.CANCELED: raise BotBackendLogicException("Session is already canceled.") session.state = Session.States.CANCELED session.canceled_at = now() session.save()
def get_session_by_id(session_id: int) -> Session: return Session.get_by_id(session_id)
def get_active_session(chat: Chat) -> Optional[Session]: return Session.get_last_started_session(chat)
def chat_has_active_session(chat: Chat) -> bool: active_session = Session.get_last_started_session(chat) return active_session is not None
def update_session_query_token(session: Session): session.query_token = str(uuid.uuid4()) session.save()