コード例 #1
0
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()
    '''
コード例 #2
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
コード例 #3
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)
コード例 #4
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
コード例 #5
0
 def __init__(self, text):
     super().__init__(
         chat=telegram.Chat(id=1, type='private'),
         message_id=1,
         from_user=telegram.User(id=1, first_name='Test', is_bot=False),
         date=1,
         text=text,
     )
コード例 #6
0
 def send_message(self, chat_id, message):
     logging.info('Sending a message to chat ' + str(chat_id))
     try:
         telegram.Chat(
             id=chat_id,
             type='private', bot=telegram.Bot(self.token)).send_message(
                 text=message)  # was I high when I wrote this? TODO: fix
     except telegram.error.Unauthorized:
         logging.warning('Bot was blocked by the user?')
コード例 #7
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)
コード例 #8
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")
コード例 #9
0
    def test_equality(self):
        a = telegram.Chat(self._id, self.title, self.type)
        b = telegram.Chat(self._id, self.title, self.type)
        c = telegram.Chat(self._id, "", "")
        d = telegram.Chat(0, self.title, self.type)
        e = telegram.User(self._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))
コード例 #10
0
ファイル: scheduler.py プロジェクト: marceloslacerda/tbs
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
コード例 #11
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)
コード例 #12
0
ファイル: tasks.py プロジェクト: OrnelaDanushi/email-telegram
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
コード例 #13
0
def test_on_start():
    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)

    updater.stop()
    assert result.text == 'Please use /login <username> to receive stories from your followed users'
コード例 #14
0
 def setUp(self):
     self._db_connection = DbConnection(in_memory=True)
     self.bot = ValeVistaBot(self._db_connection)
     self.queue = queue.Queue()
     self.dispatcher = MockDispatcher(self.bot, self.queue)
     self.user1 = telegram.User(id=get_id(),
                                first_name='john',
                                username='******',
                                is_bot=False)
     self.chat = telegram.Chat(get_id(),
                               type='private',
                               username='******',
                               first_name='john')
     self.bot.add_handlers(self.dispatcher)
     self.pass_test = True
     self.rut = Rut.build_rut('2343234-k')
     self.rut_non_std_str = '2343.234-k'
コード例 #15
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
コード例 #16
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"
コード例 #17
0
 def setUp(self):
     self._db_connection = DbConnection(in_memory=True)
     self.retriever = web_test.WebPageFromFileRetriever()
     self.bot = ValeVistaBot(self._db_connection, self.retriever)
     self.queue = queue.Queue()
     self.dispatcher = MockDispatcher(self.bot, self.queue)
     self.user1_telegram_id = get_id()
     self.user1 = telegram.User(id=self.user1_telegram_id,
                                first_name='john',
                                username='******',
                                is_bot=False)
     self.chat_id = get_id()
     self.chat = telegram.Chat(self.chat_id,
                               type='private',
                               username='******',
                               first_name='john')
     self.bot.add_handlers(self.dispatcher)
     self.pass_test = True
     self.rut = Rut.build_rut('2343234-k')
     self.rut2 = Rut.build_rut('12444333-4')
コード例 #18
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, [])
コード例 #19
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())
コード例 #20
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())
コード例 #21
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)