def start_command(bot, message: Message): user_id = message.from_user.id user_data = bot.users.get(user_id) if not user_data: current_time = time() telegram_user = message.from_user user_data = { 'id': user_id, 'created': current_time, 'last_request_ts': current_time, 'bot_mode': bot.config.get('default_mode', 'multiple_notes'), 'telegram': { 'first_name': telegram_user.first_name, 'last_name': telegram_user.last_name, 'username': telegram_user.username, 'chat_id': message.chat.id, }, 'evernote': { 'access': { 'permission': 'basic' }, }, } bot.users.create(user_data) user = BotUser(**user_data) message_text = '''Welcome! It's bot for saving your notes to Evernote on fly. Please tap on button below to link your Evernote account with bot.''' user.evernote.oauth = get_evernote_oauth_data(bot, user, message_text) bot.users.save(user.asdict())
def handle_state(self, bot_user: BotUser, message: Message): state = bot_user.state handlers_map = { 'switch_mode': self.switch_mode, # self.switch_mode() 'switch_notebook': self.switch_notebook, # self.switch_notebook() } state_handler = handlers_map[state] state_handler(bot_user, message.text) bot_user.state = None self.users.save(bot_user.asdict())
def handle_state(self, bot_user: BotUser, message: Message): state = bot_user.state handlers_map = { "switch_mode": self.switch_mode, # self.switch_mode() "switch_notebook": self.switch_notebook, # self.switch_notebook() } state_handler = handlers_map.get(state) if not state_handler: raise EvernoteBotException(f"Invalid state: {state}") state_handler(bot_user, message.text) bot_user.state = None self.users.save(bot_user.asdict())
def evernote_oauth_callback(bot, callback_key: str, oauth_verifier: str, access_type: str = "basic"): query = {"evernote.oauth.callback_key": callback_key} user_data = bot.users.get(query, fail_if_not_exists=True) user = BotUser(**user_data) chat_id = user.telegram.chat_id if not oauth_verifier: bot.api.sendMessage( chat_id, "We are sorry, but you have declined " "authorization.") return evernote_config = bot.config["evernote"]["access"][access_type] oauth = user.evernote.oauth try: oauth_params = { "token": oauth.token, "secret": oauth.secret, "verifier": oauth_verifier, } user.evernote.access.token = bot.evernote().get_access_token( evernote_config["key"], evernote_config["secret"], sandbox=bot.config.get("debug", True), **oauth_params) except TokenRequestDenied as e: bot.api.sendMessage( chat_id, "We are sorry, but we have some problems " "with Evernote connection. " "Please try again later.") raise e except Exception as e: bot.api.sendMessage(chat_id, "Unknown error. Please, try again later.") raise e user.evernote.access.permission = access_type user.evernote.oauth = None if access_type == "basic": bot.api.sendMessage( chat_id, "Evernote account is connected.\nFrom now " "you can just send a message and a note will be created.") default_notebook = bot.evernote(user).get_default_notebook() user.evernote.notebook = EvernoteNotebook(**default_notebook) mode = user.bot_mode.replace("_", " ").capitalize() bot.api.sendMessage( chat_id, "Current notebook: " f"{user.evernote.notebook.name}\nCurrent mode: {mode}") else: bot.switch_mode(user, "one_note") bot.users.save(user.asdict())
def test_evernote_oauth_declined_auth(self): callback_key = hashlib.sha1(b"xxx").hexdigest() request = self.create_request({"key": callback_key, "access": "basic"}) bot = request.app.bot bot.api = mock.Mock() bot.api.sendMessage = mock.Mock() bot_user = BotUser(**self.default_user_data) bot_user.evernote.oauth = EvernoteOauthData(token="token", secret="secret", callback_key=callback_key) bot.users.create(bot_user.asdict()) evernote_oauth(request) bot.api.sendMessage.assert_called_once() self.assertEqual(bot.api.sendMessage.call_args[0][1], "We are sorry, but you have declined authorization.")
def evernote_oauth_callback(bot, params: OauthParams): query = {'evernote.oauth.callback_key': params.callback_key} user_data = bot.users.get(query, fail_if_not_exists=True) user = BotUser(**user_data) chat_id = user.telegram.chat_id if not params.verifier: bot.api.sendMessage( chat_id, 'We are sorry, but you have declined ' 'authorization.') return evernote_config = bot.config['evernote']['access'][params.access_type] oauth = user.evernote.oauth try: oauth_params = { 'token': oauth.token, 'secret': oauth.secret, 'verifier': params.verifier, } user.evernote.access.token = bot.evernote().get_access_token( evernote_config['key'], evernote_config['secret'], sandbox=bot.config.get('debug', bot.config['debug']), **oauth_params) except TokenRequestDenied as e: bot.api.sendMessage( chat_id, 'We are sorry, but we have some problems ' 'with Evernote connection. ' 'Please try again later.') raise e except Exception as e: bot.api.sendMessage(chat_id, "Unknown error. Please, try again later.") raise e user.evernote.access.permission = params.access_type user.evernote.oauth = None if params.access_type == "basic": bot.api.sendMessage( chat_id, "Evernote account is connected.\nFrom now " "you can just send a message and a note will be created.") default_notebook = bot.evernote(user).get_default_notebook() user.evernote.notebook = EvernoteNotebook(**default_notebook) mode = user.bot_mode.replace("_", " ").capitalize() bot.api.sendMessage( chat_id, "Current notebook: " f"{user.evernote.notebook.name}\nCurrent mode: {mode}") else: bot.switch_mode(user, "one_note") bot.users.save(user.asdict())
def start_command(bot, message: dict): user_id = message['from']['id'] user_data = bot.users.get(user_id) if not user_data: current_time = time() telegram_user = message['from'] user_data = { 'id': user_id, 'created': current_time, 'last_request_ts': current_time, 'bot_mode': 'multiple_notes', 'telegram': { 'first_name': telegram_user['first_name'], 'last_name': telegram_user['last_name'], 'username': telegram_user['username'], 'chat_id': message['chat']['id'], }, 'evernote': { 'access': {'permission': 'basic'}, }, } bot.users.create(user_data) user = BotUser(**user_data) message_text = '''Welcome! It's bot for saving your notes to Evernote on fly. Please tap on button below to link your Evernote account with bot.''' chat_id = user.telegram.chat_id auth_button = {'text': 'Waiting for Evernote...', 'url': bot.url} inline_keyboard = json.dumps({'inline_keyboard': [[auth_button]]}) status_message = bot.api.sendMessage(chat_id, message_text, inline_keyboard) key = bot.config['evernote']['access']['basic']['key'] secret = bot.config['evernote']['access']['basic']['secret'] oauth_callback = bot.config['oauth_callback'] oauth_data = evernote.get_oauth_data(user.id, key, secret, oauth_callback, sandbox=bot.config.get('debug')) auth_button['text'] = 'Sign in with Evernote' auth_button['url'] = oauth_data['oauth_url'] inline_keyboard = json.dumps({'inline_keyboard': [[auth_button]]}) bot.api.editMessageReplyMarkup(chat_id, status_message['message_id'], inline_keyboard) user.evernote.oauth = EvernoteOauthData( token=oauth_data['oauth_token'], secret=oauth_data['oauth_token_secret'], callback_key=oauth_data['callback_key'] ) bot.users.save(user.asdict())
def switch_mode_command(bot, message: dict): user_id = message['from']['id'] user_data = bot.users.get(user_id) if not user_data: raise TelegramBotError("Unregistered user {0}. You've to send /start to register.") user = BotUser(**user_data) buttons = [] for mode in ('one_note', 'multiple_notes'): title = mode.capitalize().replace('_', ' ') if user.bot_mode == mode: title = f'> {title} <' buttons.append({'text': title}) keyboard = { 'keyboard': [[b] for b in buttons], 'resize_keyboard': True, 'one_time_keyboard': True, } bot.api.sendMessage(user.telegram.chat_id, 'Please, select mode', json.dumps(keyboard)) user.state = 'switch_mode' bot.users.save(user.asdict())
def switch_notebook_command(bot, message: Message): user_id = message.from_user.id user_data = bot.users.get(user_id) user = BotUser(**user_data) all_notebooks = bot.evernote.get_all_notebooks(user.evernote.access.token) buttons = [] for notebook in all_notebooks: name = notebook["name"] if name == user.evernote.notebook.name: name = f"> {name} <" buttons.append({"text": name}) keyboard = { "keyboard": [[b] for b in buttons], "resize_keyboard": True, "one_time_keyboard": True, } bot.api.sendMessage(user.telegram.chat_id, "Please, select notebook", json.dumps(keyboard)) user.state = "switch_notebook" bot.users.save(user.asdict())
def switch_mode_command(bot, message: Message): mode = message.text user_id = message.from_user.id user_data = bot.users.get(user_id) user = BotUser(**user_data) buttons = [] for mode in ('one_note', 'multiple_notes'): title = mode.capitalize().replace('_', ' ') if user.bot_mode == mode: title = f'> {title} <' buttons.append({'text': title}) keyboard = { 'keyboard': [[b] for b in buttons], 'resize_keyboard': True, 'one_time_keyboard': True, } bot.api.sendMessage(user.telegram.chat_id, 'Please, select mode', json.dumps(keyboard)) user.state = 'switch_mode' bot.users.save(user.asdict())
def switch_notebook_command(bot, message: dict): user_id = message['from']['id'] user_data = bot.users.get(user_id) if not user_data: raise TelegramBotError("Unregistered user {0}. You've to send /start to register.") user = BotUser(**user_data) evernote_api = bot.get_evernote_api(user_id) all_notebooks = evernote_api.get_all_notebooks() buttons = [] for notebook in all_notebooks: name = notebook['name'] if name == user.evernote.notebook.name: name = f'> {name} <' buttons.append({'text': name}) keyboard = { 'keyboard': [[b] for b in buttons], 'resize_keyboard': True, 'one_time_keyboard': True, } bot.api.sendMessage(user.telegram.chat_id, 'Please, select notebook', json.dumps(keyboard)) user.state = 'switch_notebook' bot.users.save(user.asdict())