Exemplo n.º 1
0
async def test_process_text(text_update):
    update = json.loads(text_update)
    User.create(id=425606,
                telegram_chat_id=2,
                mode='one_note',
                evernote_access_token='token',
                current_notebook={
                    'guid': '000',
                    'name': 'test_notebook'
                },
                places={'000': 'note_guid'})
    TelegramUpdate.create(user_id=425606,
                          request_type='text',
                          status_message_id=5,
                          message=update['message'])
    dealer = EvernoteDealer()
    mock_note_provider = AsyncMock()
    note = Types.Note()
    mock_note_provider.get_note = AsyncMock(return_value=note)
    mock_telegram_api = AsyncMock()
    dealer._telegram_api = mock_telegram_api
    for k, handlers in dealer._EvernoteDealer__handlers.items():
        for handler in handlers:
            handler._note_provider = mock_note_provider
    updates = dealer.fetch_updates()
    for user_id, update_list in updates.items():
        user = User.get({'id': user_id})
        await dealer.process_user_updates(user, update_list)

    assert mock_note_provider.get_note.call_count == 1
    assert dealer._EvernoteDealer__handlers['text'][
        0]._note_provider.update_note.call_count == 1
Exemplo n.º 2
0
async def test_process_photo_in_one_note_mode():
    User.create(id=1,
                telegram_chat_id=2,
                mode='one_note',
                evernote_access_token='token',
                current_notebook={
                    'guid': '000',
                    'name': 'test_notebook'
                },
                places={'000': 'note_guid'})
    TelegramUpdate.create(user_id=1,
                          request_type='photo',
                          status_message_id=5,
                          message={
                              'date':
                              123123,
                              'chat': {
                                  'id': 1,
                                  'type': 'private'
                              },
                              'message_id':
                              10,
                              'photo': [
                                  {
                                      'height': 200,
                                      'width': 200,
                                      'file_id': 'xBcZ1dW',
                                      'file_size': 100,
                                  },
                              ],
                              'from': {
                                  'id': 1
                              },
                          })
    dealer = EvernoteDealer()
    mock_note_provider = AsyncMock()
    note = Types.Note()
    mock_note_provider.get_note = AsyncMock(return_value=note)
    mock_note_provider.save_note = AsyncMock(return_value=Types.Note())
    mock_note_provider.get_note_link = AsyncMock(
        return_value='http://evernote.com/some/stuff/here/')
    mock_telegram_api = AsyncMock()
    file_path = "/tmp/xBcZ1dW.txt"
    if exists(file_path):
        os.unlink(file_path)
    with open(file_path, 'w') as f:
        f.write('test data')

    dealer._telegram_api = mock_telegram_api
    for k, handlers in dealer._EvernoteDealer__handlers.items():
        for handler in handlers:
            handler._note_provider = mock_note_provider
            handler.get_downloaded_file = AsyncMock(
                return_value=(file_path, 'text/plain'))

    updates = dealer.fetch_updates()
    for user_id, update_list in updates.items():
        user = User.get({'id': user_id})
        await dealer.process_user_updates(user, update_list)
Exemplo n.º 3
0
 def send_home_options(self, user: User):
     user.send(
         Message(content="What do you want to do?",
                 quick_replies=[
                     QuickReply("Pay", ExecuteFunction(self.prompt_pay)),
                     QuickReply("Get balance",
                                ExecuteFunction(self.send_balance)),
                     QuickReply("Something else", SetState("Advanced"))
                 ]))
async def test_notebook_command(testbot: EvernoteBot, text_update: str):
    update = TelegramUpdate(json.loads(text_update))
    notebook_cmd = NotebookCommand(testbot)
    user = User.create(id=update.message.user.id,
                       telegram_chat_id=update.message.chat.id,
                       evernote_access_token='',
                       current_notebook={ 'guid': 1 })
    await notebook_cmd.execute(update.message)
    await asyncio.sleep(0.0001)

    user = User.get({'id': user.id})
    assert user.state == 'select_notebook'
    assert testbot.api.sendMessage.call_count == 1
    assert testbot.update_notebooks_cache.call_count == 1
async def test_switch_mode_command(testbot: EvernoteBot, text_update):
    update = text_update
    switch_mode_cmd = SwitchModeCommand(testbot)
    user = User.create(id=update.message.user.id,
                       telegram_chat_id=update.message.chat.id,
                       mode='one_note')
    await switch_mode_cmd.execute(update.message)
    await asyncio.sleep(0.0001)
    user = User.get({'id': user.id})
    assert user.state == 'switch_mode'
    assert testbot.api.sendMessage.call_count == 1
    args = testbot.api.sendMessage.call_args[0]
    assert len(args) == 4
    assert args[0] == user.telegram_chat_id
    assert 'Please, select mode' == args[1]
Exemplo n.º 6
0
    async def execute(self, message: Message):
        self.bot.track(message)
        user = User.get({'id': message.user.id})
        notebooks = await self.bot.list_notebooks(user)

        buttons = []
        for notebook in notebooks:
            if notebook['guid'] == user.current_notebook['guid']:
                name = "> %s <" % notebook['name']
            else:
                name = notebook['name']
            buttons.append({'text': name})

        markup = json.dumps({
            'keyboard': [[b] for b in buttons],
            'resize_keyboard': True,
            'one_time_keyboard': True,
        })
        asyncio.ensure_future(
            self.bot.api.sendMessage(user.telegram_chat_id,
                                     'Please, select notebook',
                                     reply_markup=markup))
        user.state = 'select_notebook'
        user.save()
        asyncio.ensure_future(self.bot.update_notebooks_cache(user))
async def test_notebook_command(testbot: EvernoteBot, user, text_update):
    update = text_update
    notebook_cmd = SwitchNotebookCommand(testbot)
    await notebook_cmd.execute(update.message)
    await asyncio.sleep(0.0001)
    user = User.get({'id': user.id})
    assert user.state == 'select_notebook'
    assert testbot.api.sendMessage.call_count == 1
    args = testbot.api.sendMessage.call_args[0]
    assert args[0] == user.telegram_chat_id
    assert args[1] == 'Please, select notebook'
async def test_help_command(testbot: EvernoteBot, text_update: str):
    update = TelegramUpdate(json.loads(text_update))
    help_cmd = HelpCommand(testbot)
    user = User.create(id=1, telegram_chat_id=update.message.chat.id)
    await help_cmd.execute(update.message)
    await asyncio.sleep(0.0001)

    assert testbot.api.sendMessage.call_count == 1
    args = testbot.api.sendMessage.call_args[0]
    assert len(args) == 2
    assert args[0] == user.telegram_chat_id
    assert 'This is bot for Evernote' in args[1]
Exemplo n.º 9
0
def user():
    note_guid = generate_string(32)
    notebook_guid = generate_string(32)
    user = User.create(id=random.randint(1, 100),
                       name=generate_string(5),
                       username=generate_string(5),
                       telegram_chat_id=random.randint(1, 100),
                       mode='one_note',
                       evernote_access_token='token',
                       current_notebook={
                           'guid': notebook_guid,
                           'name': 'test_notebook'
                       },
                       places={notebook_guid: note_guid})
    return user
Exemplo n.º 10
0
    async def _update_note(self, user: User, update: TelegramUpdate):
        notebook_guid = user.current_notebook['guid']
        note_guid = user.places.get(notebook_guid)
        if not note_guid:
            raise Exception('There are no default note in notebook {0}'.format(user.current_notebook['name']))
        try:
            note = await self._note_provider.get_note(user.evernote_access_token, note_guid)
        except NoteNotFound:
            self.logger.warning("Note {0} not found. Creating new note".format(note_guid))
            note = await self._create_note(user, update)
            user.places[notebook_guid] = note.guid
            user.save()

        content = NoteContent(note)
        if update.has_file():
            new_note = await self._create_note(user, update)
            note_link = await self._note_provider.get_note_link(user.evernote_access_token, new_note)
            content.add_text('{0}: <a href="{1}">{1}</a>'.format(update.request_type.capitalize(), note_link))
        else:
            message = Message(update.message)
            await self.update_content(content, message)
        note.resources = content.get_resources()
        note.content = str(content)
        await self._note_provider.update_note(user.evernote_access_token, note)
    def getUsers(self):
        try:
            with open('bot/userDict.json', 'r') as userFile:
                usersJson = userFile.read()
            userFile.close()

            usersList = json.loads(usersJson)
        except:
            with open('bot/userDict.json', 'w') as userFile:
                userFile.close()
            usersList = []

        users = []
        for user in usersList:
            chatID = user.get('chatID')
            currentUser = usr.User(chatID)

            currentUser.name = user.get('name')
            currentUser.expectedMessageType = user.get('expectedMsgType')
            if user.get('tempParams') is not None:
                currentUser.tempParams = user.get('tempParams')
            if user.get('wantsMenu') is not None:
                currentUser.wantsMenu = user.get('wantsMenu')
            currentUser.course = user.get('course')
            if user.get('wantsLecturePlan') is not None:
                currentUser.wantsLecturePlan = user.get('wantsLecturePlan')
            currentUser.address = user.get('address')
            if user.get('wantsTransportInfo') is not None:
                currentUser.wantsTransportInfo = user.get('wantsTransportInfo')
            if user.get('wantsToRateMeals') is not None:
                currentUser.wantsToRateMeals = user.get('wantsToRateMeals')
            if user.get('pushTimes') is not None:
                currentUser.pushTimes = user.get('pushTimes')
            if user.get('pauseAllNotifications') is not None:
                currentUser.pauseAllNotifications = user.get(
                    'pauseAllNotifications')

            users.append(currentUser)

        return users
def getUser(sql_row):
	"""
	Converts a row retrieved from SQL to a user object
	@param sql_row: The row retrieved from SQL
	@return: The user object
	"""
	userID = sql_row[0]
	chatID = sql_row[1]
	name = sql_row[2]
	expectedMsgType = sql_row[3]
	tempParams = ast.literal_eval(sql_row[4])
	wantsMenu = sql_row[5] == 1
	course = sql_row[6]
	wantsLecturePlan = sql_row[7] == 1
	address = sql_row[8]
	wantsTransportInfo = sql_row[9] == 1
	wantsToRateMeals = sql_row[10] == 1
	menuPushTime = str(sql_row[11])[0:5]
	menuPushTime = menuPushTime if menuPushTime[len(menuPushTime) - 1] != ':' else ('0' + menuPushTime)[0:5]
	lecturePushTime = str(sql_row[12])[0:5]
	pauseAllNotifications = sql_row[13] == 1
	wantsExamWarning = sql_row[14] == 1

	user = usr.User(chatID)
	user.userID = userID
	user.name = name
	user.expectedMessageType = expectedMsgType
	user.tempParams = tempParams
	user.wantsMenu = wantsMenu
	user.course = course
	user.wantsLecturePlan = wantsLecturePlan
	user.address = address
	user.wantsTransportInfo = wantsTransportInfo
	user.wantsToRateMeals = wantsToRateMeals
	user.pushTimes['menu'] = menuPushTime
	user.pushTimes['lecture'] = lecturePushTime
	user.pauseAllNotifications = pauseAllNotifications
	user.wantsExamWarning = wantsExamWarning

	return user
Exemplo n.º 13
0
    async def execute(self, message: Message):
        self.bot.track(message)
        user = User.get({'id': message.user.id})
        buttons = []
        for mode in ['one_note', 'multiple_notes']:
            if user.mode == mode:
                name = "> %s <" % mode.capitalize().replace('_', ' ')
            else:
                name = mode.capitalize().replace('_', ' ')
            buttons.append({'text': name})

        markup = json.dumps({
            'keyboard': [[b] for b in buttons],
            'resize_keyboard': True,
            'one_time_keyboard': True,
        })
        asyncio.ensure_future(
            self.bot.api.sendMessage(user.telegram_chat_id,
                                     'Please, select mode',
                                     reply_markup=markup))
        user.state = 'switch_mode'
        user.save()
Exemplo n.º 14
0
    def __init__(self, bot, chat_id, text, message_id, user_firstname=''):
        # Get user object from SQL
        conn = sqlhandler.getConnection()
        cur = conn.cursor()
        select_user_query = """SELECT userID, chatID, name, expectedMsgType, tempParams, wantsMenu, course, 
		wantsLecturePlan, address, wantsTransportInfo, wantsToRateMeals, menuPushTime, lecturePushTime, 
		pauseAllNotifications, wantsExamWarning FROM users WHERE chatID = %s """
        cur.execute(select_user_query, (chat_id, ))
        userSqlRow = cur.fetchall()
        conn.commit()
        user = usr.User(chat_id)
        newUser = False
        if cur.rowcount == 1:
            user = sqlconverter.getUser(userSqlRow[0])
        elif cur.rowcount > 1:
            logging.warning('More than one user with chatID %s found!',
                            chat_id)
            user = sqlconverter.getUser(userSqlRow[0])
        else:
            logging.info('Creating new user for chatID %s.', chat_id)
            newUser = True
        cur.close()

        # Write firstName from telegram into user object
        user.telegram_firstName = user_firstname

        # Process message
        try:
            message = msg.Message(user, text, message_id)

            if '🥃' in message.text:
                bot.sendMessage(message.user.chatID,
                                'WHISKEEEEEYYYYYY!!! 🥃🥃🥃')

            if message.isCommand:
                cmd.Command(message, bot, conn).findCommand()
            else:
                cmd.Command(message, bot, conn).interpretMessage()
        except:
            e = sys.exc_info()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            stack = traceback.extract_tb(exc_traceback)
            logging.warning(
                "An error occured handling the following message: %s. Error: %s, Stacktrace: %s",
                text, e, stack)
            bot.sendMessage(
                chat_id,
                "An error occured while trying to fulfill your request. If this keeps happening,"
                +
                " please file a bug report via /reportbug, create an issue on GitHub under"
                +
                " https://github.com/Mueller-Patrick/dhbw_service_bot or send a message to @P4ddy_m"
            )
            bot.sendMessage(os.environ['PATRICK_TELEGRAM_ID'], (
                "The bot encountered an error.\nSender: {}\nMessage received: {}\nError: {}\nStack: {}"
                .format(user_firstname, text, e, stack)))

        # Save user object to SQL
        cur = conn.cursor()
        if newUser:
            print("new")
            insert_user_query = """INSERT INTO users (chatID, name, telegram_firstName, expectedMsgType, tempParams, wantsMenu, course, 
			wantsLecturePlan, address, wantsTransportInfo, wantsToRateMeals, menuPushTime, lecturePushTime, 
			pauseAllNotifications, lastMessage, wantsExamWarning) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, now(), %s) """
            cur.execute(insert_user_query,
                        sqlconverter.getUserInsertTuple(user))
        else:
            print("Update")
            update_user_query = """UPDATE users SET name = %s, telegram_firstName = %s, expectedMsgType = %s, tempParams = %s, wantsMenu = %s, 
			course = %s, wantsLecturePlan = %s, address = %s, wantsTransportInfo = %s, wantsToRateMeals = %s, 
			menuPushTime = %s, lecturePushTime = %s, pauseAllNotifications = %s, lastMessage = now(), wantsExamWarning = %s WHERE userID = %s """
            cur.execute(update_user_query,
                        sqlconverter.getUserUpdateTuple(user))

        conn.commit()
        cur.close()
        conn.close()