当前位置: 首页>>代码示例>>Python>>正文


Python telegram.Update类代码示例

本文整理汇总了Python中telegram.Update的典型用法代码示例。如果您正苦于以下问题:Python Update类的具体用法?Python Update怎么用?Python Update使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Update类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_webhook

    def test_webhook(self):
        print('Testing Webhook')
        self._setup_updater('', messages=0)
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(
            self.telegramHandlerTest)

        # Select random port for travis
        port = randrange(1024, 49152)
        self.updater.start_webhook('127.0.0.1', port,
                                   url_path='TOKEN',
                                   cert='./tests/test_updater.py',
                                   key='./tests/test_updater.py')
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester"), datetime.now(),
                          Chat(1, "group", title="Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        try:
            payload = bytes(update.to_json(), encoding='utf-8')
        except TypeError:
            payload = bytes(update.to_json())

        header = {
            'content-type': 'application/json',
            'content-length': str(len(payload))
        }

        r = Request('http://127.0.0.1:%d/TOKEN' % port,
                    data=payload,
                    headers=header)

        urlopen(r)

        sleep(1)
        self.assertEqual(self.received_message, 'Webhook Test')

        print("Test other webhook server functionalities...")
        request = Request('http://localhost:%d/webookhandler.py' % port)
        response = urlopen(request)
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        request.get_method = lambda: 'HEAD'

        response = urlopen(request)
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        # Test multiple shutdown() calls
        self.updater.httpd.shutdown()
        self.updater.httpd.shutdown()
        self.assertTrue(True)
开发者ID:azigran,项目名称:python-telegram-bot,代码行数:60,代码来源:test_updater.py

示例2: test_webhook_no_ssl

    def test_webhook_no_ssl(self):
        print("Testing Webhook without SSL")
        bot = MockBot("", messages=0)
        self.updater.bot = bot
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(self.telegramHandlerTest)

        # Select random port for travis
        port = randrange(1024, 49152)
        self.updater.start_webhook("127.0.0.1", port)
        sleep(0.5)

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester 2"), datetime.now(), GroupChat(1, "Test Group 2"))

        message.text = "Webhook Test 2"
        update = Update(1)
        update.message = message

        try:
            payload = bytes(update.to_json(), encoding="utf-8")
        except TypeError:
            payload = bytes(update.to_json())

        header = {"content-type": "application/json", "content-length": str(len(payload))}

        r = Request("http://127.0.0.1:%d/" % port, data=payload, headers=header)

        urlopen(r)
        sleep(1)
        self.assertEqual(self.received_message, "Webhook Test 2")
开发者ID:gisho,项目名称:python-telegram-bot,代码行数:31,代码来源:test_updater.py

示例3: test_authorized_only_exception

def test_authorized_only_exception(default_conf, mocker):
    mocker.patch.dict('freqtrade.rpc.telegram._CONF', default_conf)

    update = Update(randint(1, 100))
    update.message = Message(randint(1, 100), 0, datetime.utcnow(), Chat(0, 0))

    @authorized_only
    def dummy_handler(*args, **kwargs) -> None:
        raise Exception('test')

    dummy_handler(MagicMock(), update)
开发者ID:enenn,项目名称:freqtrade,代码行数:11,代码来源:test_rpc_telegram.py

示例4: mock_update

    def mock_update(self, text):
        message = Message(0, User(0, 'Testuser'), None, Chat(0, Chat.GROUP), bot=self)
        message.text = text
        update = Update(0)

        if self.edited:
            update.edited_message = message
        else:
            update.message = message

        return update
开发者ID:KenOokamiHoro,项目名称:python-telegram-bot,代码行数:11,代码来源:test_updater.py

示例5: mockUpdate

    def mockUpdate(self, text):
        message = Message(0, None, None, None)
        message.text = text
        update = Update(0)

        if self.edited:
            update.edited_message = message
        else:
            update.message = message

        return update
开发者ID:Clifford-Beta,项目名称:python-telegram-bot,代码行数:11,代码来源:test_updater.py

示例6: test_webhook

    def test_webhook(self):
        print("Testing Webhook")
        bot = MockBot("", messages=0)
        self.updater.bot = bot
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(self.telegramHandlerTest)

        # Select random port for travis
        port = randrange(1024, 49152)
        self.updater.start_webhook(
            "127.0.0.1", port, url_path="TOKEN", cert="./tests/test_updater.py", key="./tests/test_updater.py"
        )
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester"), datetime.now(), GroupChat(1, "Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        try:
            payload = bytes(update.to_json(), encoding="utf-8")
        except TypeError:
            payload = bytes(update.to_json())

        header = {"content-type": "application/json", "content-length": str(len(payload))}

        r = Request("http://127.0.0.1:%d/TOKEN" % port, data=payload, headers=header)

        urlopen(r)

        sleep(1)
        self.assertEqual(self.received_message, "Webhook Test")

        print("Test other webhook server functionalities...")
        request = Request("http://localhost:%d/webookhandler.py" % port)
        response = urlopen(request)
        self.assertEqual(b"", response.read())
        self.assertEqual(200, response.code)

        request.get_method = lambda: "HEAD"

        response = urlopen(request)
        self.assertEqual(b"", response.read())
        self.assertEqual(200, response.code)

        # Test multiple shutdown() calls
        self.updater.httpd.shutdown()
        self.updater.httpd.shutdown()
        self.assertTrue(True)
开发者ID:gisho,项目名称:python-telegram-bot,代码行数:53,代码来源:test_updater.py

示例7: test_authorized_only_unauthorized

def test_authorized_only_unauthorized(default_conf, mocker):
    mocker.patch.dict('freqtrade.rpc.telegram._CONF', default_conf)

    chat = Chat(0xdeadbeef, 0)
    update = Update(randint(1, 100))
    update.message = Message(randint(1, 100), 0, datetime.utcnow(), chat)
    state = {'called': False}

    @authorized_only
    def dummy_handler(*args, **kwargs) -> None:
        state['called'] = True

    dummy_handler(MagicMock(), update)
    assert state['called'] is False
开发者ID:enenn,项目名称:freqtrade,代码行数:14,代码来源:test_rpc_telegram.py

示例8: test_webhook

    def test_webhook(self):
        self._setup_updater('', messages=0)
        d = self.updater.dispatcher
        handler = MessageHandler([], self.telegramHandlerTest)
        d.addHandler(handler)

        ip = '127.0.0.1'
        port = randrange(1024, 49152)  # Select random port for travis
        self.updater.start_webhook(ip,
                                   port,
                                   url_path='TOKEN',
                                   cert='./tests/test_updater.py',
                                   key='./tests/test_updater.py',
                                   webhook_url=None)
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1,
                          User(1, "Tester"),
                          datetime.now(),
                          Chat(1, "group", title="Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN')

        sleep(1)
        self.assertEqual(self.received_message, 'Webhook Test')

        print("Test other webhook server functionalities...")
        response = self._send_webhook_msg(ip, port, None, 'webookhandler.py')
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        response = self._send_webhook_msg(
            ip, port,
            None, 'webookhandler.py',
            get_method=lambda: 'HEAD')

        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        # Test multiple shutdown() calls
        self.updater.httpd.shutdown()
        self.updater.httpd.shutdown()
        self.assertTrue(True)
开发者ID:Gurzo,项目名称:python-telegram-bot,代码行数:50,代码来源:test_updater.py

示例9: test_webhook_no_ssl

    def test_webhook_no_ssl(self, monkeypatch, updater):
        q = Queue()
        monkeypatch.setattr('telegram.Bot.set_webhook', lambda *args, **kwargs: True)
        monkeypatch.setattr('telegram.Bot.delete_webhook', lambda *args, **kwargs: True)
        monkeypatch.setattr('telegram.ext.Dispatcher.process_update', lambda _, u: q.put(u))

        ip = '127.0.0.1'
        port = randrange(1024, 49152)  # Select random port for travis
        updater.start_webhook(ip, port, webhook_url=None)
        sleep(.2)

        # Now, we send an update to the server via urlopen
        update = Update(1, message=Message(1, User(1, '', False), None, Chat(1, ''), text='Webhook 2'))
        self._send_webhook_msg(ip, port, update.to_json())
        sleep(.2)
        assert q.get(False) == update
开发者ID:ferisystem,项目名称:python-telegram-bot,代码行数:16,代码来源:test_updater.py

示例10: getUpdates

    def getUpdates(self, offset=None, limit=100, timeout=0):
        """Use this method to receive incoming updates using long polling.

        Args:
          offset:
            Identifier of the first update to be returned. Must be greater by
            one than the highest among the identifiers of previously received
            updates. By default, updates starting with the earliest unconfirmed
            update are returned. An update is considered confirmed as soon as
            getUpdates is called with an offset higher than its update_id.
          limit:
            Limits the number of updates to be retrieved. Values between 1—100
            are accepted. Defaults to 100.
          timeout:
            Timeout in seconds for long polling. Defaults to 0, i.e. usual
            short polling.

        Returns:
          A list of telegram.Update objects are returned.
        """

        url = "%s/getUpdates" % (self.base_url)

        data = {}
        if offset:
            data["offset"] = offset
        if limit:
            data["limit"] = limit
        if timeout:
            data["timeout"] = timeout

        json_data = self._requestUrl(url, "POST", data=data)
        data = self._parseAndCheckTelegram(json_data)

        return [Update.de_json(x) for x in data]
开发者ID:Avanatiker,项目名称:python-telegram-bot,代码行数:35,代码来源:bot.py

示例11: post

    def post(self, request, token):
        dispatcher = self.get_dispatcher(token)
        if not dispatcher:
            return Http404()

        json_string = request.body.decode('utf-8')
        update = Update.de_json(json.loads(json_string))
        dispatcher.process_update(update)
        return HttpResponse()
开发者ID:ebertti,项目名称:python-telegram-bot,代码行数:9,代码来源:django.py

示例12: __init__

 def __init__(self):
     update = Update.de_json(request.get_json(force=True))
     if getattr(update, 'message', None):
         for t, c in self.types.items():
             if getattr(update.message, t):
                 m = c()
                 m.update = update
                 m.parse()
                 m.run()
                 m.respond()
开发者ID:ZUNbado,项目名称:gallerybot,代码行数:10,代码来源:webhook.py

示例13: getUpdates

    def getUpdates(self,
                   offset=None,
                   limit=100,
                   timeout=0,
                   network_delay=.2):
        """Use this method to receive incoming updates using long polling.

        Args:
          offset:
            Identifier of the first update to be returned. Must be greater by
            one than the highest among the identifiers of previously received
            updates. By default, updates starting with the earliest unconfirmed
            update are returned. An update is considered confirmed as soon as
            getUpdates is called with an offset higher than its update_id.
          limit:
            Limits the number of updates to be retrieved. Values between 1-100
            are accepted. Defaults to 100.
          timeout:
            Timeout in seconds for long polling. Defaults to 0, i.e. usual
            short polling.
          network_delay:
            Additional timeout in seconds to allow the response from Telegram
            to take some time when using long polling. Defaults to 2, which
            should be enough for most connections. Increase it if it takes very
            long for data to be transmitted from and to the Telegram servers.

        Returns:
            list[:class:`telegram.Update`]: A list of :class:`telegram.Update`
            objects are returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getUpdates'.format(self.base_url)

        data = {'timeout': timeout}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        urlopen_timeout = timeout + network_delay

        result = request.post(url, data, timeout=urlopen_timeout)

        if result:
            self.logger.debug(
                'Getting updates: %s', [u['update_id'] for u in result])
        else:
            self.logger.debug('No new updates found.')

        return [Update.de_json(x) for x in result]
开发者ID:Gurzo,项目名称:python-telegram-bot,代码行数:55,代码来源:bot.py

示例14: test_webhook

    def test_webhook(self, monkeypatch, updater):
        q = Queue()
        monkeypatch.setattr('telegram.Bot.set_webhook', lambda *args, **kwargs: True)
        monkeypatch.setattr('telegram.Bot.delete_webhook', lambda *args, **kwargs: True)
        monkeypatch.setattr('telegram.ext.Dispatcher.process_update', lambda _, u: q.put(u))

        ip = '127.0.0.1'
        port = randrange(1024, 49152)  # Select random port for travis
        updater.start_webhook(
            ip,
            port,
            url_path='TOKEN',
            cert='./tests/test_updater.py',
            key='./tests/test_updater.py', )
        sleep(.2)
        # SSL-Wrapping will fail, so we start the server without SSL
        thr = Thread(target=updater.httpd.serve_forever)
        thr.start()

        try:
            # Now, we send an update to the server via urlopen
            update = Update(1, message=Message(1, User(1, '', False), None, Chat(1, ''),
                                               text='Webhook'))
            self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN')
            sleep(.2)
            assert q.get(False) == update

            response = self._send_webhook_msg(ip, port, None, 'webookhandler.py')
            assert b'' == response.read()
            assert 200 == response.code

            response = self._send_webhook_msg(ip, port, None, 'webookhandler.py',
                                              get_method=lambda: 'HEAD')

            assert b'' == response.read()
            assert 200 == response.code

            # Test multiple shutdown() calls
            updater.httpd.shutdown()
        finally:
            updater.httpd.shutdown()
            thr.join()
开发者ID:technoekat,项目名称:prodeda1,代码行数:42,代码来源:test_updater.py

示例15: webhook

def webhook():
    if request.method == "POST":
        # retrieve the message in JSON and then transform it to Telegram object
        update = Update.de_json(request.get_json(force=True))

        logger.info("Update received! "+ update.message.text)
        dp.process_update(update)
        update_queue.put(update)
        return "OK"
    else:
        return redirect("https://telegram.me/links_forward_bot", code=302)
开发者ID:gaiar,项目名称:pocket-telegram-bot,代码行数:11,代码来源:forwardbot.py


注:本文中的telegram.Update类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。