def test_on_login_with_a_non_existing_user(
):  #MISS THE OTHER CASES OF SEVERAL LOGIN CASES (if the interaction with USERS goes right)
    email_telegram.create_bot(mock=True)
    updater = Updater(email_telegram.token, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', email_telegram.on_start))
    updater.start_polling()

    user = telegram.User(id=1, first_name='test', is_bot=False)
    chat = telegram.Chat(1, 'group')
    message = telegram.Message(404, user, None, chat, text="/start henlo")
    update = telegram.Update(1, message=message)
    result = email_telegram.on_start(update, None)

    #mock on_login
    context = email_telegram.MockContext(['Admin'])
    message = telegram.Message(406, user, None, chat, text="/login test")
    update = telegram.Update(1, message=message)

    email_telegram.on_login = Mock(return_value={
        'username': '******',
        'chat_id': 123
    })
    result = email_telegram.on_login(update, context)
    updater.stop()
    '''
Exemplo n.º 2
0
def test_mock_bot(app, client, database, auth):
    user = telegram.User(id=1, first_name="test", is_bot=False)
    chat = telegram.Chat(45, "group")
    message = telegram.Message(404, user, None, chat, text="/start henlo")
    update = telegram.Update(1, message=message)
    result = telebot.on_start(update, None)
    assert result.text == 'Please use /login <username> to receive stories from your followed users'

    reply = client.post('/bot/register',
                        data={
                            'username': '******',
                            'chat_id': 42
                        })
    assert reply.status_code == 200

    context = MockContext([])
    # Testing login without parameters
    message = telegram.Message(405, user, None, chat, text="/login")
    update = telegram.Update(1, message=message)
    result = telebot.on_login(update, context)
    assert result.text == 'Use the command /login <username>'

    auth.login('Admin', 'admin')
    # Testing login with a non existing user
    context = MockContext(['Admin'])
    message = telegram.Message(406, user, None, chat, text="/login test")
    update = telegram.Update(1, message=message)
    result = telebot.on_login(update, context)
    # assert result.text == 'No user is registered with this username'

    # Testing login with a existing user
    context.args = ['Admin']
    message = telegram.Message(407, user, None, chat, text="/login")
    update = telegram.Update(1, message=message)
    result = telebot.on_login(update, context)
Exemplo n.º 3
0
    def test_effective_attachment(self):
        for i in ('audio', 'game', 'document', 'photo', 'sticker', 'video',
                  'voice', 'video_note', 'contact', 'location', 'venue',
                  'invoice', 'invoice', 'successful_payment'):
            dummy = object()
            kwargs = {i: dummy}
            msg = telegram.Message(1, telegram.User(1, ""), None, None,
                                   **kwargs)
            self.assertIs(msg.effective_attachment, dummy,
                          'invalid {} effective attachment'.format(i))

        msg = telegram.Message(1, telegram.User(1, ""), None, None)
        self.assertIsNone(msg.effective_attachment)
Exemplo n.º 4
0
def task_send_telegram_message(story_text, follower_telegram_chat_id, username,
                               user_id):
    try:
        str(username)
    except ValueError:
        return errors.response('094')
    try:
        int(user_id)
    except ValueError:
        return errors.response('093')

    # start messaging with the bot
    email_telegram.create_bot(mock=True)
    updater = Updater(email_telegram.token, use_context=True)
    dp = updater.dispatcher

    # Add functions to the dispatcher to be handled.
    dp.add_handler(CommandHandler('start', email_telegram.on_start))
    dp.add_handler(CommandHandler('login', email_telegram.on_login))
    dp.add_handler(CommandHandler('send',
                                  email_telegram.send_telegram_message))
    updater.start_polling()

    user = telegram.User(id=user_id, first_name=username, is_bot=False)
    chat = telegram.Chat(1, 'group')

    message = telegram.Message(407, user, None, chat, text='/start')
    update = telegram.Update(1, message=message)
    result = email_telegram.on_start(update, None)

    if result.text == 'Please use /login <username> to receive stories from your followed users':  #proceed with the login

        context = email_telegram.MockContext(['Admin'])
        message = telegram.Message(405, user, None, chat, text="/login")
        update = telegram.Update(1, message=message)
        result = email_telegram.on_login(update, context)

        if ((result == 'Use the command /login <username>')
                or (result == 'Server is currently not reachable')
                or (result == 'No user is registered with this username')):

            updater.stop(
            )  #otherwise telegram checks entering in a loop to messages to be sent
        else:  #if (result == 'You will now receive updates about followed users')
            for elem in follower_telegram_chat_id:
                result = email_telegram.send_telegram_message(story_text, elem)
            updater.stop()
    else:
        updater.stop()
    return result
Exemplo n.º 5
0
 def test_text_markdown_emoji(self):
     text = (b'\\U0001f469\\u200d\\U0001f469\\u200d ABC').decode('unicode-escape')
     expected = (b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*').decode('unicode-escape')
     bold_entity = telegram.MessageEntity(type=telegram.MessageEntity.BOLD, offset=7, length=3)
     message = telegram.Message(
         message_id=1, from_user=None, date=None, chat=None, text=text, entities=[bold_entity])
     self.assertEquals(expected, message.text_markdown)
Exemplo n.º 6
0
 def test_parse_entity(self):
     text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
             b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
     entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=13, length=17)
     message = telegram.Message(
         message_id=1, from_user=None, date=None, chat=None, text=text, entities=[entity])
     self.assertEqual(message.parse_entity(entity), 'http://google.com')
Exemplo n.º 7
0
def _create_update_mock(chat_id: int = -12345678,
                        chat_type: str = "private",
                        message_id: int = 12345678,
                        user_id: int = 12345678,
                        username: str = "myusername") -> Update:
    """
    Helper method to create an "Update" object with mocked content
    """
    import telegram

    update = lambda: None  # type: Update

    user = telegram.User(id=user_id,
                         username=username,
                         first_name="Max",
                         is_bot=False)

    chat = telegram.Chat(id=chat_id, type=chat_type)
    date = datetime.datetime.now()

    update.effective_chat = chat
    update.effective_message = telegram.Message(
        message_id=message_id,
        from_user=user,
        chat=chat,
        date=date,
    )

    return update
def user_reply():
    from bot_firestore_user import User
    from bot_telegram_dialogue import repeat_state
    import telegram
    user_id = request.form.get('id')
    user_reply = request.form.get('reply')
    logging.debug('ENDOPOINT: user_reply id={} reply={}'.format(
        user_id, user_reply))
    if user_id and user_reply:
        if user_id.startswith('web_') and len(user_id) > 4:
            application, serial_id = user_id.split('_')
            u = User.get_user(application, serial_id)
            if u is None:
                error_msg = 'user does not exist'
                return jsonify({'success': False, 'error': error_msg}), 400
            message_obj = telegram.Message(message_id=-1,
                                           from_user=None,
                                           date=None,
                                           chat=None,
                                           text=user_reply)
            repeat_state(u, message_obj=message_obj)
            return jsonify({'success': True, 'error': None}), 200
        else:
            error_msg = 'id must conform to string pattern <web_serial>'
            return jsonify({'success': False, 'error': error_msg}), 400
    else:
        error_msg = 'Both id and reply params need to be specified'
        return jsonify({'success': False, 'error': error_msg}), 400
Exemplo n.º 9
0
 def fake_message(self, text, bot, **params):
     msg = tg.Message(next_id(),
                      chat=tg.Chat(next_id(), 'chat'),
                      text=text,
                      date=datetime.datetime.utcnow(),
                      bot=bot,
                      **params)
     return msg
Exemplo n.º 10
0
 def simpleMessage(self, message: Optional[str] = None, cb_reply=dummyCb):
     msg = telegram.Message(get_id(),
                            from_user=self.user1,
                            date=datetime.datetime.now(),
                            chat=self.chat,
                            text=message,
                            reply_to_message=cb_reply)
     update = telegram.Update(get_id(), message=msg)
     return update
Exemplo n.º 11
0
def process_schedule(bot: telegram.Bot, job: Job):
    logging.debug('Processing schedules')
    update = telegram.Update(-1,
                             message=telegram.Message(
                                 -1, -1, datetime.datetime.now(),
                                 telegram.Chat(settings.DEFAULT_CHANNEL,
                                               'group')))
    for messages in scheduler.process_schedule_now(bot):
        process_message(bot, messages, update)
Exemplo n.º 12
0
def test_ensure_daily_book(g_bot: GDGAjuBot, telebot: MockTeleBot):
    # given
    chat_id = 1234
    telebot.get_chat.return_value = telegram.Chat(chat_id, type="group")
    state = g_bot.states["daily_book"][chat_id]

    # when
    g_bot.ensure_daily_book()

    # then
    g_bot.updater.job_queue.run_once.assert_called_once_with(ANY, when=60)
    job_callback = g_bot.updater.job_queue.run_once.call_args[0][0]
    assert isinstance(job_callback, Callable)
    assert state["__memory__"]["first_call"] is True
    assert isinstance(state["__memory__"]["schedule_fn"], Callable)

    # given
    message = telegram.Message(0, g_bot.get_me(), datetime.now(),
                               telebot.get_chat.return_value)

    # when
    g_bot.ensure_daily_book(message, as_job=False)

    # then
    assert state["messages_since"] == 1

    # when
    g_bot.ensure_daily_book(message, as_job=True)

    # then
    last_time = state["last_time"].astimezone().timestamp()
    expected = datetime.utcnow().astimezone().timestamp()
    assert last_time == approx(expected, rel=0.1)

    # given
    g_bot.updater.job_queue.run_once.reset_mock()

    # when
    g_bot.ensure_daily_book(message, as_job=True)

    # then
    g_bot.updater.job_queue.run_once.assert_called_once_with(ANY, when=ANY)
    seconds = g_bot.updater.job_queue.run_once.call_args[1]["when"]
    assert seconds // 3600 in range(3, 12 + 1)

    # given
    state["last_time"] -= timedelta(hours=3)
    state["messages_since"] += 300

    # when
    g_bot.ensure_daily_book(message, as_job=True)

    # then
    telebot.send_message.assert_any_call(chat_id,
                                         Contains(" Mensagem automática do "),
                                         parse_mode="Markdown")
Exemplo n.º 13
0
    def test_equality(self):
        _id = 1
        a = telegram.Message(_id, telegram.User(1, ""), None, None)
        b = telegram.Message(_id, telegram.User(1, ""), None, None)
        c = telegram.Message(_id, telegram.User(0, ""), None, None)
        d = telegram.Message(0, telegram.User(1, ""), None, None)
        e = telegram.Update(_id)

        self.assertEqual(a, b)
        self.assertEqual(hash(a), hash(b))
        self.assertIsNot(a, b)

        self.assertEqual(a, c)
        self.assertEqual(hash(a), hash(c))

        self.assertNotEqual(a, d)
        self.assertNotEqual(hash(a), hash(d))

        self.assertNotEqual(a, e)
        self.assertNotEqual(hash(a), hash(e))
Exemplo n.º 14
0
def execute(filename: str, bot: telegram.bot.Bot) -> Iterable[Dict]:
    logging.info(f'Starting schedule for: {filename}')
    chat = telegram.Chat(-1, 'private')
    message = telegram.Message(-1, {
        'first_name': 'robot',
        'last_name': None
    }, datetime.datetime.now(), chat)
    update = telegram.Update(-1, message=message)
    result = tbs.docparse.run_command(
        bot, update, f"{bot.first_name} {filename.split('.')[0]}", -1)
    return result
Exemplo n.º 15
0
def create_telegram_update(message_text):
    """ Helper function: create an "Update" to simulate a message sent to the
        Telegram bot.
    """
    from datetime import datetime
    message = telegram.Message(message_id=0,
                               from_user=telegram.User(0, 'greenkey'),
                               date=datetime.now(),
                               chat=telegram.Chat(0, ''),
                               text=message_text)

    return telegram.Update(update_id=0, message=message)
Exemplo n.º 16
0
 def test_parse_entities_url_emoji(self):
     url = b'http://github.com/?unicode=\\u2713\\U0001f469'.decode('unicode-escape')
     text = 'some url'
     link_entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=0, length=8, url=url)
     message = telegram.Message(
         message_id=1,
         from_user=None,
         date=None,
         chat=None,
         text=text,
         entities=[link_entity])
     self.assertDictEqual(message.parse_entities(), {link_entity: text})
     self.assertEqual(next(iter(message.parse_entities())).url, url)
def test_on_login_without_parameters():
    email_telegram.create_bot(mock=True)
    updater = Updater(email_telegram.token, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', email_telegram.on_start))
    updater.start_polling()

    user = telegram.User(id=1, first_name='test', is_bot=False)
    chat = telegram.Chat(1, 'group')
    message = telegram.Message(404, user, None, chat, text="/start henlo")
    update = telegram.Update(1, message=message)
    result = email_telegram.on_start(update, None)
    if result.text == 'Please use /login <username> to receive stories from your followed users':
        context = email_telegram.MockContext([])
        message = telegram.Message(405, user, None, chat, text="/login")
        update = telegram.Update(1, message=message)

        email_telegram.on_login = Mock(return_value={})
        result = email_telegram.on_login(update, context)

        updater.stop()

        assert result == {}
    updater.stop()
Exemplo n.º 18
0
def simpleMessage(bot,
                  name: str,
                  user: telegram.User,
                  chat: telegram.Chat,
                  cb_reply=None,
                  message: Optional[str] = None) -> telegram.Update:
    msg = telegram.Message(get_id(),
                           from_user=user,
                           date=datetime.datetime.now(),
                           chat=chat,
                           text=name,
                           reply_to_message=cb_reply,
                           bot=bot)
    update = telegram.Update(get_id(), message=msg)
    update.message.reply_text = cb_reply
    return update
Exemplo n.º 19
0
def test_log_message(resources: "Resources"):
    with orm.db_session:
        assert Message.get(id=1) is None

    msg = telegram.Message(
        message_id=1,
        chat=telegram.Chat(id=1, type="comics"),
        from_user=telegram.User(
            id=1938, is_bot=False, first_name="Kal-El", username="******"
        ),
        text="I’m here to fight for truth and justice.",
        date=datetime.datetime.utcnow(),
    )

    resources.log_message(msg)

    with orm.db_session:
        assert Message[1].text == msg.text
Exemplo n.º 20
0
def test_log_message_creates_user_if_not_exists(resources: "Resources"):
    with orm.db_session:
        assert User.get(telegram_id=9000) is None

    msg = telegram.Message(
        message_id=1,
        chat=telegram.Chat(id=2001, type="space"),
        from_user=telegram.User(
            id=9000, is_bot=True, first_name="HALL 9000", username="******"
        ),
        text="I am afraid I can't do that Dave.",
        date=datetime.datetime.utcnow(),
    )

    resources.log_message(msg)

    with orm.db_session:
        assert User[9000].telegram_username == "@hal9k"
Exemplo n.º 21
0
    def test_call_telegram_return_no_updates_for_user(self, telegram_api,
                                                      *args, **kwargs):
        token = 'abc'
        username = '******'
        config = {'token': token, 'accept_from': [username]}
        inst = MagicMock(name='telegram.Bot()')
        telegram_api.Bot = MagicMock(name='telegram', return_value=inst)

        username = '******'
        user = telegram.User(id=1, first_name='', username=username)
        chat = telegram.Chat(1, 'private', username=username)
        date = datetime.datetime(2016, 12, 18, 0, 0)
        message = telegram.Message(1, user, date=date, chat=chat)
        update = telegram.update.Update(update_id=1, message=message)

        inst.get_updates.return_value = [update]

        ret = telegram_bot_msg.beacon(config)

        telegram_api.Bot.assert_called_once_with(token)
        self.assertEqual(ret, [])
Exemplo n.º 22
0
    def test_call_telegram_returning_updates(self):
        with patch("salt.beacons.telegram_bot_msg.telegram") as telegram_api:
            token = 'abc'
            username = '******'
            config = {'token': token, 'accept_from': [username]}
            inst = MagicMock(name='telegram.Bot()')
            telegram_api.Bot = MagicMock(name='telegram', return_value=inst)

            user = telegram.User(id=1, first_name='', username=username)
            chat = telegram.Chat(1, 'private', username=username)
            date = datetime.datetime(2016, 12, 18, 0, 0)
            message = telegram.Message(1, user, date=date, chat=chat)
            update = telegram.update.Update(update_id=1, message=message)

            inst.get_updates.return_value = [update]

            ret = telegram_bot_msg.beacon(config)

            telegram_api.Bot.assert_called_once_with(token)
            self.assertTrue(ret)
            self.assertEqual(ret[0]['msgs'][0], message.to_dict())
Exemplo n.º 23
0
    def test_call_telegram_returning_updates(self):
        with patch("salt.beacons.telegram_bot_msg.telegram") as telegram_api:
            token = "abc"
            username = "******"
            config = [{"token": token, "accept_from": [username]}]
            inst = MagicMock(name="telegram.Bot()")
            telegram_api.Bot = MagicMock(name="telegram", return_value=inst)

            user = telegram.User(id=1, first_name="", username=username)
            chat = telegram.Chat(1, "private", username=username)
            date = datetime.datetime(2016, 12, 18, 0, 0)
            message = telegram.Message(1, user, date=date, chat=chat)
            update = telegram.update.Update(update_id=1, message=message)

            inst.get_updates.return_value = [update]

            ret = telegram_bot_msg.beacon(config)
            self.assertEqual(ret, (True, "Valid beacon configuration"))

            telegram_api.Bot.assert_called_once_with(token)
            self.assertTrue(ret)
            self.assertEqual(ret[0]["msgs"][0], message.to_dict())
Exemplo n.º 24
0
    def setUp(self):
        self.test_entities = [
            {
                'length': 4,
                'offset': 10,
                'type': 'bold'
            },
            {
                'length': 7,
                'offset': 16,
                'type': 'italic'
            },
            {
                'length': 4,
                'offset': 25,
                'type': 'code'
            },
            {
                'length': 5,
                'offset': 31,
                'type': 'text_link',
                'url': 'http://github.com/'
            },
            {
                'length': 3,
                'offset': 41,
                'type': 'pre'
            },
        ]

        self.test_text = 'Test for <bold, ita_lic, code, links and pre.'
        self.test_message = telegram.Message(
            message_id=1,
            from_user=None,
            date=None,
            chat=None,
            text=self.test_text,
            entities=[telegram.MessageEntity(**e) for e in self.test_entities])
Exemplo n.º 25
0
    feedback_text = ["👍", "👎", "🤮"]
    feedback_answer = ["赞了一把", "踩了一脚", "吐了一地"]

    feedback.feedbacks = dict(zip(feedback_text, feedback_answer))

    # 为了测试,关闭反馈和反馈提示
    feedback.show_alert = False
    feedback.show_answer = False

    # 用feedbacks初始化buttons
    bs = feedback.init_buttons()
    print("初始化buttons:")
    __show_buttons__(bs)

    #
    now = date.today()
    chat = telegram.Chat(1, 'group')

    replay_markup = InlineKeyboardMarkup([bs])
    msg = telegram.Message(1, 1, now, chat, reply_markup=replay_markup)
    callback = telegram.CallbackQuery(1, 1, 1, message=msg, data="👎:0")
    bs = feedback.get_updatebuttons(callback)
    print("callback一次")
    __show_buttons__(bs)

    replay_markup = InlineKeyboardMarkup([bs])
    msg = telegram.Message(1, 1, now, chat, reply_markup=replay_markup)
    callback = telegram.CallbackQuery(1, 1, 1, message=msg, data="👎:1")
    bs = feedback.get_updatebuttons(callback)
    print("callback两次")
    __show_buttons__(bs)
Exemplo n.º 26
0
                            first_name='Harry',
                            last_name='Potter',
                            username='******')

# User chat, private conversation.
SAMPLE_CHAT = SAMPLE_USER

SAMPLE_DATE = datetime.date(2015, 9, 4)

# TEXT

SAMPLE_TEXT = 'Alohomora'

SAMPLE_TEXT_MESSAGE = telegram.Message(message_id=1,
                                       from_user=SAMPLE_USER,
                                       date=SAMPLE_DATE,
                                       chat=SAMPLE_CHAT,
                                       text=SAMPLE_TEXT)

SAMPLE_TEXT_UPDATE = telegram.Update(update_id=1, message=SAMPLE_TEXT_MESSAGE)

# STICKER

SAMPLE_STICKER_PHOTOSIZE = telegram.PhotoSize(file_id='photosize_id',
                                              width=10,
                                              height=10,
                                              file_size=100)

SAMPLE_STICKER = telegram.Sticker(file_id='sticker_id',
                                  width=100,
                                  height=100,