Esempio n. 1
0
    async def test():
        telegram = Telegram(token="token", session=aiohttp.ClientSession())
        telegram.api_messages_lock = asyncio.Lock()

        async def req(method, kwargs):
            requests.append((method, kwargs))

        telegram._request = req

        attachment = Attachment.new(b"file")
        await telegram.execute_send(1, "", attachment, {})

        attachment = Attachment.new(b"file", type="doc")
        await telegram.execute_send(1, "", attachment, {})

        attachment = Attachment.new(b"file", type="voice")
        await telegram.execute_send(1, "", attachment, {})

        assert len(requests) == 3

        assert requests[0] == ("sendPhoto", {"chat_id": "1", "photo": b"file"})
        assert requests[1] == ("sendDocument", {
            "chat_id": '1',
            "document": b'file'
        })
        assert requests[2] == ("sendVoice", {"chat_id": '1', "voice": b'file'})
Esempio n. 2
0
def test_attachments():
    app, debug, hu = make_kutana_no_run()

    pl = Plugin("")

    @pl.on_attachments(["image", "voice"])
    async def _(msg, ctx):
        await ctx.reply(msg.text)

    app.add_plugin(pl)

    image = Attachment("", "image", "", None, "", None, "present")
    voice = Attachment("", "voice", "", None, "", None, "present")
    sticker = Attachment("", "sticker", "", None, "", None, "present")

    hu(Message(None, UpdateType.MSG, "i", (image, ), 1, 0, 0, 0))
    hu(Message(None, UpdateType.MSG, "v", (voice, ), 1, 0, 0, 0))
    hu(Message(None, UpdateType.MSG, "vi", (voice, image), 1, 0, 0, 0))
    hu(Message(None, UpdateType.MSG, "si", (
        sticker,
        image,
    ), 1, 0, 0, 0))
    hu(Message(None, UpdateType.MSG, "s", (sticker, ), 1, 0, 0, 0))

    assert hu(Update(None, UpdateType.UPD)) == hr.SKIPPED

    assert len(debug.answers[1]) == 4
    assert debug.answers[1][0] == ("i", (), {})
    assert debug.answers[1][1] == ("v", (), {})
    assert debug.answers[1][2] == ("vi", (), {})
    assert debug.answers[1][3] == ("si", (), {})
Esempio n. 3
0
    async def test():
        attachment = Attachment.new(b"content")
        image = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert image.type == "image"
        assert image.id is not None
        assert image.file is None

        attachment = Attachment.new(b"content", type="doc")
        doc = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert doc.type == "doc"
        assert doc.id is not None
        assert doc.file is None

        attachment = Attachment.new(b"content", type="voice")
        voice = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert voice.type == "voice"
        assert voice.id is not None
        assert voice.file is None

        attachment = Attachment.new(b"content", type="graffiti")
        voice = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert voice.type == "graffiti"
        assert voice.id == "graffiti87641997_497831521"
        assert voice.file is None

        attachment = Attachment.new(b"content", type="video")
        with pytest.raises(ValueError):
            await vkontakte.upload_attachment(attachment, peer_id=123)
Esempio n. 4
0
    def test_tg_send_message(self):
        mngr = TGManager("token")

        attachment1 = Attachment("photo", 13, None, None, None, None)
        attachment2 = Attachment("doc", 14, None, None, None, None)
        attachment3 = Attachment("document", 15, None, None, None, None)
        attachment4 = TGAttachmentTemp("bad_type", "strange_content", {})

        async def request(self, method, **kwargs):
            return TGResponse(False, (), [method, kwargs])

        mngr.request = types.MethodType(request, mngr)

        res0 = self.loop.run_until_complete(mngr.send_message("hi", None))

        self.assertEqual(len(res0), 0)

        res1 = self.loop.run_until_complete(
            mngr.send_message("hi", 1, [attachment1, attachment4]))

        self.assertEqual(len(res1), 2)

        self.assertEqual(res1[0].response,
                         ["sendMessage", {
                             "chat_id": '1',
                             "text": "hi"
                         }])

        self.assertEqual(res1[1].response,
                         ["sendPhoto", {
                             "chat_id": '1',
                             "photo": "13"
                         }])

        res2 = self.loop.run_until_complete(
            mngr.send_message("", 1, attachment2))

        self.assertEqual(len(res2), 1)

        self.assertEqual(res2[0].response,
                         ["sendDocument", {
                             "chat_id": '1',
                             "document": "14"
                         }])

        res3 = self.loop.run_until_complete(
            mngr.send_message("", 1, attachment3))

        self.assertEqual(len(res3), 1)

        self.assertEqual(res3[0].response,
                         ["sendDocument", {
                             "chat_id": '1',
                             "document": "15"
                         }])

        self.loop.run_until_complete(mngr.dispose())
Esempio n. 5
0
async def __(msg, ctx):
    # Document
    with open(get_path(__file__, "assets/pizza.png"), "rb") as fh:
        doc = Attachment.new(fh.read(), "pizza.png")

    await ctx.reply("Document", attachments=doc)

    # Audio message
    with open(get_path(__file__, "assets/audio.ogg"), "rb") as fh:
        audio_message = Attachment.new(fh.read(), "audio.ogg", "voice")

    await ctx.reply("Audio message", attachments=audio_message)
Esempio n. 6
0
    def test_tg_get_file_from_attachment(self):
        mngr = TGManager("token")

        env = self.loop.run_until_complete(
            mngr.get_environment({"message": {
                "chat": {
                    "id": 1
                }
            }}))

        async def request(_, method, **kwargs):
            self.assertEqual(kwargs["file_id"], 13)

            return TGResponse(False, (), {"file_path": "path"})

        mngr.request = types.MethodType(request, mngr)

        async def request_file(_, path):
            self.assertEqual(path, "path")

            return "file"

        mngr.request_file = types.MethodType(request_file, mngr)

        attachment = Attachment("photo", 13, None, None, None, None)

        file = self.loop.run_until_complete(
            env.get_file_from_attachment(attachment))

        self.assertEqual(file, "file")
Esempio n. 7
0
def test_upload_attachment_error_retry(
    mock_make_attachment,
    mock_upload_file_to_vk,
    mock_request,
):
    mock_request.side_effect = [
        {"upload_url": "_"},
        RequestException(None, None, None, {"error_code": 1}),
        {"upload_url": "_"},
        "ok",
    ]

    mock_upload_file_to_vk.side_effect = [
        "ok",
        "ok",
    ]

    mock_make_attachment.return_value = "ok"

    vkontakte = VkontakteLongpoll("token")

    result = asyncio.get_event_loop().run_until_complete(
        vkontakte.upload_attachment(Attachment.new(b""), peer_id=123)
    )

    assert result == "ok"
Esempio n. 8
0
    async def test():
        telegram = Telegram(token="token", session=aiohttp.ClientSession())
        telegram.api_messages_lock = asyncio.Lock()

        attachment = Attachment.new(b"bruh", type="location")

        with pytest.raises(ValueError):
            await telegram.execute_send(1, "", attachment, {})
Esempio n. 9
0
    def test_plugin_no_attachments_type(self):
        plugin = Plugin()

        @plugin.on_attachment("photo")
        async def _(message, env):
            return "DONE"

        wrapper = plugin._callbacks[0][1]

        attachments = [
            Attachment("audio", 0, 0, 0, 0, {}),
            Attachment("video", 0, 0, 0, 0, {})
        ]

        res = asyncio.get_event_loop().run_until_complete(
            wrapper(Message("", attachments, 0, 0, 0, {}),
                    DebugEnvironment(None, 0)))

        self.assertEqual(res, None)
Esempio n. 10
0
async def bg_loop(vk):
    while True:
        with open(get_path(__file__, "assets/pizza.png"), "rb") as fh:
            temp_a = Attachment.new(fh.read(), "pizza.png")

        a = await vk.upload_attachment(temp_a, peer_id=None)

        for sub in subscribers:
            await vk.send_message(sub, "", a)

        await asyncio.sleep(5)
Esempio n. 11
0
async def _(msg, ctx):
    # Document
    with open(get_path(__file__, "assets/pizza.png"), "rb") as fh:
        doc = Attachment.new(fh.read(), "pizza.png")

    await ctx.reply("Document", attachments=doc)

    # Graffiti (special for vk)
    with open(get_path(__file__, "assets/pizza.png"), "rb") as fh:
        graffiti = Attachment.new(fh.read(), "pizza.png", type="graffiti")

    try:
        await ctx.reply("Graffiti", attachments=graffiti)
    except ValueError:
        await ctx.reply("Can't upload this type of attachments")

    # Audio message
    with open(get_path(__file__, "assets/audio.ogg"), "rb") as fh:
        audio_message = Attachment.new(fh.read(), "audio.ogg", "voice")

    await ctx.reply("Audio message", attachments=audio_message)
Esempio n. 12
0
        async def test():
            mngr.session = aiohttp.ClientSession()

            env = VKEnvironment(mngr)

            res = await env.get_file_from_attachment(None)

            self.assertEqual(res, None)

            res = await env.get_file_from_attachment(
                Attachment("photo", 13, 1, None, None, {}))

            self.assertEqual(res, None)
Esempio n. 13
0
async def _(msg, ctx):
    files = files_find("/home/hord/Музыка/", ctx.body)

    if (len(files) == 0):
        await ctx.reply("Нет такой музыки...")

    else:
        filepath = files.pop()

        with open(get_path(__file__, filepath), "rb") as fh:
            audio_message = Attachment.new(fh.read(),
                                           os.path.basename(filepath), "voice")

        await ctx.reply(os.path.basename(filepath), attachments=audio_message)
Esempio n. 14
0
    async def test():
        # image
        attachment = Attachment.new(b"content")
        image = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert image.type == "image"
        assert image.id is not None
        assert image.file is None

        # doc with peer_id
        attachment = Attachment.new(b"content", type="doc")
        doc = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert doc.type == "doc"
        assert doc.id is not None
        assert doc.file is None

        # doc without peer_id
        attachment = Attachment.new(b"content", type="doc")
        doc = await vkontakte.upload_attachment(attachment, peer_id=None)

        assert doc.type == "doc"
        assert doc.id is not None
        assert doc.file is None

        # voice
        attachment = Attachment.new(b"content", type="voice")
        voice = await vkontakte.upload_attachment(attachment, peer_id=123)

        assert voice.type == "voice"
        assert voice.id is not None
        assert voice.file is None

        # video
        attachment = Attachment.new(b"content", type="video")
        with pytest.raises(ValueError):
            await vkontakte.upload_attachment(attachment, peer_id=123)
Esempio n. 15
0
    def test_plugin_attachments_type(self):
        plugin = Plugin()

        async def on_attachment(message, env):
            return "DONE"

        plugin.on_attachment("photo")(on_attachment)

        wrapper = plugin._callbacks[0][1]

        res = asyncio.get_event_loop().run_until_complete(
            wrapper(
                Message("text", [Attachment("photo", 0, 0, 0, 0, {})], 0, 0, 0,
                        {}), DebugEnvironment(None, 0)))

        self.assertEqual(res, "DONE")
Esempio n. 16
0
def test_execute_send_sticker():
    vkontakte = VkontakteLongpoll(token="token")

    async def req(method, kwargs):
        assert method == "messages.send"
        assert "attachment" not in kwargs
        assert kwargs["sticker_id"] == "123"
        return 1
    vkontakte._request = req

    sticker_attachment = Attachment.existing("123", "sticker")

    result = asyncio.get_event_loop().run_until_complete(
        vkontakte.execute_send(1, "text", sticker_attachment, {})
    )

    assert result == 1
Esempio n. 17
0
async def _(msg, ctx):
    messages = await extract_messages(msg, ctx)
    if not messages:
        await ctx.reply('Вы не указали сообщения для цитаты')
    else:
        user_ids = [i["from_id"] for i in messages]
        await asyncio.sleep(0)  # заставляем роботать другие процессы
        users = await get_avatars_and_names(ctx, user_ids)
        file = await make_alternate_quote(users, messages)
        if not file:
            await ctx.reply("Текста не найдено")
            return
        attach = Attachment.new(file)
        attachment = await ctx.backend.upload_attachment(
            attach, peer_id=msg.receiver_id)
        message = ""
        await ctx.reply(message, attachments=attachment)
Esempio n. 18
0
async def bg_loop(vk):
    while True:
        with open(get_path(__file__, "assets/pizza.png"), "rb") as fh:
            temp_a = Attachment.new(fh.read(), "pizza.png")

        try:
            a = await vk.upload_attachment(temp_a, peer_id=None)
        except RequestException:
            for sub in subscribers:
                await vk.send_message(sub, "Failed to upload attachment; Paused for 1 hour")

            await asyncio.sleep(60 * 60)

            continue

        for sub in subscribers:
            await vk.send_message(sub, "", a)

        await asyncio.sleep(60 * 10)
Esempio n. 19
0
def test_upload_attachment_error_no_retry(
    mock_upload_file_to_vk,
    mock_request,
):
    mock_request.side_effect = [
        {"upload_url": "_"},
        RequestException(None, None, None, {"error_code": 1}),
    ]

    mock_upload_file_to_vk.side_effect = [
        "ok",
    ]

    vkontakte = VkontakteLongpoll("token")

    with pytest.raises(RequestException):
        asyncio.get_event_loop().run_until_complete(
            vkontakte.upload_attachment(Attachment.new(b""))
        )
Esempio n. 20
0
def test_execute_send_new():
    vkontakte = VkontakteLongpoll(token="token")

    async def _upl_att(attachment, peer_id):
        return attachment._replace(id=1, raw={"ok": "ok"})
    vkontakte.upload_attachment = _upl_att

    async def req(method, kwargs):
        assert method == "messages.send"
        assert kwargs["attachment"] == "1"
        return 1
    vkontakte._request = req

    attachment = Attachment.new(b"content", "image")

    result = asyncio.get_event_loop().run_until_complete(
        vkontakte.execute_send(1, "text", attachment, {})
    )

    assert result == 1
Esempio n. 21
0
    def test_vk_manager_send_message_attachment(self):
        mngr = VKManager("token")

        attachment = Attachment("photo", 1, 0, None, None, None)

        responses = self.loop.run_until_complete(
            mngr.send_message("text for message", 0, attachment, _timeout=0))

        response = responses[0]

        self.assertTrue(response.error)
        self.assertEqual(len(mngr.requests_queue), 1)
        self.assertEqual(mngr.requests_queue[0].method, "messages.send")
        self.assertIsNotNone(mngr.requests_queue[0].kwargs.get("random_id"))
        self.assertEqual(
            mngr.requests_queue[0].kwargs, {
                "message": "text for message",
                "attachment": "photo0_1,",
                "peer_id": 0,
                "random_id": mngr.requests_queue[0].kwargs.get("random_id")
            })
Esempio n. 22
0
async def __(msg, ctx):
    with open(get_path(__file__, "assets/pizza.png"), "rb") as fh:
        image = Attachment.new(fh.read(), "pizza.png")

    await ctx.reply("", attachments=image)