示例#1
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)
示例#2
0
    def test_claim(self, mock_set_webhook, mock_get_me):
        url = reverse('channels.types.telegram.claim')

        self.login(self.admin)

        # check that claim page URL appears on claim list page
        response = self.client.get(reverse('channels.channel_claim'))
        self.assertContains(response, url)

        # can fetch the claim page
        response = self.client.get(url)
        self.assertContains(response, "Connect Telegram")

        # claim with an invalid token
        mock_get_me.side_effect = telegram.TelegramError('Boom')
        response = self.client.post(url, {'auth_token': 'invalid'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            'Your authentication token is invalid, please check and try again',
            response.context['form'].errors['auth_token'][0])

        user = telegram.User(123, 'Rapid', True)
        user.last_name = 'Bot'
        user.username = '******'

        mock_get_me.side_effect = None
        mock_get_me.return_value = user
        mock_set_webhook.return_value = ''

        response = self.client.post(
            url,
            {'auth_token': '184875172:BAEKbsOKAL23CXufXG4ksNV7Dq7e_1qi3j8'})
        channel = Channel.objects.get(address="rapidbot")
        self.assertEqual(channel.channel_type, 'TG')
        self.assertEqual(
            channel.config, {
                'auth_token': '184875172:BAEKbsOKAL23CXufXG4ksNV7Dq7e_1qi3j8',
                'callback_domain': channel.callback_domain
            })

        self.assertRedirect(
            response, reverse('channels.channel_read', args=[channel.uuid]))
        self.assertEqual(302, response.status_code)

        response = self.client.post(
            url,
            {'auth_token': '184875172:BAEKbsOKAL23CXufXG4ksNV7Dq7e_1qi3j8'})
        self.assertEqual(
            'A telegram channel for this bot already exists on your account.',
            response.context['form'].errors['auth_token'][0])

        contact = self.create_contact('Telegram User',
                                      urn=URN.from_telegram('1234'))

        # make sure we our telegram channel satisfies as a send channel
        response = self.client.get(
            reverse('contacts.contact_read', args=[contact.uuid]))
        send_channel = response.context['send_channel']
        self.assertIsNotNone(send_channel)
        self.assertEqual(send_channel.channel_type, 'TG')
示例#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)
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()
    '''
示例#5
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
示例#6
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,
     )
示例#7
0
    def test_claim(self, mock_set_webhook, mock_get_me):
        url = reverse("channels.types.telegram.claim")

        self.login(self.admin)

        # check that claim page URL appears on claim list page
        response = self.client.get(reverse("channels.channel_claim"))
        self.assertContains(response, url)

        # can fetch the claim page
        response = self.client.get(url)
        self.assertContains(response, "Connect Telegram")

        # claim with an invalid token
        mock_get_me.side_effect = telegram.TelegramError("Boom")
        response = self.client.post(url, {"auth_token": "invalid"})
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            "Your authentication token is invalid, please check and try again",
            response.context["form"].errors["auth_token"][0],
        )

        user = telegram.User(123, "Rapid", True)
        user.last_name = "Bot"
        user.username = "******"

        mock_get_me.side_effect = None
        mock_get_me.return_value = user
        mock_set_webhook.return_value = ""

        response = self.client.post(url, {"auth_token": "184875172:BAEKbsOKAL23CXufXG4ksNV7Dq7e_1qi3j8"})
        channel = Channel.objects.get(address="rapidbot")
        self.assertEqual(channel.channel_type, "TG")
        self.assertEqual(
            channel.config,
            {
                "auth_token": "184875172:BAEKbsOKAL23CXufXG4ksNV7Dq7e_1qi3j8",
                "callback_domain": channel.callback_domain,
            },
        )

        self.assertRedirect(response, reverse("channels.channel_read", args=[channel.uuid]))
        self.assertEqual(302, response.status_code)

        response = self.client.post(url, {"auth_token": "184875172:BAEKbsOKAL23CXufXG4ksNV7Dq7e_1qi3j8"})
        self.assertEqual(
            "A telegram channel for this bot already exists on your account.",
            response.context["form"].errors["auth_token"][0],
        )

        contact = self.create_contact("Telegram User", urn=URN.from_telegram("1234"))

        # make sure we our telegram channel satisfies as a send channel
        response = self.client.get(reverse("contacts.contact_read", args=[contact.uuid]))
        send_channel = response.context["send_channel"]
        self.assertIsNotNone(send_channel)
        self.assertEqual(send_channel.channel_type, "TG")
示例#8
0
    def test_equality(self):
        a = telegram.User(self._id, self.first_name, self.last_name)
        b = telegram.User(self._id, self.first_name, self.last_name)
        c = telegram.User(self._id, self.first_name)
        d = telegram.User(0, self.first_name, self.last_name)
        e = telegram.Update(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))
示例#9
0
    def test_equality(self):
        a = telegram.InlineQuery(self._id, telegram.User(1, ""), "", "")
        b = telegram.InlineQuery(self._id, telegram.User(1, ""), "", "")
        c = telegram.InlineQuery(self._id, telegram.User(0, ""), "", "")
        d = telegram.InlineQuery(0, telegram.User(1, ""), "", "")
        e = telegram.Update(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))
    def test_equality(self):
        a = telegram.ChatMember(telegram.User(1, ""),
                                telegram.ChatMember.ADMINISTRATOR)
        b = telegram.ChatMember(telegram.User(1, ""),
                                telegram.ChatMember.ADMINISTRATOR)
        d = telegram.ChatMember(telegram.User(2, ""),
                                telegram.ChatMember.ADMINISTRATOR)
        d2 = telegram.ChatMember(telegram.User(1, ""),
                                 telegram.ChatMember.CREATOR)

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

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

        self.assertNotEqual(a, d2)
        self.assertNotEqual(hash(a), hash(d2))
    def setUp(self):
        self.result_id = 'result id'
        self.from_user = telegram.User(1, 'First name', None, 'Last name',
                                       'username')
        self.measureBot = MeasureBot(
            "301568247:BBF1GUx2f5Hq7h3drBupUZV-RLzP806jsKo"
        )  # NON-EXISTING TOKEN

        self.measureBot.getUserUpdateText = MagicMock(name='getUserUpdateText')
        self.measureBot.replyToUserUpdate = MagicMock(name='replyToUserUpdate')
        self.measureBot.replyToUserUpdate.return_value = None
示例#12
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))
示例#13
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)
示例#14
0
    def setUp(self):
        user = telegram.User(1, 'First name')

        self.result_id = 'result id'
        self.from_user = user
        self.query = 'query text'

        self.json_dict = {
            'result_id': self.result_id,
            'from': self.from_user.to_dict(),
            'query': self.query
        }
    def setUp(self):
        self._id = 5
        self.invoice_payload = 'invoice_payload'
        self.from_user = telegram.User(0, '')
        self.shipping_address = telegram.ShippingAddress(
            'GB', '', 'London', '12 Grimmauld Place', '', 'WC1')

        self.json_dict = {
            'id': self._id,
            'invoice_payload': self.invoice_payload,
            'from': self.from_user.to_dict(),
            'shipping_address': self.shipping_address.to_dict()
        }
示例#16
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
示例#17
0
    def setUp(self):
        user = telegram.User(1, 'First name')

        self.id = 'id'
        self.from_user = user
        self.query = 'query text'
        self.offset = 'offset'

        self.json_dict = {
            'id': self.id,
            'from': self.from_user.to_dict(),
            'query': self.query,
            'offset': self.offset
        }
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'
示例#19
0
    def setUp(self):
        user = telegram.User(1, 'First name')
        location = telegram.Location(8.8, 53.1)

        self.id = 'id'
        self.from_user = user
        self.query = 'query text'
        self.offset = 'offset'
        self.location = location

        self.json_dict = {
            'id': self.id,
            'from': self.from_user.to_dict(),
            'query': self.query,
            'offset': self.offset,
            'location': self.location.to_dict()
        }
示例#20
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'
示例#21
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
示例#22
0
    def setUp(self):
        self._id = 5
        self.invoice_payload = 'invoice_payload'
        self.shipping_option_id = 'shipping_option_id'
        self.currency = 'EUR'
        self.total_amount = 100
        self.from_user = telegram.User(0, '')
        self.order_info = telegram.OrderInfo()

        self.json_dict = {
            'id': self._id,
            'invoice_payload': self.invoice_payload,
            'shipping_option_id': self.shipping_option_id,
            'currency': self.currency,
            'total_amount': self.total_amount,
            'from': self.from_user.to_dict(),
            'order_info': self.order_info.to_dict()
        }
示例#23
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"
示例#24
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))
示例#25
0
    def test_equality(self):
        a = telegram.Update(self.update_id, message=self.message)
        b = telegram.Update(self.update_id, message=self.message)
        c = telegram.Update(self.update_id)
        d = telegram.Update(0, message=self.message)
        e = telegram.User(self.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))
示例#26
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')
示例#27
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())
    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, [])
示例#29
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())
示例#30
0
def start(bot, update):
	update.message.reply_text("Hi, Bugs are bugging you? Fret not, I'm here to help!")

	user = telegram.User(id=562767140, first_name="", is_bot=False)
	user.send_message("Hey There!")