Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Bot API 8.0: Add Bot.set_user_emoji_status #4572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 28, 2024

Conversation

Bibo-Joshi
Copy link
Member

No description provided.

@Bibo-Joshi Bibo-Joshi added the ⚙️ bot-api affected functionality: bot-api label Nov 24, 2024
@Bibo-Joshi Bibo-Joshi mentioned this pull request Nov 24, 2024
42 tasks
@Bibo-Joshi Bibo-Joshi changed the title Add Bot.set_user_emoji_status Bot API 8.0: Add Bot.set_user_emoji_status Nov 24, 2024
Copy link

codecov bot commented Nov 28, 2024

❌ 2 Tests Failed:

Tests completed Failed Passed Skipped
6036 2 6034 268
View the top 2 failed tests by shortest run time
tests.ext.test_updater.TestUpdater::test_webhook_basic[None-None-False-True]
Stack Traces | 0.126s run time
self = <tests.ext.test_updater.TestUpdater object at 0x000002D56DB42C90>
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x000002D570BB3B50>
updater = Updater[bot=PytestExtBot[token=690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To]]
drop_pending_updates = False, ext_bot = True, secret_token = None, unix = None
file_path = 'D:\\a\\python-telegram-bot\\python-telegram-bot\\tests\\data\\test.sock'
one_time_bot = PytestExtBot[token=690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To]
one_time_raw_bot = PytestBot[token=690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To]

    @pytest.mark.parametrize("ext_bot", [True, False])
    @pytest.mark.parametrize("drop_pending_updates", [True, False])
    @pytest.mark.parametrize("secret_token", ["SecretToken", None])
    @pytest.mark.parametrize(
        "unix", [None, "file_path", "socket_object"] if UNIX_AVAILABLE else [None]
    )
    async def test_webhook_basic(
        self,
        monkeypatch,
        updater,
        drop_pending_updates,
        ext_bot,
        secret_token,
        unix,
        file_path,
        one_time_bot,
        one_time_raw_bot,
    ):
        # Testing with both ExtBot and Bot to make sure any logic in WebhookHandler
        # that depends on this distinction works
        if ext_bot and not isinstance(updater.bot, ExtBot):
            updater.bot = one_time_bot
        if not ext_bot and type(updater.bot) is not Bot:
            updater.bot = one_time_raw_bot
    
        async def delete_webhook(*args, **kwargs):
            # Dropping pending updates is done by passing the parameter to delete_webhook
            if kwargs.get("drop_pending_updates"):
                self.message_count += 1
            return True
    
        monkeypatch.setattr(updater.bot, "set_webhook", return_true)
        monkeypatch.setattr(updater.bot, "delete_webhook", delete_webhook)
    
        ip = "127.0.0.1"
        port = randrange(1024, 49152)  # Select random port
    
        async with updater:
            if unix:
                socket = file_path if unix == "file_path" else bind_unix_socket(file_path)
                return_value = await updater.start_webhook(
                    drop_pending_updates=drop_pending_updates,
                    secret_token=secret_token,
                    url_path="TOKEN",
                    unix=socket,
                    webhook_url="string",
                )
            else:
>               return_value = await updater.start_webhook(
                    drop_pending_updates=drop_pending_updates,
                    ip_address=ip,
                    port=port,
                    url_path="TOKEN",
                    secret_token=secret_token,
                    webhook_url="string",
                )

tests\ext\test_updater.py:741: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
telegram\ext\_updater.py:594: in start_webhook
    await self._start_webhook(
telegram\ext\_updater.py:686: in _start_webhook
    await self._httpd.serve_forever(ready=ready)
telegram\ext\_utils\webhookhandler.py:92: in serve_forever
    self._http_server.listen(self.port, address=self.listen)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\tornado\tcpserver.py:183: in listen
    sockets = bind_sockets(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

port = 1801, address = '127.0.0.1', family = <AddressFamily.AF_UNSPEC: 0>
backlog = 128, flags = <AddressInfo.AI_PASSIVE: 1>, reuse_port = False

    def bind_sockets(
        port: int,
        address: Optional[str] = None,
        family: socket.AddressFamily = socket.AF_UNSPEC,
        backlog: int = _DEFAULT_BACKLOG,
        flags: Optional[int] = None,
        reuse_port: bool = False,
    ) -> List[socket.socket]:
        """Creates listening sockets bound to the given port and address.
    
        Returns a list of socket objects (multiple sockets are returned if
        the given address maps to multiple IP addresses, which is most common
        for mixed IPv4 and IPv6 use).
    
        Address may be either an IP address or hostname.  If it's a hostname,
        the server will listen on all IP addresses associated with the
        name.  Address may be an empty string or None to listen on all
        available interfaces.  Family may be set to either `socket.AF_INET`
        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
        both will be used if available.
    
        The ``backlog`` argument has the same meaning as for
        `socket.listen() <socket.socket.listen>`.
    
        ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
        ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
    
        ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket
        in the list. If your platform doesn't support this option ValueError will
        be raised.
        """
        if reuse_port and not hasattr(socket, "SO_REUSEPORT"):
            raise ValueError("the platform doesn't support SO_REUSEPORT")
    
        sockets = []
        if address == "":
            address = None
        if not socket.has_ipv6 and family == socket.AF_UNSPEC:
            # Python can be compiled with --disable-ipv6, which causes
            # operations on AF_INET6 sockets to fail, but does not
            # automatically exclude those results from getaddrinfo
            # results.
            # http://bugs.python.org/issue16208
            family = socket.AF_INET
        if flags is None:
            flags = socket.AI_PASSIVE
        bound_port = None
        unique_addresses = set()  # type: set
        for res in sorted(
            socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),
            key=lambda x: x[0],
        ):
            if res in unique_addresses:
                continue
    
            unique_addresses.add(res)
    
            af, socktype, proto, canonname, sockaddr = res
            if (
                sys.platform == "darwin"
                and address == "localhost"
                and af == socket.AF_INET6
                and sockaddr[3] != 0  # type: ignore
            ):
                # Mac OS X includes a link-local address fe80::1%lo0 in the
                # getaddrinfo results for 'localhost'.  However, the firewall
                # doesn't understand that this is a local address and will
                # prompt for access (often repeatedly, due to an apparent
                # bug in its ability to remember granting access to an
                # application). Skip these addresses.
                continue
            try:
                sock = socket.socket(af, socktype, proto)
            except socket.error as e:
                if errno_from_exception(e) == errno.EAFNOSUPPORT:
                    continue
                raise
            if os.name != "nt":
                try:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                except socket.error as e:
                    if errno_from_exception(e) != errno.ENOPROTOOPT:
                        # Hurd doesn't support SO_REUSEADDR.
                        raise
            if reuse_port:
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            if af == socket.AF_INET6:
                # On linux, ipv6 sockets accept ipv4 too by default,
                # but this makes it impossible to bind to both
                # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,
                # separate sockets *must* be used to listen for both ipv4
                # and ipv6.  For consistency, always disable ipv4 on our
                # ipv6 sockets and use a separate ipv4 socket when needed.
                #
                # Python 2.x on windows doesn't have IPPROTO_IPV6.
                if hasattr(socket, "IPPROTO_IPV6"):
                    sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
    
            # automatic port allocation with port=None
            # should bind on the same port on IPv4 and IPv6
            host, requested_port = sockaddr[:2]
            if requested_port == 0 and bound_port is not None:
                sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))
    
            sock.setblocking(False)
            try:
>               sock.bind(sockaddr)
E               PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\tornado\netutil.py:162: PermissionError
tests.ext.test_conversationhandler.TestConversationHandler::test_no_running_job_queue_warning[False]
Stack Traces | 5.99s run time
@contextlib.contextmanager
    def map_httpcore_exceptions() -> typing.Iterator[None]:
        global HTTPCORE_EXC_MAP
        if len(HTTPCORE_EXC_MAP) == 0:
            HTTPCORE_EXC_MAP = _load_httpcore_exceptions()
        try:
>           yield

C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_transports\default.py:101: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_transports\default.py:394: in handle_async_request
    resp = await self._pool.handle_async_request(req)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_async\connection_pool.py:256: in handle_async_request
    raise exc from None
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_async\connection_pool.py:236: in handle_async_request
    response = await connection.handle_async_request(
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_async\connection.py:101: in handle_async_request
    raise exc
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_async\connection.py:78: in handle_async_request
    stream = await self._connect(request)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_async\connection.py:124: in _connect
    stream = await self._network_backend.connect_tcp(**kwargs)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_backends\auto.py:31: in connect_tcp
    return await self._backend.connect_tcp(
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_backends\anyio.py:113: in connect_tcp
    with map_exceptions(exc_map):
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\contextlib.py:158: in __exit__
    self.gen.throw(typ, value, traceback)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

map = {<class 'TimeoutError'>: <class 'httpcore.ConnectTimeout'>, <class 'OSError'>: <class 'httpcore.ConnectError'>, <class 'anyio.BrokenResourceError'>: <class 'httpcore.ConnectError'>}

    @contextlib.contextmanager
    def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]:
        try:
            yield
        except Exception as exc:  # noqa: PIE786
            for from_exc, to_exc in map.items():
                if isinstance(exc, from_exc):
>                   raise to_exc(exc) from exc
E                   httpcore.ConnectTimeout

C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpcore\_exceptions.py:14: ConnectTimeout

The above exception was the direct cause of the following exception:

self = <telegram.request._httpxrequest.HTTPXRequest object at 0x000002D56FC49C70>
url = 'https://api.telegram.org/bot690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To/getMe'
method = 'POST'
request_data = <telegram.request._requestdata.RequestData object at 0x000002D56FAF8580>
read_timeout = 5.0, write_timeout = 5.0, connect_timeout = 5.0
pool_timeout = 1.0

    async def do_request(
        self,
        url: str,
        method: str,
        request_data: Optional[RequestData] = None,
        read_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
        write_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
        connect_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
        pool_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
    ) -> tuple[int, bytes]:
        """See :meth:`BaseRequest.do_request`."""
        if self._client.is_closed:
            raise RuntimeError("This HTTPXRequest is not initialized!")
    
        files = request_data.multipart_data if request_data else None
        data = request_data.json_parameters if request_data else None
    
        # If user did not specify timeouts (for e.g. in a bot method), use the default ones when we
        # created this instance.
        if isinstance(read_timeout, DefaultValue):
            read_timeout = self._client.timeout.read
        if isinstance(connect_timeout, DefaultValue):
            connect_timeout = self._client.timeout.connect
        if isinstance(pool_timeout, DefaultValue):
            pool_timeout = self._client.timeout.pool
    
        if isinstance(write_timeout, DefaultValue):
            write_timeout = self._client.timeout.write if not files else self._media_write_timeout
    
        timeout = httpx.Timeout(
            connect=connect_timeout,
            read=read_timeout,
            write=write_timeout,
            pool=pool_timeout,
        )
    
        try:
>           res = await self._client.request(
                method=method,
                url=url,
                headers={"User-Agent": self.USER_AGENT},
                timeout=timeout,
                files=files,
                data=data,
            )

telegram\request\_httpxrequest.py:293: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_client.py:1542: in request
    return await self.send(request, auth=auth, follow_redirects=follow_redirects)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_client.py:1631: in send
    response = await self._send_handling_auth(
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_client.py:1659: in _send_handling_auth
    response = await self._send_handling_redirects(
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_client.py:1696: in _send_handling_redirects
    response = await self._send_single_request(request)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_client.py:1732: in _send_single_request
    response = await transport.handle_async_request(request)
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_transports\default.py:393: in handle_async_request
    with map_httpcore_exceptions():
C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\contextlib.py:158: in __exit__
    self.gen.throw(typ, value, traceback)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    @contextlib.contextmanager
    def map_httpcore_exceptions() -> typing.Iterator[None]:
        global HTTPCORE_EXC_MAP
        if len(HTTPCORE_EXC_MAP) == 0:
            HTTPCORE_EXC_MAP = _load_httpcore_exceptions()
        try:
            yield
        except Exception as exc:
            mapped_exc = None
    
            for from_exc, to_exc in HTTPCORE_EXC_MAP.items():
                if not isinstance(exc, from_exc):
                    continue
                # We want to map to the most specific exception we can find.
                # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to
                # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.
                if mapped_exc is None or issubclass(to_exc, mapped_exc):
                    mapped_exc = to_exc
    
            if mapped_exc is None:  # pragma: no cover
                raise
    
            message = str(exc)
>           raise mapped_exc(message) from exc
E           httpx.ConnectTimeout

C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\httpx\_transports\default.py:118: ConnectTimeout

The above exception was the direct cause of the following exception:

self = <tests.ext.test_conversationhandler.TestConversationHandler object at 0x000002D56D837110>
app = Application[bot=ExtBot[token=690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To]]
bot = PytestExtBot[token=690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To]
user1 = User(first_name='Misses Test', id=123, is_bot=False)
recwarn = WarningsRecorder(record=True), jq = False

    @pytest.mark.parametrize("jq", [True, False])
    async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq):
        handler = ConversationHandler(
            entry_points=self.entry_points,
            states=self.states,
            fallbacks=self.fallbacks,
            conversation_timeout=0.5,
        )
        if not jq:
            app = ApplicationBuilder().token(bot.token).job_queue(None).build()
        app.add_handler(handler)
    
        message = Message(
            0,
            None,
            self.group,
            from_user=user1,
            text="/start",
            entities=[
                MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
            ],
        )
        message.set_bot(bot)
        message._unfreeze()
        message.entities[0]._unfreeze()
    
>       async with app:

tests\ext\test_conversationhandler.py:1092: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
telegram\ext\_application.py:370: in __aenter__
    await self.initialize()
telegram\ext\_application.py:487: in initialize
    await self.bot.initialize()
telegram\ext\_extbot.py:297: in initialize
    await super().initialize()
telegram\_bot.py:761: in initialize
    await self.get_me()
telegram\ext\_extbot.py:1924: in get_me
    return await super().get_me(
telegram\_bot.py:893: in get_me
    result = await self._post(
telegram\_bot.py:617: in _post
    return await self._do_post(
telegram\ext\_extbot.py:351: in _do_post
    return await super()._do_post(
telegram\_bot.py:646: in _do_post
    result = await request.post(
telegram\request\_baserequest.py:202: in post
    result = await self._request_wrapper(
telegram\request\_baserequest.py:334: in _request_wrapper
    code, payload = await self.do_request(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <telegram.request._httpxrequest.HTTPXRequest object at 0x000002D56FC49C70>
url = 'https://api.telegram.org/bot690091347:AAFLmR5pAB5Ycpe_mOh7zM4JFBOh0z3T0To/getMe'
method = 'POST'
request_data = <telegram.request._requestdata.RequestData object at 0x000002D56FAF8580>
read_timeout = 5.0, write_timeout = 5.0, connect_timeout = 5.0
pool_timeout = 1.0

    async def do_request(
        self,
        url: str,
        method: str,
        request_data: Optional[RequestData] = None,
        read_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
        write_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
        connect_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
        pool_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE,
    ) -> tuple[int, bytes]:
        """See :meth:`BaseRequest.do_request`."""
        if self._client.is_closed:
            raise RuntimeError("This HTTPXRequest is not initialized!")
    
        files = request_data.multipart_data if request_data else None
        data = request_data.json_parameters if request_data else None
    
        # If user did not specify timeouts (for e.g. in a bot method), use the default ones when we
        # created this instance.
        if isinstance(read_timeout, DefaultValue):
            read_timeout = self._client.timeout.read
        if isinstance(connect_timeout, DefaultValue):
            connect_timeout = self._client.timeout.connect
        if isinstance(pool_timeout, DefaultValue):
            pool_timeout = self._client.timeout.pool
    
        if isinstance(write_timeout, DefaultValue):
            write_timeout = self._client.timeout.write if not files else self._media_write_timeout
    
        timeout = httpx.Timeout(
            connect=connect_timeout,
            read=read_timeout,
            write=write_timeout,
            pool=pool_timeout,
        )
    
        try:
            res = await self._client.request(
                method=method,
                url=url,
                headers={"User-Agent": self.USER_AGENT},
                timeout=timeout,
                files=files,
                data=data,
            )
        except httpx.TimeoutException as err:
            if isinstance(err, httpx.PoolTimeout):
                raise TimedOut(
                    message=(
                        "Pool timeout: All connections in the connection pool are occupied. "
                        "Request was *not* sent to Telegram. Consider adjusting the connection "
                        "pool size or the pool timeout."
                    )
                ) from err
>           raise TimedOut from err
E           telegram.error.TimedOut: Timed out

telegram\request\_httpxrequest.py:310: TimedOut

To view more test analytics, go to the Test Analytics Dashboard
📢 Thoughts on this report? Let us know!

@Bibo-Joshi Bibo-Joshi merged commit 59aabc7 into api-8.0 Nov 28, 2024
19 of 21 checks passed
@Bibo-Joshi Bibo-Joshi deleted the api-8.0-set-user-emoji-status branch November 28, 2024 18:45
@Bibo-Joshi Bibo-Joshi mentioned this pull request Nov 28, 2024
30 tasks
Copy link
Member

@Poolitzer Poolitzer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. What a method...

@github-actions github-actions bot locked and limited conversation to collaborators Dec 8, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
⚙️ bot-api affected functionality: bot-api
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants