예제 #1
0
    def test_update_caption(self):
        bot = EvernoteBot(self.config)
        message = Message(message_id=1,
                          date=1,
                          from_user={
                              'id': 2,
                              'is_bot': False,
                              'first_name': 'John'
                          },
                          forward_from={
                              'id': 3,
                              'is_bot': False,
                              'first_name': 'Jack',
                              'username': '******'
                          })
        message.caption = bot.get_caption(message)
        self.assertEqual(message.caption, 'Forwarded from Jack jack11')

        message = Message(message_id=1,
                          date=1,
                          from_user={
                              'id': 2,
                              'is_bot': False,
                              'first_name': 'John'
                          },
                          forward_from_chat={
                              'id': 3,
                              'title': 'Testchat',
                              'type': 'channel',
                              'username': '******'
                          })
        message.caption = bot.get_caption(message)
        self.assertEqual(message.caption, 'Forwarded from channel Testchat')
예제 #2
0
class EvernoteBotApplication(WsgiApplication):
    def __init__(self):
        config = load_config()
        self.config = config
        super().__init__(
            src_root=realpath(dirname(__file__)),
            urls=self.get_urls(),
            config=config
        )
        self.bot = EvernoteBot(config)
        atexit.register(self.shutdown)

    def get_urls(self):
        telegram_api_token = self.config['telegram']['token']
        return (
            ('POST', f'^/{telegram_api_token}$', telegram_hook),
            ('GET', r'^/evernote/oauth$', evernote_oauth),
        )

    def set_telegram_webhook(self, webhook_url):
        try:
            self.bot.api.setWebhook(webhook_url)
        except Exception:
            message = f"Can't set up webhook url `{webhook_url}`"
            logging.getLogger('evernotebot').fatal(message, exc_info=True)

    def shutdown(self):
        self.bot.stop()
예제 #3
0
 def __init__(self):
     config = load_config()
     self.config = config
     super().__init__(
         src_root=realpath(dirname(__file__)),
         urls=self.get_urls(),
         config=config
     )
     self.bot = EvernoteBot(config)
     atexit.register(self.shutdown)
예제 #4
0
 def test_evernote_quota(self):
     bot = EvernoteBot(self.config)
     bot.api = mock.Mock()
     bot.api.getFile = mock.Mock(
         return_value="https://google.com/robots.txt")
     bot.users = mock.Mock()
     bot.users.get = mock.Mock(return_value=self.default_user_data)
     bot.evernote = mock.Mock()
     now = datetime.datetime.now()
     bot.evernote().get_quota_info = mock.Mock(return_value={
         "remaining": 99,
         "reset_date": now
     })
     bot.save_note = mock.Mock()
     message = Message(
         message_id=1,
         date=1,
         document={
             "file_id": 123,
             "file_size": 100
         },
         from_user={
             "id": 2,
             "is_bot": False,
             "first_name": "John"
         },
         caption="My document",
     )
     with self.assertRaises(EvernoteBotException) as ctx:
         bot.on_document(message)
     self.assertTrue(
         str(ctx.exception).startswith("Your evernote quota is out"))
예제 #5
0
 def test_help(self):
     bot = EvernoteBot(self.config)
     bot.api = Mock()
     bot.api.sendMessage = Mock()
     message = Message(message_id=1,
                       date=1,
                       chat={
                           "id": 1,
                           "type": "private"
                       })
     help_command(bot, message)
     bot.api.sendMessage.assert_called_once()
예제 #6
0
 def test_switch_notebook(self):
     message = Message(message_id=1,
                       date=1,
                       from_user={
                           "id": 2,
                           "is_bot": False,
                           "first_name": "John"
                       })
     bot = EvernoteBot(bot_config)
     user_data = {
         "id": 2,
         "created": 123,
         "last_request_ts": 123,
         "bot_mode": "multiple_notes",
         "telegram": {
             "first_name": "Bob",
             "last_name": None,
             "username": None,
             "chat_id": 1,
         },
         "evernote": {
             "access": {
                 "token": "access_token",
                 "permission": "basic"
             },
             "notebook": {
                 "name": "xxx",
                 "guid": "xxx"
             }
         },
     }
     bot.users = Mock()
     bot.users.get = Mock(return_value=user_data)
     bot.evernote = Mock()
     bot.evernote.get_all_notebooks = Mock(return_value=[{
         "name": "xxx",
         "guid": "xxx"
     }])
     bot.api = Mock()
     bot.api.sendMessage = Mock()
     bot.users.save = Mock()
     switch_notebook_command(bot, message)
     bot.users.get.assert_called_once_with(2)
     bot.evernote.get_all_notebooks.assert_called_once_with("access_token")
     bot.api.sendMessage.assert_called_once_with(
         1, "Please, select notebook",
         '{"keyboard": [[{"text": "> xxx <"}]], "resize_keyboard": true, "one_time_keyboard": true}'
     )
     bot.users.save.assert_called_once()
     save_data = bot.users.save.call_args[0][0]
     self.assertEqual(save_data["state"], "switch_notebook")
예제 #7
0
 def test_get_evernote_api_object(self, sdk):
     bot = EvernoteBot(bot_config)
     api = bot.evernote()
     self.assertIsNotNone(api)
     self.assertTrue("default" in bot._evernote_apis_cache)
     bot_user = BotUser(**self.default_user_data)
     api = bot.evernote(bot_user)
     self.assertIsNotNone(api)
     self.assertEqual(len(bot._evernote_apis_cache), 2)
     self.assertTrue(bot_user.id in bot._evernote_apis_cache)
     for i in range(110):
         self.default_user_data["id"] = i
         bot_user = BotUser(**self.default_user_data)
         api = bot.evernote(bot_user)
         self.assertIsNotNone(api)
     self.assertEqual(len(bot._evernote_apis_cache), 100)
     self.assertFalse("default" in bot._evernote_apis_cache)
     self.assertFalse(1 in bot._evernote_apis_cache)
예제 #8
0
 def test_location(self):
     bot = EvernoteBot(bot_config)
     bot.users = mock.Mock()
     bot.users.get = mock.Mock(return_value=self.default_user_data)
     bot.save_note = mock.Mock()
     message = Message(
         message_id=1,
         date=1,
         from_user={"id": 2, "is_bot": False, "first_name": "John"},
         location = {"longitude": 1.2, "latitude": 3.4},
         venue = {
             "location": {"longitude": 1.2, "latitude": 3.4},
             "title": "Kremlin",
             "address": "Red Square, 1",
             "foursquare_id": "123",
         }
     )
     bot.on_location(message)
     bot.save_note.assert_called_once()
     user = bot.save_note.call_args[0][0]
     self.assertIsInstance(user, BotUser)
     title = bot.save_note.call_args[1]["title"]
     html = bot.save_note.call_args[1]["html"]
     self.assertEqual(title, "Kremlin")
     self.assertEqual(html, "Kremlin<br />Red Square, 1<br />"
     "<a href='https://maps.google.com/maps?q=3.4,1.2'>"
         "https://maps.google.com/maps?q=3.4,1.2"
     "</a><br />"
     "<a href='https://foursquare.com/v/123'>https://foursquare.com/v/123</a>")
 def create_request(self, data):
     bot = EvernoteBot(self.config)
     app = namedtuple("App", ["bot"])(bot=bot)
     bytes_data = json.dumps(data).encode()
     wsgi_input = tempfile.NamedTemporaryFile(mode="rb+", suffix=".txt",
                                              dir="/tmp")
     wsgi_input.write(bytes_data)
     wsgi_input.seek(0, 0)
     self._files.append(wsgi_input)
     request = Request({
         'wsgi.input': wsgi_input,
         'CONTENT_LENGTH': len(bytes_data),
         'QUERY_STRING': urlencode(data),
     })
     request.app = app
     return request
예제 #10
0
 def setUp(self):
     bot = EvernoteBot(self.config)
     bot.api = TelegramApiMock()
     bot.evernote = EvernoteApiMock()
     message = Message(
         message_id=1,
         date=time(),
         from_user={"id": 6, "is_bot": False, "first_name": "test"},
         chat={"id": 1, "type": "private"}
     )
     start_command(bot, message)
     oauth_data =  bot.evernote._oauth_data
     evernote_oauth_callback(bot, OauthParams(oauth_data["callback_key"], "oauth_verifier", "basic"))
     # creating new mocks because we want get a clean picture
     bot.api = TelegramApiMock()
     bot.evernote = EvernoteApiMock()
     self.bot = bot
예제 #11
0
 def test_start(self):
     user_id = 5
     update_data = {
         "update_id": 1,
         "message": {
             "message_id":
             1,
             "date":
             123,
             "text":
             '/start',
             "entities": [{
                 "type": "bot_command",
                 "offset": 0,
                 "length": len("/start"),
             }],
             "from_user": {
                 "id": user_id,
                 "is_bot": False,
                 "first_name": "test",
             },
             "chat": {
                 "id": 9,
                 "type": ""
             },
         },
     }
     bot = EvernoteBot(self.config)
     bot.api = TelegramApiMock()
     bot.evernote = EvernoteApiMock()
     bot.process_update(update_data)
     user_data = bot.users.get(user_id)
     self.assertIsNotNone(user_data)
     self.assertEqual(user_data["id"], 5)
     self.assertEqual(user_data["evernote"]["oauth"]["token"], "token")
     self.assertEqual(bot.api.sendMessage.call_count, 1)
     self.assertEqual(bot.api.editMessageReplyMarkup.call_count, 1)
     self.assertEqual(bot.evernote.get_oauth_data.call_count, 1)
예제 #12
0
    def test_switch_mode(self):
        bot_user = BotUser(**self.default_user_data)
        bot = EvernoteBot(self.config)
        with self.assertRaises(EvernoteBotException) as ctx:
            bot.switch_mode(bot_user, "invalid")
        self.assertEqual(str(ctx.exception), "Unknown mode 'invalid'")

        bot.api = mock.Mock()
        bot.api.sendMessage = mock.Mock()
        bot.switch_mode(bot_user, "multiple_notes")
        bot.api.sendMessage.assert_called_once_with(
            1, "The bot already in 'multiple_notes' mode.",
            "{\"hide_keyboard\": true}")

        bot.switch_mode_one_note = mock.Mock()
        bot.switch_mode(bot_user, "one_note")
        bot.switch_mode_one_note.assert_called_once()

        bot_user.bot_mode = "one_note"
        bot_user.evernote.shared_note_id = 123
        bot.api.sendMessage = mock.Mock()
        bot.switch_mode(bot_user, "multiple_notes")
        bot.api.sendMessage.assert_called_once_with(
            1, "The bot has switched to 'multiple_notes' mode.",
            "{\"hide_keyboard\": true}")
        self.assertIsNone(bot_user.evernote.shared_note_id)
        self.assertEqual(bot_user.bot_mode, "multiple_notes")
예제 #13
0
 def test_switch_notebook(self):
     bot_user = BotUser(**self.default_user_data)
     bot = EvernoteBot(self.config)
     bot.api = mock.Mock()
     bot.api.sendMessage = mock.Mock()
     bot.evernote = mock.Mock()
     all_notebooks = [
         {
             "guid": "xxx",
             "name": "xxx"
         },
         {
             "guid": "zzz",
             "name": "zzz"
         },
     ]
     bot.evernote().get_all_notebooks = lambda query: list(
         filter(lambda nb: nb["name"] == query["name"], all_notebooks))
     with self.assertRaises(EvernoteBotException) as ctx:
         bot.switch_notebook(bot_user, "> www <")
     self.assertEqual(str(ctx.exception), "Notebook 'www' not found")
     bot.switch_notebook(bot_user, "zzz")
     self.assertEqual(bot_user.evernote.notebook.name, "zzz")
     self.assertEqual(bot_user.evernote.notebook.guid, "zzz")
     bot.api.sendMessage.assert_called_once()
     bot.switch_notebook(bot_user, "xxx")
     self.assertEqual(bot_user.evernote.notebook.guid, "xxx")
     bot.switch_notebook(bot_user, "xxx")
     self.assertEqual(bot_user.evernote.notebook.guid, "xxx")
예제 #14
0
 def test_audio(self):
     bot = EvernoteBot(self.config)
     bot.api = mock.Mock()
     bot.api.getFile = mock.Mock(
         return_value="https://google.com/robots.txt")
     bot.users = mock.Mock()
     bot.users.get = mock.Mock(return_value=self.default_user_data)
     bot.evernote = mock.Mock()
     bot.evernote().get_quota_info = mock.Mock(
         return_value={"remaining": 100})
     bot.save_note = mock.Mock()
     message = Message(
         message_id=1,
         date=1,
         voice={
             "file_id": 123,
             "file_unique_id": 123,
             "file_size": 100,
             "duration": 5
         },
         from_user={
             "id": 2,
             "is_bot": False,
             "first_name": "John"
         },
         caption="My voice",
     )
     bot.on_voice(message)
     bot.api.getFile.assert_called_once()
     bot.evernote().get_quota_info.assert_called_once()
     bot.save_note.assert_called_once()
 def setUp(self):
     bot = EvernoteBot(self.config)
     bot.api = TelegramApiMock()
     self.bot = bot
예제 #16
0
import logging
import traceback
from os.path import dirname, realpath

from uhttp import WsgiApplication

from evernotebot.config import load_config
from evernotebot.bot.core import EvernoteBot
from evernotebot.web.urls import urls

config = load_config()
src_root = realpath(dirname(__file__))
app = WsgiApplication(src_root, config=config, urls=urls)
app.bot = EvernoteBot(config)

webhook_url = config["telegram"]["webhook_url"]
try:
    app.bot.api.setWebhook(webhook_url)
except Exception:
    e = traceback.format_exc()
    message = f"Can't set up webhook url `{webhook_url}`.\n{e}"
    logging.getLogger('evernotebot').fatal({"exception": message})